有没有办法知道我是否处于(特定)环境中?
这个 MWE 应该可以解答我的问题吗?
\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}
答案1
这是一个可以随时保存打开的环境的堆栈的可能实现。
\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}