这个标题很令人摸不着头脑,但大致是下面的需求:
下面有一小段代码用于排版problem-solution
的内容:
\documentclass{article}
\usepackage[many]{tcolorbox}
\newcounter{problem}
\newcounter{solution}
\newcommand*{\Problem}[1]{%
\setcounter{solution}{0}
\refstepcounter{problem}%
\begin{tcolorbox}[enhanced,title={\bfseries Problem~\theproblem},colframe=magenta!80!white,colback=magenta!20!white]
#1
\end{tcolorbox}
}
\newcommand*{\Solution}[1]{%
\refstepcounter{solution}%
\begin{tcolorbox}[enhanced,title={\bfseries Solution~\theproblem-\thesolution},colframe=cyan!80!white,colback=cyan!20!white]
#1
\end{tcolorbox}
}
\begin{document}
\Problem{This is the problem statement.}
\Solution{This is the first solution of the problem}
xi
\Problem{This is another problem but two solution multiple line.}
\Solution{This is the second solution.}
\Solution{This is the second solution.}
\Problem{This is another problem balabalabala}
\Solution{This is the only solution}
\Problem{This is another problem balabalabala}
\end{document}
效果图如下,由一个问题可能有1个解答,或者多于1个解答。
希望:
于是出现了如题所述的“TeX是否有办法在顺序的执行次序下获取之后文本的信息”问题?是否有比较优雅的方式实现这一点进行逻辑判断。
这类问题总是可以通过把必要的信息写入到辅助文件中解决。
\documentclass{article}
\usepackage[many]{tcolorbox}
\newcounter{problem}
\newcounter{solution}
\makeatletter
\protected\def\solutionwriteaux{\immediate\write\@auxout{%
\global\string\@namedef
{solution@count@of-\number\value{problem}}{\number\value{solution}}}}
\def\solutionmaxcount{\@ifundefined{solution@count@of-\number\value{problem}}
{1}{\@nameuse{solution@count@of-\number\value{problem}}}}
\def\thesolutionornone#1{\ifnum\number\solutionmaxcount>\@ne #1\thesolution\fi} % #1: sep
\makeatletter
\newcommand*{\Problem}[1]{%
\setcounter{solution}{0}
\refstepcounter{problem}%
\begin{tcolorbox}[enhanced,title={\bfseries Problem~\theproblem},colframe=magenta!80!white,colback=magenta!20!white]
#1
\end{tcolorbox}
}
\newcommand*{\Solution}[1]{%
\refstepcounter{solution}%
\solutionwriteaux % <- 这里写入辅助文件
\begin{tcolorbox}[enhanced,
title={\bfseries Solution~\theproblem \thesolutionornone{-}}, % <- 检查是否多于一个
colframe=cyan!80!white,colback=cyan!20!white]
#1
\end{tcolorbox}
}
\begin{document}
\Problem{This is the problem statement.}
\Solution{This is the first solution of the problem}
xi
\Problem{This is another problem but two solution multiple line.}
\Solution{This is the second solution.}
\Solution{This is the second solution.}
\Problem{This is another problem balabalabala}
\Solution{This is the only solution}
\Problem{This is another problem balabalabala}
\end{document}
看懂
\solutionwriteaux
,\solutionmaxcount
和\thesolutionornone
的实现逻辑了,谢谢雾月老师。但我还有个小问题是关于\protected\def\solutionwriteaux
前的\protected
宏的设置,而其他两个定义不需要protected
宏是基于什么考虑呢?可否顺便解释一二。谢谢您!@u70550
\solutionwriteaux
涉及写入文件,不可展;\solutionmaxcount
可展;\thesolutionornone
在#1\thesolution
可展时,也是可展的,而且如果需要把title
写入目录或书签,必需要求它不能是\protected
,否则不会得到正确的\thesolution
值。@u10307 明白了,谢谢您的耐心解释!