Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I would like to define a command which checks if it is executed inside a certain environment. Like this:

\documentclass{article}

\newenvironment{myenv}[0]{at start}{ at end}

\newcommand{\inner}[0]{%
  % if iside a myenv
  (inner)
  % else
  \begin{myenv}
  (inner)%
  \end{myenv}
  % end
}

\begin{document}

\begin{myenv}
  \inner
\end{myenv}

\inner

\end{document}

See the definition of \inner. Is an if-condition of this form possible?

share|improve this question
add comment

2 Answers

up vote 13 down vote accepted

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?

share|improve this answer
    
@Nickoley: Note that this doesn't work any longer when \inner is used inside another environment inside the myenv environment, e.g. \begin{myenv}\begin{center}\inner\end{center}\end{myenv}. Then \@currenvir` will be center when \inner is expanded. –  Martin Scharrer May 20 '11 at 10:28
add comment

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.

share|improve this answer
    
If you prefer the \if… … \else … \fi form, just replace \expandafter\@first/secondoftwo with your stuff, but i'd suggest the arguments-form because it's robust to unbalanced \if's. –  Natror May 20 '11 at 9:06
    
Please indent your code with four spaces (or use the '101010' button to do this) so that it is properly highlighted. Please don't use HTML for code formatting. Thanks. –  Martin Scharrer May 20 '11 at 9:39
    
the command is \strcmp in XeTeX and \pdfstrcmp in pdfTeX. One can load pdftexcmds and use \pdf@strcmp in all engines (including LuaTeX). –  egreg May 20 '11 at 10:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.