TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am not that much into TeX/LaTex programming ...

but what I want to do is the following:

How to put a number into my document that increments with every compilation

My ideas so far are:

  • use a text file as storage of the number
  • read in the number
  • add 1
  • save the number to the text file
  • put the number into the text

I was able to use something like this :


(source) to write to a file but did not manage to read the number from the file into a variable that than could be iterated by one and saved back to the file. Does anyone has an idea?

share|improve this question
It should be pointed out that the file with the number should be read before you write a number to it. The \immediate\openout command immediately overwrites whatever was in the file beforehand. David's answer uses the .aux file, which is input at the beginning of \begin{document}'s code, before material added by \AtBeginDocument. A second point: it is easiest to write the full definition to the external file (as in David's answer), and then just input it to get the macro defined. – Dan Jul 3 '14 at 19:54
up vote 5 down vote accepted

You can use the package totcount:


  % when the aux file doesn't yet exist the value is -1
  % so we fix it
  \ifnum\value{compilation}=-1 \setcounter{compilation}{0}\fi


This is \LaTeX{} run number \thecompilation.


This will however restart from 1 if the .aux file is removed or gets corrupted. You can use, instead, a different file:


  % no file yet
  \read\readcompilation to \temp


This is \LaTeX{} run number \thecompilation.


If nothing goes wrong, the file with the same name as the main file and extension .vrs will contain the number of the most recent run.

share|improve this answer

\edef\mynum{\the\numexpr\mynum + 1\relax}%



share|improve this answer
Ah, nice, this uses the .aux file to store the value. But when the .aux is deleted, the version number is lost - right? Is it possible to use another file for storage? – petermeissner Jul 4 '14 at 7:57
Yes but you shouldn't delete the aux file, you could save it in a .foo file but if you delete that you'd have the same problem. You need to read the old file, close it then re-open for writing, it's easier with aux as latex is doing that anyway. To use another one I'd probably use \@starttoc{foo} which is the helper macro behind toc for table of contents and lof for list of figures etc. But personally I'd use aux – David Carlisle Jul 4 '14 at 8:44

Your Answer


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.