# \expandafter to expand macro before macro call

I am trying to include an image:

\documentclass{article}
\usepackage{graphicx}
\begin{document}

\newcommand{\ext}{.pdf}

\def\incPIC#1{ \expandafter\includegraphics{#1}}

{
\tracingmacros=1
\tracingassigns=1
\incPIC{../graphics/PerformancePlots/figureTree-P-0-10\ext}
}

\end{document}


The above does not work as the \ext is first expanded deep inside the \includegraphics command, I would like to expand it before the call the \includegraphics? what am I doing wrong. Shouldn't the \expandafter expand the #1 first?

• \expandafter expands the token after the next, in your case the opening brace. You would need something like \edef\next{\noexpand\includegraphics{example-image\ext}}\next if you want to expand a command so far away. But why are you adding the extension? pdflatex doesn't need it. – Ulrike Fischer May 30 '16 at 13:30
• @ChristianHupfer: That doesn't matter here, the code doesn't try to expand \includegraphics. – Ulrike Fischer May 30 '16 at 13:31
• Try some pre-expansion \def\incPIC#1{\edef\tmpa{#1}\includegraphics{\tmpa}} – user31729 May 30 '16 at 13:31
• @UlrikeFischer: Right,I read too fast – user31729 May 30 '16 at 13:32
• Why should you need the extension? Maybe Choosing whether to include PDF or PNG in pdflatex helps. – egreg May 30 '16 at 13:36

The \expandafter command tries to expand one level the token immediately following the next one.

With your code, the tried token is {, which is not expandable.

Reaching the last token in the argument is impossible with \expandafter, because you don't know how many of them there are.

Some tricks are possible, though. The easiest one is to force complete expansion of the argument:

\documentclass{article}
\usepackage{graphicx}

\newcommand{\ext}{.jpg}

\newcommand\incPIC[1]{%
\begingroup\edef\x{\endgroup
\noexpand\includegraphics{#1}%
}\x
}

\begin{document}

\incPIC{example-image\ext}

\end{document}


On the other hand, the \ext can better go in the definition:

\documentclass{article}
\usepackage{graphicx}

\newcommand{\ext}{.jpg}

\newcommand\incPIC[1]{%
\begingroup\edef\x{\endgroup
\noexpand\includegraphics{#1\ext}%
}\x
}

\begin{document}

\incPIC{example-image}

\end{document}


A different trick with xparse and expl3, so it's easy to also accommodate the optional argument to \includegraphics.

\documentclass{article}
\usepackage{graphicx}
\usepackage{xparse}

\newcommand{\ext}{.jpg}

\ExplSyntaxOn
\cs_new_protected:Nn \gabriel_includegraphics:nnn
{
\includegraphics[#2]{#3#1}
}
\cs_generate_variant:Nn \gabriel_includegraphics:nnn { V }

\NewDocumentCommand\incPIC {O{}m}
{
\gabriel_includegraphics:Vnn \ext { #1 } { #2 }
}
\ExplSyntaxOff

\begin{document}

\incPIC{example-image}

\incPIC[width=3cm]{example-image}

\end{document}


See also Choosing whether to include PDF or PNG in PDFLaTeX for different strategies.