假设我有一个维度(称为\shape
),其值在一段代码中会局部改变几次。还假设我定义了一个命令(\shifter
在后面的代码中称为)来影响这些变化。那么,是否可以使用开始守则,最终的值\shape
将是多少?例如:
\documentclass{article}
\usepackage{showframe}
\usepackage{etoolbox}
\setlength{\parindent}{0pt} % Cancel automatic indentation
\newdimen\shape % Let there be the dimension \shape
\setlength{\shape}{0pt} % Let \shape start at 0pt
\newdimen\shapecompare % Let there be the dimension \shapecompare
\newcommand{\shifter}[1]{% If \shape is less than the width of the input of \shifter, then make \shape equal to the width of the input. Otherwise, do nothing.
\settowidth\shapecompare{#1}%
\ifdimless{\shape}{\shapecompare}%
{\setlength{\shape}{\shapecompare}}%
{}%
}%
\begin{document}
% At this moment (namely, the very beginning of the document), I would like to make use of whatever value \shape will end up at by the end of the code (namely, by the end, \shape = the width of the words ``Yes, sir, I will be there.'').
\hspace{\shape}Hello
\shifter{Hello}
\hspace{\shape}Hello
Hello
\shifter{Yes, sir, I will be there.}
\hspace{\shape}Hello
Yes, sir, I will be there.
\end{document}
注:Stephen 的回答(https://tex.stackexchange.com/a/55432/277990)这个问题如何检索文档中稍后设置的值?似乎它可能与我的情况有关,但是当我尝试将其用法替换\setvalue
为\getvalue
我的情况中的相应术语时,我无法使其发挥作用 --- 而且最重要的是,我不确定有关的内容是如何.aux
工作的。
答案1
您需要将设置写入.aux
文件中,该文件将在下次运行 LaTeX 时读取。这里需要\global
设置,因为.aux
文件是按组读取的。
\documentclass{article}
\usepackage{ifthen}
\usepackage{showframe}
\newdimen\shape
\global\shape=0pt
\makeatletter
\AtEndDocument{\immediate\write\@auxout{\global\shape=\the\shape}}
\makeatother
\newcommand{\shifter}[1]{%
\settowidth{\dimen0}{#1}%
\ifdim\shape<\dimen0
\global\shape=\dimen0
\fi
}
\setlength{\parindent}{0pt}
\begin{document}
\hspace{\shape}Hello
\shifter{Tyrannosaurus}
\hspace{\shape}Hello
Tyrannosaurus % check the space
\end{document}