The subfiles package
Splits a document into files that compile on their own with the preamble of the main file: \subfile in the main file and the class subfiles in each part.
Loading the package
\usepackage{subfiles}A file loaded with \input or \include cannot be compiled alone, because it has no preamble. With subfiles, each part starts with \documentclass[main.tex]{subfiles} and has its own \begin{document} and \end{document}.
Compiled alone, the part loads the preamble of the main file named in the square brackets, so one chapter is typeset without the rest, with all packages and commands of the whole document. Loaded from the main file with \subfile{...}, only the text between \begin{document} and \end{document} is used.
Main commands
\subfile{sections/intro} | In the main file: inserts the body of the part. |
\documentclass[../main.tex]{subfiles} | First line of a part: the path to the main file, seen from the part. |
\subfileinclude{sections/intro} | Like \subfile, but with the page breaks and the .aux file of \include. |
\ifSubfilesClassLoaded{alone}{from main} | Runs the first branch when the part is compiled alone, for example to print the bibliography there too. |
\subfix{images/} | Puts the folder of the current part in front of a path. The package does this itself for \graphicspath and \bibliography; other commands that take a path need it written out. |
Complete example
\documentclass{article}
\usepackage{graphicx}
\usepackage{subfiles}
\begin{document}
\section{Main file}
The main file holds the preamble and loads the parts.
\subfile{sections/intro}
\end{document}File sections/intro.tex:
\documentclass[../main.tex]{subfiles}
\begin{document}
\section{Introduction}
This file compiles alone and as part of the main file.
\ifSubfilesClassLoaded{It was compiled alone.}{It was loaded from the main file.}
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
- The path in
\documentclass[...]{subfiles}is relative to the part, not to the main file. With a wrong path the main file still compiles, and the part alone stops with File `boktabs.sty' not found. - Load
subfilesaftergraphicx. The package adapts\graphicspathto the folders of the parts only whengraphicxis already loaded at that point. - A preamble of its own in a part, between
\documentclassand\begin{document}, is used only when the part is compiled alone. Commands defined there are missing in the main document. - File names inside a part, such as in
\includegraphics, are relative to the folder of the part in both ways of compiling.