仅当环境前面有文本时才在环境前留有垂直空间

仅当环境前面有文本时才在环境前留有垂直空间

我需要将用户定义的环境放置在另一个环境中,单独放置或放在一些文本之后,并且我希望垂直空间是自动地仅在后一种情况下插入。换句话说,我想定义它environment2,以便在这种情况下它前面有一些垂直空间

\begin{environment}
Text
      <--- space here
\begin{environment2}
Text
\end{environment2}
\end{environment}

不是在这种情况下:

\begin{environment}
\begin{environment2}
Text
\end{environment2}
\end{environment}

答案1

解决此类问题的典型方法是使用钩子\everypar,每次 TeX开始一个新段落。因此,您可以有一个开关,例如,在开始外部环境时\if@EnvOneHasText@将其设置为,同时向钩子添加一条指令,将同一开关设置为。然后在内部环境开始时测试此开关:false\everypartrue

  • 如果你发现它仍然是错误的,那么你知道 TeX 没有开始任何段落,因为最外层环境已经开始,所以你这样做不是添加垂直空间;

  • 另一方面,如果你发现它已经成为事实,你知道 TeX 在外部环境的开头和内部环境的开头之间找到了一些文本,这迫使它开始一个新段落,所以你添加垂直空间。

下面是一个说明此技术的 MWE:

% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly 
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\makeatletter

\@ifdefinable\if@EnvOneHasText@{\newif\if@EnvOneHasText@}

\newenvironment*{environment1}{%
    \par % make sure we terminate any preceding paragraph
    % The following is just to mark where the environment begins;
    % you should substitute your real code here:
    \addvspace{\bigskipamount}%
    \noindent Begin of \texttt{environment1}.\par
    % The following two lines do the trick:
    \@EnvOneHasText@false
    \everypar \expandafter{\the\everypar \@EnvOneHasText@true}%
}{%
    \par
    % Add whatever you need here.
    \noindent End of \texttt{environment1}.\par
    \addvspace{\bigskipamount}% for example
}

\newenvironment*{environment2}{%
    \par
    \if@EnvOneHasText@
        \addvspace{\bigskipamount}% say
    \fi
    % The following is just to mark where the environment begins;
    % you should substitute your real code here:
    \noindent
    Begin of \texttt{environment2}.\par
}{
    \par
    % Add whatever you need here.
    \noindent End of \texttt{environment2}.\par
}

\makeatother



\begin{document}

Some text to begin with.

\begin{environment1}
    \begin{environment2}
        Some text inside the innermost environment.
    \end{environment2}
\end{environment1}

Words words words words\ldots

\begin{environment1}
    Some text in between.
    \begin{environment2}
        Some text inside the innermost environment.
    \end{environment2}
\end{environment1}

Words words words words\ldots

\begin{environment1}
    Does it nest correctly?
    \begin{environment2}
        Some text inside the outer \texttt{environment2} environment.
        \begin{environment1}
            \begin{environment2}
                Some text inside the inner \texttt{environment2} environment.
                There should be no space above this text.
            \end{environment2}
            We are now inside the inner \texttt{environment1} environment.
        \end{environment1}
    \end{environment2}
\end{environment1}

\end{document}

相关内容