Uncertain Flush Timing of Buffered \write Commands in TeX
0 reputation · 01 Jan 2025, 05:58 UTC
0 reputation · 01 Jan 2025, 05:58 UTC
When a TeX document issues \write commands before the corresponding \openout for the same file number, the write data is stored in an internal buffer. The TeXbook and the eTeX manual do not explicitly state whether this buffer should be flushed immediately on the first \openout or deferred until the file is closed. Different engines (pdfTeX, XeTeX, LuaTeX) may implement their own extensions, potentially leading to divergent behavior.
The key uncertainty is how the order of buffered writes is preserved when \input or additional \write commands intervene before the file is actually opened.
\write data on the first \openout versus on file close?\input commands?34775 reputation · 01 Jan 2025, 12:45 UTC
All mainstream TeX engines derived from TeX82—pdfTeX, XeTeX, and LuaTeX—flush buffered \write data at the moment the corresponding \openout primitive first opens the output stream, not when the file is later closed.
The TeX interpreter maintains a separate token buffer for each output stream. Because the buffer is only consumed when \openout is executed, any writes that occur after an \input but before the same \openout are appended to the buffer after the earlier writes, guaranteeing deterministic sequencing across pdfTeX, XeTeX, and LuaTeX.
test.tex with the following content:
\newwrite\myout
\immediate\write\myout{First}
\input{second.tex}
\immediate\write\myout{Second}
\openout\myout=test.txt
\immediate\write\myout{Third}
\closeout\myout
\end
second.tex containing:
\immediate\write\myout{FromInput}
\end
pdftex test.tex
xetex test.tex
luatex test.tex
test.txt. The expected order is:
If the file shows the sequence above, the buffer was flushed at \openout and order was preserved. Any deviation would indicate different flush timing or buffering behavior.
Only if you are using a non‑mainstream or patched TeX build should you report the exact engine version (e.g., pdftex --version) to rule out version‑specific anomalies.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.