How can I check if the current code is inside a certain environment?

LaTeX keeps the current environment in the macro \@currenvir

\makeatletter
\newcommand{\inner}{%
  \ifx\@currenvir\@myenvname
    (inner)
  \else
    \begin{myenv}(inner)\end{myenv}
  \fi}
\newcommand*\@myenvname{myenv}
\makeatother

Another approach would be to define a global conditional that's set to true by myenv start code and to false by myenv end code. It depends mostly on what you are expecting from the myenv environment: can it appear nested inside itself?


If you use pdftex, etex or xetex (I mean engine), you can define a fully expandable test:

\makeatletter \def\IfEnvir #1%
% implicit #2 "what if true"
% implicit #3 "what if false"
{%
  \ifnum \strcmp{\@currenvir}{#1}=0
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
}

\makeatother

Such a conditional is defined in the gmutils package: \@ifenvir, but there it's \protected for some reason.