[Tex/LaTex] Duplicating Environments

environmentsmacros

When I want to globally modify a command in my document, I will often use a duplicated version of the original in the stencil, with the help of the \let macro. For example, if I wanted to do something every time I created a section, I might say:

\let\svsection\section
\renewcommand\section[1]{\mychanges\svsection{#1}}

It just dawned on me that I don't know how or if something similar can be done for environments. What I would hope for is something like (I'm omitting arguments for the sake of simplicity, don't focus on that):

\let\svfigure\figure
\renewenvironment{figure}{\blahblah\begin{svfigure}}
                         {\end{svfigure}\moreblah}

Of course, this syntax won't work because \figure isn't a command.

But, I was hoping that the creation of environment abc would always be accompanied by the creation of associated constructed commands, for example, \start@abc and \end@abc, such that these associated commands could be \let to duplicate the original environment.

I also realize that one approach may be to "patch" the original environment, but I don't think that is really what I'm asking, since I'm not sure a patch can be easily undone, whereas redoing a \let in the opposite direction (e.g., \let\section\svsection) will totally undo the effects of redefinition.

It would be a handy feature to know how to duplicate an environment, so that the original copy can be \renewed in the fashion I describe.

Best Answer

When you define an environment with

\newenvironment{foo}[1]{start code with #1}{end code}

what happens internally (after some checking for optional arguments, testing if the environment exists, and taking care of a possible star argument to \newenvironment) essentially boils down to

\newcommand\foo[1]{start code with #1}% actually \new@command
\def\endfoo{end code}

This means if the environment has no optional arguments

\let\myfoo\foo
\let\endmyfoo\endfoo

copies the environment {foo} as environment {myfoo}. (If it has an optional argument \LetLtxMacro should be used instead of \let, see When to use \LetLtxMacro?.)

In the article class the {figure} environment is defined as

\newenvironment{figure}
               {\@float{figure}}
               {\end@float}

so saying

\let\myfigure\figure
\let\endmyfigure\endfigure

works:

\documentclass{article}
\newenvironment{foo}[1]{start foo with (#1)}{end foo}

\let\myfoo\foo
\let\endmyfoo\endfoo

\let\myfigure\figure
\let\endmyfigure\endfigure

\begin{document}

\begin{myfoo}{arg}
  bar
\end{myfoo}

\begin{myfigure}
  copied figure
  \caption{my figure}
\end{myfigure}

\end{document}

enter image description here

Some environments like {verbatim} or AMSmath's {align} cannot be copied this way since they need to find \end{verbatim} or \end{align}, respectively, exactly.

Related Question