Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 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}

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}
share|improve this answer
    
+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 at 15:06
    
Edited example with counting the runs. –  Herbert Mar 26 at 15:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.