Background: I'm writing 3 small 'papers' for my B.Sc. thesis, which have to be submitted both separately and in a single document. And I wanted both 3 single documents and 1 overview, all with matching bibliographies and tables of contents. There is a common preamble, title pages for each document separately and chapter titles for the overview are automatically generated with the corresponding information, all was working perfectly. The document structure is like this (not all files and directories are shown, only those important for this post):


So each text.tex contains the actual text of the paper while report.tex is a document that sets some specific options for a single paper and includes the text.tex, overview.tex does the same for all three at the same time, including all three text.tex files. It's quite an elaborate set-up, but I've used the same scheme when TeX'ing solutions to exercises (a file for each lesson and one overview of the entire semester), so I do feel there are genuine uses for it.

But when I had to include source code I encountered a problem. Relative to subject-2/text.tex the code could be found in code/code.sage. But relative to overview.tex this file is found in subject/code/code.sage! So when building the local file all is fine, but the global file cannot find the path. Here is my solution.

Let preamble.tex define two commands:[sourcecode language="latex" wraplines="false" toolbar="false"]\newcommand\relativepath{}
which perform all the magic. \relativepath contains the extra information for constructing the relative path from the current document, \relative will construct the actual path. When inputting a listing, you can now write \inputminted{python}{\relative{code/code.sage}}.

To make this setup work, you'll need to redefine \relativepath before including text.tex. In overview.tex you write \renewcommand\relativepath{subject-2/} and in subject-2/report.tex you won't need to redefine it at all (as the path is already complete). The correct path is now available both documents!