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?

  • 1
    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

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.


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



  • 1
    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? Jul 4 '14 at 7:57
  • 2
    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 Jul 4 '14 at 8:44

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.