To create a Table of Contents (for example), LaTeX2e follows the process:
Run 1
.auxfile is created from scratch after\begin{document}.- When processing section headers, write
\addtocontentsto the.auxfile with the pertinent sectioning information. - At
\end{document},\inputthe.auxfile, which executes\@writefilevia\contentslineto generate the.tocfile.
Run 2
At
\begin{document}, deactivate\@writefileand re-input the.auxfile. This generates labelling information, etc., for the current compilation and has no effect on the.tocfile already generated.After
\begin{document}, the.auxfile is opened for writing, which clears its contents. The process starts anew.
The 2e sources don't go into detail about why the system was designed this way. Since there are limited write registers, writing all .toc information in one pass at \end{document} minimises the number of files that need to be kept open during the document. So that aspect is sensible.
But why is the .aux file input both at the beginning and the end of the document? Couldn't the .toc file be generated at \begin{document} instead?
(One difference is that if ‘Run 1’ is terminated prematurely, no .toc file will be generated at all so there'll be no ToC. Whereas if the .toc file were created at \begin{document} it would contain a partial ToC — but that's arguably no better or worse. And you could add, say, a \@finishedauxtrue flag inserted at \end{document} to catch this happening if necessary.)
[[EDIT: Well, loading the aux file at the end allows for some checking whether labels have changed, and so on. So the aux file does always need to be loaded twice; I guess my question is whether there's any difference for ToC generation when that happens.]]
\begin{documement}without a full document pass. – Steven B. Segletes Jun 26 '14 at 00:38auxfile twice? Once with@writefileactive and once with it inactive? – cfr Jun 26 '14 at 00:49