# How to execute a command only on the next run?

Let's say I have a command \foo that I want to execute only on the next run of TeX. How do I create a command \onceFoo that does this? (It is also permitted to execute \foo if the aux file has been compromised.)

Minimal (non-)working example:

\documentclass{article}
\def\foo{First execution}
\def\onceFoo{This doesn't work.}
\begin{document}
testing: \onceFoo
\end{document}


The desired output is

testing: First execution


on the first run of latex, and

testing:


on every subsequent run.

If the file above (with the correct definition of \onceFoo) has been run several times, and the line new testing: \onceFoo is added, then the desired output is

testing: new testing: First execution


on the first subsequent run, and

testing: new testing:


on all runs thereafter.

Motivation: I would like to create a command that clears certain useful files and recomputes them. Normally, this command should be used for a single run to remove corrupted information (or for testing); afterwards, the command should be removed from the source file. However, some users (notably I) are likely to forget to remove the command, since it does not actually break anything--it only produces a significant drop in efficiency, because many things must be recalculated. Thus, I would like a second version of this command that affects only the first run after it is added.

-

## 1 Answer

\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}


And the same for counting the runs:

\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}

-
+1, but this does not consider separate occurrences separately. Nevertheless, it's useful and readable; if you post a more elaborate version, please don't delete this one in the process. –  Charles Staats Mar 26 '14 at 15:06
Edited example with counting the runs. –  Herbert Mar 26 '14 at 15:32