gsalzer / subfiles

class and package for multi-file projects in LaTeX
LaTeX Project Public License v1.3c
25 stars 2 forks source link

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. #36

Open gsalzer opened 3 months ago

gsalzer commented 3 months ago

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.

gsalzer commented 3 months ago

A workaround is to split preamble.tex at the line \begin{document} into \preamble1.tex and preamble2.tex and to put \begin{document} into the main file.

% main.tex
\input{preamble1.tex}
\begin{document}
\input{preamble2.tex}
\XXX
\end{document}

% preamble1.tex
\documentclass{article}
\newcommand\XXX{The command XXX is defined.}
\usepackage{subfiles}

% preamble2.tex
% Everything from preamble.tex that came after \begin{document}
% In this example, there was nothing, so this file is empty.