# [texhax] how to copy a file within eTeX?

Ulrike Fischer news3 at nililand.de
Tue Apr 6 09:52:05 CEST 2010

Am Mon, 05 Apr 2010 16:58:16 -0600 schrieb D. R. Evans:

> My problem:
>
> I need to process a single ToC file multiple times within the course of
> compiling a single TeX file. However, since I'm also regenerating the ToC,
> I can't simply put the usual \readtoc at the points where I want the ToC
> processing to occur.

Well actually the contents of .toc aren't  written directly when
e.g. a \section command is encountered. This wouldn't work if the
\tableofcontents command isn't the first thing in a document like
here:
\documentclass{article}

\begin{document}
\section{A}
\tableofcontents
\section{B}
\end{document}

What really happens is that a \addtocontents command first writes a
\@writefile command in the aux-file, and at \end{document} the
aux-file is input and then all entries are written in one go to the
toc.

The reason that you can't normally use two \tableofcontents command
is that \jobename.toc is already opened for writing by the first
\tableofcontents command. The memoir class moves the opening of
\jobname.toc to the end of document and so allows two (or more)
\tableofcontents commands. You could copy this method:

\documentclass{article}
\makeatletter
\renewcommand{\@starttoc}[1]{%
\begingroup\makeatletter
\@input{\jobname.#1}%
\if at filesw
\AtEndDocument{%
\expandafter\newwrite\csname tf@#1\endcsname
\immediate\openout \csname tf@#1\endcsname \jobname.#1\relax
}%
\fi
\@nobreakfalse
\endgroup}
\makeatother
\begin{document}
\tableofcontents
\setcounter{tocdepth}{2}
\tableofcontents
\setcounter{tocdepth}{1}
\tableofcontents

\section{A}
\subsection{b}
\subsubsection{c}
\section{B}
\end{document}

--
Ulrike Fischer