
假設我有一個命令\foo
,只想在下次執行 TeX 時執行。如何建立\onceFoo
執行此操作的命令? (\foo
如果aux
文件已洩露,也允許執行。)
最小(非)工作範例:
\documentclass{article}
\def\foo{First execution}
\def\onceFoo{This doesn't work.}
\begin{document}
testing: \onceFoo
\end{document}
期望的輸出是
testing: First execution
第一次運轉時latex
, 和
testing:
在隨後的每次運行中。
如果上面的檔案(具有正確的定義\onceFoo
)已運行多次,並且new testing: \onceFoo
添加了該行,則所需的輸出為
testing: new testing: First execution
在隨後的第一次運行中,以及
testing: new testing:
此後的所有運行。
動機:我想創建一個命令來清除某些有用的檔案並重新計算它們。通常,此命令應用於單次運行以刪除損壞的資訊(或用於測試);之後,應從來源檔案中刪除該命令。然而,一些用戶(尤其是我)可能會忘記刪除該命令,因為它實際上並沒有破壞任何東西——它只會導致效率顯著下降,因為許多事情必須重新計算。因此,我想要此命令的第二個版本,該版本僅影響新增後的第一次運行。
答案1
\documentclass{article}
\def\foo{First execution}
\newif\ifFirstRun
\makeatletter
\AtBeginDocument{%
\ifx\FirstRunTest\@undefined
\FirstRuntrue
\else
\FirstRunfalse
\fi
\write\@auxout{\string\gdef\string\FirstRunTest{}}}
\makeatother
\begin{document}
testing: \ifFirstRun\foo\fi
\end{document}
計算運行次數也是如此:
\documentclass{minimal}
\def\foo{First execution}
\makeatletter
\AtBeginDocument{%
\ifx\runNo\@undefined
\newcount\runNo \runNo=1
\else
\advance\runNo by \@ne
\fi
\write\@auxout{%
\string\newcount\string\runNo ^^J
\string\global\runNo=\the\runNo}}
\makeatother
\begin{document}
testing: \ifnum\the\runNo=1\foo\else Run no \the\runNo\fi
\end{document}