[Tex/LaTex] \expandafter to expand macro before macro call

expansionmacros

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?

Best Answer

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.

Related Question