如何检测环境是否位于分段命令之后?

如何检测环境是否位于分段命令之后?

我想构建一个环境,它可以检测它是否紧跟在分段命令(\section\subsection\subsubsection)之后,并且足够智能,可以检测分段命令和它本身之间是否插入了float-type 环境(例如figure)。这是我脑海中的想法的草图(为课堂编写article,我的真实案例与课堂有关book,但我认为这并不重要)。

\documentclass{article}
\newif\ifRightAfterASectioningCommand
\newenvironment{myenv}{%
  % Some detection mechanism
  % that sets RightAfterASectioningCommand
  % to true or false
  % ...
  \ifRightAfterASectioningCommand
    Right after a sectioning command
  \else
    Not right after a sectioning command
  \fi
  }{}
\begin{document}

\begin{myenv}
% RightAfterASectioningCommand is false
\end{myenv}

\section{Section}

\begin{myenv}
% RightAfterASectioningCommand is true
\end{myenv}

\begin{myenv}
% RightAfterASectioningCommand is false
\end{myenv}

\subsection{Subsection}

\begin{myenv}
% RightAfterASectioningCommand is true
\end{myenv}

\begin{myenv}
% RightAfterASectioningCommand is false
\end{myenv}

\subsubsection{Subsubsection}

\begin{myenv}
% RightAfterASectioningCommand is true
\end{myenv}

\begin{myenv}
% RightAfterASectioningCommand is false
\end{myenv}

\subsubsection{Subsubsection}

\begin{figure}
\end{figure}

\begin{myenv}
% RightAfterASectioningCommand is true
\end{myenv}

\begin{myenv}
% RightAfterASectioningCommand is false
\end{myenv}

\end{document}

答案1

所有分段命令都会全局将内部条件设置\if@nobreak为真。一旦段落开始,此条件就会重置为假。但是,浮动只有在现场真正排版时才会改变它。理由是,在分段标题后立即出现的浮动计为标题后的第一个段落。

你可能会满意

\makeatletter
\newenvironment{myenv}{%
  % Some detection mechanism
  % that sets RightAfterASectioningCommand
  % to true or false
  % ...
  \if@nobreak
    Right after a sectioning command
  \else
    Not right after a sectioning command
  \fi
  }{}
\makeatother

相关内容