Define your own environments in LaTeX (newenvironment)

\newenvironment{name}{begin code}{end code} defines an environment. The first block of code runs at \begin{name}, the second at \end{name}.

A simple environment

This environment prints a bold label and sets its content in italics. Font changes made inside an environment end with it.

\newenvironment{remark}
  {\par\medskip\noindent\textbf{Remark.}\itshape}
  {\par\medskip}

\begin{remark}
The result also holds for negative values.
\end{remark}
Result
The compiled example

Open in the editor

An environment with an argument

The number in brackets is the number of arguments. They follow \begin{name} in braces and are available as #1, #2 in the begin code.

\newenvironment{task}[1]
  {\par\medskip\noindent\textbf{Task #1.}}
  {\par\medskip}

\begin{task}{3}
Calculate the area of a circle with a radius of 2 cm.
\end{task}
Result
The compiled example

Open in the editor

An optional argument

A second pair of brackets makes the first argument optional and sets its default, as with \newcommand. \ignorespaces at the end of the begin code drops the space from the line end after \begin{hint}, so the text starts at the same distance with and without the optional argument.

\newenvironment{hint}[1][Hint]
  {\begin{quote}\textbf{#1:}\ \ignorespaces}
  {\end{quote}}

\begin{hint}
Use the chain rule.
\end{hint}

\begin{hint}[Warning]
The function is not defined at zero.
\end{hint}
Result
The compiled example

Open in the editor

Use an argument in the end code

With \newenvironment, #1 is not allowed in the end code. \NewDocumentEnvironment allows it; its second argument describes the arguments with letters, here m for one mandatory argument.

\NewDocumentEnvironment{saying}{m}
  {\begin{quote}\itshape}
  {\par\hfill\upshape--- #1\end{quote}}

\begin{saying}{English proverb}
A stitch in time saves nine.
\end{saying}
Result
The compiled example

Open in the editor

Pitfalls

Compiled with pdfLaTeX from TeX Live 2023.

Related pages