基于最后环境的计数器值

基于最后环境的计数器值

如何使用 TeX 宏设置条件,即规则应该只启用最后一个test环境?

假设文档只包含一条\begin{test}...\end{test} 应启用的规则。

如果\begin{test}...\end{test}文档中包含多个规则,则应仅\begin{test}...\end{test}单独启用最后一条。

请查看我的 MWE 文件:

\documentclass{book}
\pagestyle{empty}
\makeatletter
\newif\ifruletest\global\ruletestfalse
\newcounter{testcounter}
\setcounter{testcounter}{0}

\newenvironment{test}{\noindent\parindent0pt}
{\par\stepcounter{testcounter}
\ifnum\value{testcounter}>0\rule{\textwidth}{1bp}\global\ruletestfalse\else\fi\bigskip}


\makeatother


\begin{document}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}
\end{document}

答案1

您可以使用totcount;如果环境数量test发生变化,则需要运行两次 LaTeX。

\documentclass{book}
\usepackage{totcount}

\newtotcounter{testcounter}

\newenvironment{test}
 {\par\setlength{\parindent}{0pt}}
 {\par\stepcounter{testcounter}
  \ifnum\totvalue{testcounter}=\value{testcounter}%
    \nobreak\rule{\textwidth}{1bp}\bigskip
  \fi}

\begin{document}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}

\begin{test}
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
Sample text Sample text Sample text Sample text
\end{test}
\end{document}

在此处输入图片描述

相关内容