如何检查自定义环境所嵌入的父环境(例如 multicols)

如何检查自定义环境所嵌入的父环境(例如 multicols)

有没有办法检查自定义环境是否嵌入在另一个父环境中。

在以下示例中,自定义环境 myenv 既位于 multicol 内部,又位于 multicol 外部。我知道 @currenvit 包含当前环境。我需要在自定义环境 myenv 开始时检查自定义 myenv(以红色文本表示)是否位于 multicol 内部。

\documentclass{article}
\usepackage{multicol}
\usepackage{xcolor}

\makeatletter
\newcommand{\whereamI}{%
    \par\@currenvir\par
    \ifx\@currenvir\@myenvname
    (\@currenvir~true)
    \else
    {\color{brown}(false myenv, it is in ~\@currenvir)}
    \fi}
\newcommand*\@myenvname{myenv}
\makeatother

\newenvironment{myenv}[0]{%
    {(\color{red}at start of~\whereamI I would like to test if parent environment is multicols) }
}{}


\begin{document}
    \begin{multicols}{2}
    \begin{myenv}
        Want to test if parent is multicols
    \end{myenv}
    {\color{blue} Inside multicols and outside myenv\whereamI}
    \end{multicols}
\end{document}

在此处输入图片描述

答案1

使用before环境钩子。似乎有效。(文档在 lthooks.pdf 中)

%! TEX program = lualatex
\documentclass{article}
\usepackage{multicol}
\usepackage{xcolor}

\makeatletter
\newcommand{\whereamI}{%
    \par\@currenvir\par
    \ifx\@currenvir\@myenvname
    (\@currenvir~true)
    \else
    {\color{brown}(false myenv, it is in ~\@currenvir)}
    \fi}
\newcommand*\@myenvname{myenv}
\makeatother

\newenvironment{myenv}[0]{%
    {(\color{red}at start of~\whereamI parent environment is \parentenvir) }
    %                                                        ^^^^^^^^^^^^
    %                      it can be used like this, how to check if it's equal to multicols is left as an exercise to the reader
}{}

% ======== start of important code ========
\makeatletter
\AddToHook{env/myenv/before}{\let\parentenvir\@currenvir}
\makeatother
% ======== end of important code ========

\begin{document}
    \begin{multicols}{2}
    \begin{myenv}
        Want to test if parent is multicols
    \end{myenv}
    {\color{blue} Inside multicols and outside myenv\whereamI}
    \end{multicols}
\end{document}

如果您愿意,可以将其重命名\parentenvir为其他名称。

相关内容