subfiles
subfiles copied to clipboard
Error `Missing \begin{document}` or `File ended while scanning use of \subfiles@skipToEndDocument` when `\begin{document}` is placed in a file \input by the main file.
The following issue was raised on tex.stackexchange.com in the post "Undefined control sequence. \begin{document}" in subfile when compiling in TeXstudio.
Consider the following files:
% main.tex
\input{preamble.tex}
\XXX
\end{document}
% preamble.tex
\documentclass{article}
\newcommand\XXX{The command XXX is defined.}
\usepackage{subfiles}
\begin{document}
% sub.tex
\documentclass[main]{subfiles}
\begin{document}
\XXX
\end{document}
When LaTeXing sub.tex
, we get the following error:
! LaTeX Error: Missing \begin{document}.
...
l.3 \XXX
The problem arises because when encountering \begin{document}
in preamble.tex
, the subfiles
package skips the rest of the file (here: preamble.tex
) and assumes that it has thus skipped the rest of the document. However, in the example above, there is still the rest of main.tex
, which means that \XXX
will be processed as part of the preamble. As \XXX
generates output, we get the observed error message.
Alternatively, when loading, in preamble.tex
, the package subfiles
with the option v1
:
\usepackage[v1]{subfiles}
we get the error
! File ended while scanning use of \subfiles@skipToEndDocument.
...
l.1 \input{preamble.tex}
Here, the lines after \begin{document}
are skipped as a macro argument delimited by \end{document}
. As argument parsing is interrupted when reaching the end of the file preamble.tex
and not continued in the main file, we get the error shown above.