[Tex/LaTex] Path problem with included file inside of a standalone file

standalone

How can I get the current path inside an included standalone file?

1. Theoretical Example:

let's assume the following directory structure:

main.tex
img/
 |-standalonefile.tex
 |-data

standalonefile.tex:

\documentclass{standalone}

\begin{document}
    \somecommand{data}
\end{document}

main.tex:

\documentclass{article}

\usepackage{standalone}

\begin{document}
    \includestandalone{img/standalonefile}
\end{document}

Now standalonefile.tex compiles, but main.tex can't find data.
I couldn't find a way to use path from \includestandalone somehow inside standalonefile.tex.

2. Practical example with pgfplots (MWE) (I'm looking for a general solution)

directory structure:

main.tex
plots/
 |- plot1/
     |- plot1.tex
     |- data.csv

main.tex

\documentclass{article}

\usepackage[subpreambles]{standalone}

\begin{document}
    \includestandalone{plots/plot1/plot1}
\end{document}

plot1.tex

\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}
    \begin{tikzpicture}
    \begin{axis}
        \addplot table [x=x, y=y, col sep=semicolon]{data.csv};
    \end{axis}
    \end{tikzpicture}

\end{document}

data.csv

x;y
0;0
1;1

Now plot1.tex compiles fine, but with main.tex the data.csv can't be found.

Ideas for a solution

  • a command like \mystandalonedir that would return
    • the relative path to the main file, if included with \includestandalone
    • nothing, if not included
  • change the base dir somehow with the \includestandalone
  • (or something else 😉 )

Best Answer

My answer is possibly not a very elegant one, but it's roughly the way I handle this problem with my own files. The basic idea is to set up a path macro \datapath.

For your given practical example, I suggest the following:

main.tex

\documentclass{article}

\usepackage[subpreambles]{standalone}

\newcommand{\includestandalonewithpath}[3][]{%
  \begingroup%
  \newcommand{\datapath}{#2}%
  \includestandalone[#1]{\datapath/#3}%
  \endgroup}

\begin{document}
  \includestandalonewithpath{plots/plot1}{plot1}
\end{document}

plot1.tex

\providecommand{\datapath}{.}
\documentclass{standalone}

\usepackage{pgfplots}

\begin{document}
    \begin{tikzpicture}
    \begin{axis}
        \addplot table [x=x, y=y, col sep=semicolon]{\datapath/data.csv};
    \end{axis}
    \end{tikzpicture}
\end{document}

This solution will also work, if your data file is in a subdirectory relative to plot1.tex, e.g.

plots/plot1/data/data.csv

Then, you would have:

\addplot table [x=x, y=y, col sep=semicolon]{\datapath/data/data.csv};
Related Question