20

Do you know how LaTeX implements environments? To be more precise, what does

\newenvironment{<env-name>}[<n-args>][<default>]{<begin-code>}{<end-code>}

in terms of TeX commands (i.e., how is the LaTeX command \newenvironment defined in TeX)?

1

1 Answer 1

27

The command \newenvironment{<env-name>}[<n-args>][<default>]{<begin-code>}{<end-code>} is equivalent to:

\newcommand{\<env-name>}[<n-args>][<default>]{<begin-code>}
\newcommand{\end<env-name>}{<end-code>}

The reason is that \begin{<env-name>}...\end{<env-name>} is transferred into

<check whether the command \<env-name> exists
\begingroup
\csname <env-name>\endcsname % this is a way to call macro \<env-name> by its name
...
<check whether the inner-most environment is really <env-name>
\csname end<env-name>\endcsname % calls \end<env-name>
\endgroup

The problem is that you cannot do \newcommand{\#1}... so the command \csname...\endcsname is actually used by \newenvironment to overcome this problem.

The exact definition of \newenvironment is very complicated since the presence of * (that indicate the environment to be defined without \long), presence of [<n-args>] and [<default>] has to be tested, which in the terms of LaTeX means a lot of inner macros. To explore the details, you can run the following short source code that shows the macro definitions:

\documentclass{article}
\begin{document}
\parindent0pt
\parskip2ex
\makeatletter
\ttfamily
\meaning\newenvironment   % <-- put any macro name here
\par
\meaning\newcommand   % <-- put any macro name here
\makeatother
\end{document}
2
  • 1
    Should "transferred into" be "expanded into"? Aug 11, 2019 at 15:20
  • Remark: \begin{X} is expanded/executed strictly before \end{X}, and in some special cases (verbatim environment for example) \end{X} is read as-is without any expansion, and the begin command (macro) uses it to delimit the end of the environment.
    – user202729
    Nov 14, 2021 at 6:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .