4

Is there a way to know if I am in an (specific) environment or not?

This MWE should clearify my question?

\documentclass{scrartcl}
\usepackage{xltxtra}
\usepackage{polyglossia}
\setdefaultlanguage[spelling=new]{german}

\newcommand{\myMacro}{%
    % if inside itemize
    in-itemize
    % else/default
    normal
}

%% Document %%
\begin{document}
\myMacro % „normal“

\begin{itemize}
    \item \myMacro % „in-itemize“
\end{itemize}
\end{document}
  • 2
    you can maybe check the definition of \@currenvir – cgnieder Jul 14 '16 at 9:50
  • 1
    Suppose \myMacro is found in an enumerate nested inside itemize: what code should be used? – egreg Jul 14 '16 at 9:51
  • 2
    Another idea: tex.stackexchange.com/a/55866 – cgnieder Jul 14 '16 at 9:52
  • @egreg I would check for mutliple environments. – buhtz Jul 14 '16 at 10:10
  • @clemens This sounds like TeX-code. Could you give an example. Logical I know what you mean but I have no idea how to code that. – buhtz Jul 14 '16 at 10:12
6

Here's a possible implementation of a stack saving the environments open at any time.

\documentclass{article}
\usepackage{etoolbox,xparse}

\makeatletter
\patchcmd{\begin}
  {\def\@currenvir}
  {\envstackpush{#1}\def\@currenvir}
  {}{}
\patchcmd{\end}
  {\@checkend}
  {\envstackpop\@checkend}
  {}{}
\makeatother

\ExplSyntaxOn
\seq_new:N \g_env_stack_seq
\NewDocumentCommand{\envstackpush}{m}
 {
  \seq_gpush:Nn \g_env_stack_seq { #1 }
 }
\NewDocumentCommand{\envstackpop}{}
 {
  \seq_gpop:NN \g_env_stack_seq \l_tmpa_tl
 }
\NewDocumentCommand{\inenvironment}{mmm}
 {
  \seq_if_in:NnTF \g_env_stack_seq { #1 } { #2 } { #3 }
 }
\NewDocumentCommand{\lastenvironment}{mmm}
 {
  \seq_get:NN \g_env_stack_seq \l_tmpa_tl
  \tl_set:Nn \l_tmpb_tl { #1 }
  \tl_if_eq:NNTF \l_tmpa_tl \l_tmpb_tl { #2 } { #3 }
 }
\ExplSyntaxOff

\newcommand{\myMacro}{%
  \inenvironment{itemize}{In itemize}{Not in itemize}%
}
\newcommand{\myMacroLast}{%
  \lastenvironment{itemize}{In itemize}{Not in itemize}%
}

\begin{document}

\begin{itemize}
\item A
\item B
  \begin{enumerate}
  \item \myMacro
  \item \myMacroLast
  \end{enumerate}
\item \myMacro
\end{itemize}

\begin{enumerate}
\item A
\item B
  \begin{itemize}
  \item \myMacro
  \item \myMacroLast
  \end{itemize}
\item \myMacro
\end{enumerate}

\end{document}

enter image description here

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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