[Tex/LaTex] Subfiles package – two levels (subfile in subfile)

nestingsubfiles

Although the documentation of the subfiles package states that nesting is supported, I somehow can't get it to work.
I have the following structure:

./main.tex
./level1/level1.tex
./level1/level2/level2.tex

These files have the following content (MWE):

%%% ./main.tex
\documentclass{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{subfiles}
\begin{document}
Level 0
\subfile{level1/level1}
\end{document}



%%% ./level1/level1.tex
\documentclass[../main.tex]{subfiles}
\begin{document}
Level 1
\subfile{level2/level2}
\end{document}



%%% ./level1/level2/level2.tex
\documentclass[../../main.tex]{subfiles}
\begin{document}
Level 2
\end{document}

For your convenience, I uploaded the structure here (valid until 23rd Jan 2018).

I want all files to compile in their respective location. At the moment, level2.tex and level1.tex compile but when I try to compile main.tex it gives me the error

! LaTeX Error: File `level2/level2.tex' not found

I can make main.tex compile by changing the line

\subfile{level2/level2}

in level1.tex to

\subfile{level1/level2/level2}

but then level1.tex doesn't compile because (obviously) it can't find level2.tex anymore.

There must be an automated approach so that all files compile and the input path is updated automatically, right?

Thanks for your help in advance!

Best Answer

Answer 1

Don't worry about paths yourself, but make tex find the files for you by modifing the input path.

% !TeX root = main.tex
\documentclass{article}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{subfiles}

\makeatletter
\providecommand*{\input@path}{}
\g@addto@macro\input@path{{./level1//}{./level1/level2//}{./level2//}}
\makeatother

\begin{document}
Level 0
\subfile{level1}
\end{document}

% !TeX root = level1.tex
\documentclass[../main.tex]{subfiles}
\begin{document}
Level 1
\subfile{level2}
\end{document}

% !TeX root = level2.tex
\documentclass[../../main.tex]{subfiles}
\begin{document}
Level 2
\end{document}

Answer 2

The first answer will break if multiple files in different subfolders share the same name. In this case you could test if the file exists in a given location and select the correct path based on this.

% !TeX root = level1.tex
\documentclass[../main.tex]{subfiles}

\begin{document}
Level 1

\IfFileExists{./level2/level2.tex}{
    \subfile{./level2/level2}
}{
    \subfile{./level1/level2/level2}
}

\end{document}
Related Question