The correct way to import files within subfiles

importincludeinputpathssubfiles

The subfiles docs explains that it handles path issues when main files and subfiles are in different directories and subfiles contain paths relative to their own directories using the \import package. It appears that this means subfiles uses \import when adding the content of files passed to \subfile. For example, \subfile{ch/ch1.tex} is roughly equivalent to modifying the preamble of ch1.tex then calling \import{ch/ch1.tex}. What is not clear is how to correctly nest imports, i.e. import within imported subfiles.

Below I provide an example project/directory structure and two example files assuming that main.tex should import ch1.tex and ch1.tex should import fig.png and text.txt.

 +-- main.tex
 +-- chapters
     |
     +-- ch1.tex
     +-- content
         |
         +-- text1.txt
         +-- fig1.png
%% main.tex
\documentclass{book}
\usepackage{graphicx}
\usepackage{subfiles}

\begin{document}
    \subfile{chapters/ch1.tex} % \imports ch1.tex
\end{document}
%% ch1.tex
\documentclass[../main.tex]{subfiles}
\begin{document}
    \import{content}{text.txt}        % adds some text - note use of \import
    \includegraphics{content/fig.png} % adds a figure
\end{document}

When I compile the files above, they produce the desired output. However, as \import is used in the \subfile{chapters/ch1.tex} call in main.tex but then is also used within ch1.tex in the \import{content}{text.txt} call. The import docs indicates \subimport should be used for the latter. As \subimportrequires a path relative to the currently imported file, the call should be\subimport{content/}{text1.txt}`.

Should importing within subfiles always use subimport? If so, I am confused as to why swapping \import with \subimport produces the same results when they should presumably point to different directories as in the examples in the import docs.

Best Answer

You can use \input directly.

│  main.tex
│
└─chapters
    │  ch1.tex
    │
    └─content
            fig1.png
            text1.txt

main.tex

\documentclass{book}
\usepackage{graphicx}
\graphicspath{{chapters/content/}}
\makeatletter
\newcommand{\input@path}{{chapters/}{chapters/content/}}
\makeatother
\begin{document}
aaa
\input{ch1.tex}
bbb
\end{document}

ch1.tex

ccc
\input{text1.txt}
\includegraphics[width=3cm]{fig1.png}
ddd

text1.txt

eee

enter image description here