[Tex/LaTex] When is the aux file read and written


  1. I'd like to know when the aux file is read. I know it happens after the preamble, but does it come before or after the \AtBeginDocument hook?

  2. I'd like to know when the aux file (or any other helper file) is actually written. I tried to trace the writing process by placing an undefined command after something should have been written to the aux file, and run pdflatex in interactive mode, like so:

    \section{S}\label{s}% write something to the aux file
    \foo% unknown command

    but to my surprise the aux file is still empty when pdflatex stops at the error. I guess there is some buffering happening, but how would I resolve the synchronization issue? Say, when \foo is command that wants to read from the aux file?

Best Answer

The .aux file is read as part of the \document macro (\begin{document}) but before the \AtBeginDocument hook is used. (You can check this by inserting some 'test code' into the .aux file and the hook.)

Writing to the .aux file takes place both 'immediately' and at shipout. The latter is important to get for example the correct page numbers for cross-references, so things like \label take place in a delayed fashion, using the \protected@write 'wrapper' around the \write primitive. Thus for example




only places \foo in the .aux file: \baz is never written as there is no page shipout. In your example, shipout occurs after \foo, so you see nothing in the .aux file at that point although a shipout does occur later.

Note that TeX keeps the .aux file open until the end of the run, so you cannot be sure that any particular \write will appear in the partial .aux file during a run. As such, the only safe time to check on what gets written to the file is after the run completes. In particular, badly-terminated jobs may leave the .aux file in an incomplete state even if the crash occurs after writes 'should' have taken place.

Related Question