# Detect Number of Times pdflatex was run

I would like to include information in the pdf to indicate of how many times pdflatex was run. This seems pretty trivial, but I can't seem to get this to work -- must be someting obvious.

The output works fine the first time (since the .aux file does not exist). But, after that it is stuck at:

### Code:

\documentclass{article}
\usepackage{pgfmath}
\usepackage{xcolor}\pagecolor{white}

\makeatletter
\providecommand{\CurrentRunNumber}{0}%
\IfFileExists{\jobname.aux}{%
% Set via the .aux file
}{%
\def\CurrentRunNumber{1}%
}%
\AtEndDocument{%
\pgfmathtruncatemacro{\@NewRunNumber}{\CurrentRunNumber+1}%
\immediate\write\@auxout{%
\noexpand\def\noexpand\CurrentRunNumber{\@NewRunNumber}%
}%
}%
\makeatother

\begin{document}
Run Count: \CurrentRunNumber
\end{document}

• \gdef, perhaps? Jan 20 at 22:38
• @egreg: Hmmm.. You aren't sure. :-). Thanks, that works great Jan 20 at 22:40

The .aux file is read inside a group. Use \gdef. No need for pgfmath.

\documentclass{article}

\providecommand{\CurrentRunNumber}{1}
\makeatletter
\AtEndDocument{%
\immediate\write\@auxout{%
\gdef\noexpand\CurrentRunNumber{\the\numexpr\CurrentRunNumber+1}
}%
}
\makeatother

\begin{document}
Run Count: \CurrentRunNumber
\end{document}


After two runs, for instance, the .aux file will be

\relax
\gdef \CurrentRunNumber {2}
\gdef \@abspage@last{1}

• Is \CurrentRunNumber becoming \the\numexpr \the\numexpr ... +1 +1? Or the \the will be expanded by the \write? I am asking because the former sounds funny. Jan 20 at 23:15
• @Symbol1 \write stores the token list and expands it at the moment the write operation is performed. That's why one needs \gdef\noexpand\CurrentRunNumber so \gdef\CurrentRunNumber is written out; but \the is expanded. I'll add the contents after two runs. Note that \noexpand is not needed in front of \gdef, because this is an unexpandable token. Jan 20 at 23:25
• Nice! But don't try this with latexmk 😜... (spoiler: I know it will stop after a while, but...) Jan 21 at 9:31
• BTW, auto-commenting my comment: solvable by adding \$hash_calc_ignore_pattern{'aux'}='.*CurrentRunNumber.*'; to your latexmkrc. I think. Jan 21 at 9:39