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}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}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}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}Pitfalls
#1in the end code of\newenvironmentstops with "Illegal parameter number in definition of", see Illegal parameter number in definition of \pair.\newenvironment{name}creates the commands\nameand\endname. If one of them exists, LaTeX stops with "Command \name already defined";\renewenvironmentreplaces an existing environment.- For numbered theorems, definitions and examples, use
\newtheorem, see Theorems, lemmas and proofs in LaTeX.
Compiled with pdfLaTeX from TeX Live 2023.