[Tex/LaTex] Command behavior depending on current environment

conditionalsenvironmentsmacros

I would like to write a LaTeX macro whose code depends on the parent environment such as:

\newcommand\test{
%if current_environment=env1
test1
%elseif current_environment=env2
test2
%else
}

\begin{env1}
\test %output test1
\end{env1}


\begin{env2}
\test %output test2
\end{env2}

\test %output nothing

Any idea?

Best Answer

The current name of the environment is saved in the macro \@currenvir.

In the example below is defined a new test named \ifenv. The syntax of the command is:

\ifenv{environment name}{TRUE}{FALSE}

\ifenv test whether the name of the current environment is equal to the input or not. Depending of the result the true or false part will be used.

\documentclass{article}

\makeatletter
\def\ifenv#1{
   \def\@tempa{#1}%
   \ifx\@tempa\@currenvir
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
   \fi
}
\makeatother
\newenvironment{enva}{}{}
\newenvironment{envb}{}{}
\begin{document}
\begin{enva}
\ifenv{enva}{TRUE}{FALSE}

\ifenv{envb}{TRUE}{FALSE}
\end{enva}

\begin{envb}
\ifenv{enva}{TRUE}{FALSE}

\ifenv{envb}{TRUE}{FALSE}
\end{envb}
\end{document}

It is important to use \begin --- \end to define \@currenvir.

As Marc van Dongen mentioned the test fails if you combine environments.

In this case I would use another solution.

\documentclass{article}

\makeatletter
\def\Mycurrentvir{document}
\def\ifenv#1{
   \def\@tempa{#1}%
   \ifx\@tempa\Mycurrentvir
      \expandafter\@firstoftwo
    \else
      \expandafter\@secondoftwo
   \fi
}
\makeatother
\newenvironment{enva}{\def\Mycurrentvir{enva}}{}
\newenvironment{envb}{\def\Mycurrentvir{envb}}{}
\begin{document}
\begin{enva}
\ifenv{enva}{TRUE}{FALSE}

\ifenv{envb}{TRUE}{FALSE}
\end{enva}

\begin{envb}
\ifenv{enva}{TRUE}{FALSE}

\ifenv{envb}{TRUE}{FALSE}
\end{envb}
\end{document}
Related Question