includegraphics and xstring package

I would really like to do something like the following:

\includegraphics{\StrSubstitute{No Spaces}{ }{}}


However, this gives me an Undefined control sequence error. I saw some other posts about includegraphics not evaluating macros in arguments. So, I tried this:

\newcommand{\imageFoo}[1]{
\includegraphics{#1}
}

\begin{document}

\imageFoo{\StrSubstitute{No Spaces}{ }{}}

\end{document}


This also gives me the Undefined control sequence error.

To test further, I defined:

\newcommand{\identityMacro}[1]{#1}


The following then all work as expected:

\includegraphics{NoSpaces}
\imageFoo{NoSpaces}
\imageFoo{\identityMacro{NoSpaces}}
\includegraphics{\identityMacro{NoSpaces}}
\StrSubstitute{No Spaces}{ }{}


Can anyone help me understand why includegraphics never works with StrSubstitute?

The argument has to expand to the filename.

so you can go

\newcommand\foo{file.png}
\includegraphics{\foo}


as \foo expands to file.png

But you can not go

\includegraphics{\newcommand\foo{file.png}\foo}


as the definition of the command is an assignment and not expandable. The string functions you are invoking are of this form, making internal definitions and not simply expanding to the result.

after

\makeatletter
\newcommand\removespace[1]{\zap@space#1 \@empty}
\makeatother


you could go

\includegraphics{\removespace{ my file}}


to input myfile.png

• Thanks! This sounds like there isn't a good workaround for this problem, is that right? – Kyle May 28 '14 at 16:23
• @Kyle you can either use xstring to define a macro with the spaces removed (I think) and then use that macro in includegraphics, or use a macro such as \zap@space (defined in the latex format) that removes spaces by expansion, or you could just not enter spaces in the first place:-) or you could surround by " and have spaces in the filename or.... – David Carlisle May 28 '14 at 16:27
• \zap@space seems like the easiest option to use, but it is unrecognized. Is this not included in PDFLaTeX? – Kyle May 28 '14 at 18:16
• @Kyle probably you didn't make a @ a letter I'll add something to the answer – David Carlisle May 28 '14 at 18:54