Filecontents LaTeX – How ‘Filecontents’ Keeps LaTeX Parsing While Stopping Output

external filesparsing

We all know filecontents.sty can do

\documentclass{article}

\usepackage{filecontents}

\begin{document}

Hello World

\begin{filecontents}{dummy.txt}
No one will read this if I don't use it elsewhere
\end{filecontents}

\end{document}

But since the filecontents.sty's code is pretty advanced chemistry, I do not get how it prevents including No one will read this if I don't use it elsewhere.

Best Answer

The basic working of the filecontents environment is the same as verbatim: every character is made printable and the end of line character is made active so that LaTeX can define it to delimit an argument which will be an entire line of input.

First the environment checks whether the named file already exists and, in this case, does nothing else than discarding everything up to \end{filecontents}. Otherwise it opens an output stream and writes some information lines (this is suppressed with \begin{filecontents*}.

Then it reads one line at a time as roughly explained above; if this line turns out to be \end{filecontents} (or \end{filecontents*} for the variant environment), the write stream is closed, otherwise the line is written to the output file.

A possible more efficient strategy is outlined in the documentation of the verbatim package, where the definition of a possible verbatimwrite environment is shown. I used the same in my abc package.

Related Question