[Tex/LaTex] How to use a command as path in ‘includegraphics’

graphicsmacros

I want to include a graphic by using \includegraphics{\mycommand} but it doesn't work. The path to the picture will be a combination of text written in .txt files. This is my code:

\usepackage{german}  
\usepackage{graphicx}  
% read in the files  
\def\textx{\input{x.txt}} %com  
\def\texty{\input{y.txt}} %bin  
\def\textz{\input{z.txt}} %ed   
\def\textp{\input{p.txt}} %.png  
% delete spaces etc.  
\newcommand{\textxx}{\unskip \textx \ignorespaces}  
\newcommand{\textyy}{\unskip \texty \ignorespaces}  
\newcommand{\textzz}{\unskip \textz \ignorespaces}  
\newcommand{\textpp}{\unskip \textp \ignorespaces}  
\textxx\textyy\textzz\textpp %combined.png  
%combine them  
\newcommand{\textv}{\textxx\textyy\textzz\textpp}  
\textv %output: combined.png  
\includegraphics{\textv} % Error: undefined control sequence  

Best Answer

The example in the question reveals quite some show stoppers:

  • Package graphics needs to know the file name extension and calls LaTeX's \filename@parse to split the path specification. \filename@parse expands the first token once. Thus it is possible to put the starting path in a macro. But after the expansion step, further macros or nested macros are not expanded. They will break the file name parser, if they hide important path syntax elements. Nested macros can be avoided by expanding them by defining a macro with \edef and then passing the macro with the expanded path to \includegraphics.

  • \unskip and \ignorespaces are unexpandable tokens, they will appear as path component. Check out package trimspaces or similar packages to strip spaces at the begin and end from a string.

  • Also LaTeX's \input is not expandable. Even the primitive version \@@input is quite tricky to use:

    • Line ends cause unwanted spaces, they can be suppressed by \endlinechar=-1.
    • The file end causes an error in an expandable context, there are some tricks to avoid the error, e.g., \everyeof{\noexpand} with e-TeX.

    Package catchfile provides means to put files into macros.

If you want to use \includegraphics{\imagepath}, then you can inspect \imagepath:

\typeout{[meaning of \string\imagepath: \meaning\imagepath]}

will print the following to the console and log output, assuming \imagepath contains x/y/z.png:

[meaning of \imagepath: macro:->x/y/z.png]

The shown path should be free of TeX commands or unwanted spaces.