5

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:

enter image description here

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}
2
  • 1
    \gdef, perhaps?
    – egreg
    Jan 20 at 22:38
  • @egreg: Hmmm.. You aren't sure. :-). Thanks, that works great Jan 20 at 22:40

1 Answer 1

7

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}
4
  • 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.
    – Symbol 1
    Jan 20 at 23:15
  • 1
    @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.
    – egreg
    Jan 20 at 23:25
  • Nice! But don't try this with latexmk 😜... (spoiler: I know it will stop after a while, but...)
    – Rmano
    Jan 21 at 9:31
  • BTW, auto-commenting my comment: solvable by adding $hash_calc_ignore_pattern{'aux'}='.*CurrentRunNumber.*'; to your latexmkrc. I think.
    – Rmano
    Jan 21 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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