# Why does \includegraphics[\varone]{\vartwo} not compile?

I want to convert each EPS image imported from within the input file to a PDF version and save it with its original name separately. The code below simulates the real condition in which we don't want to make heavy modification. So I have to renew the definition of \includegraphics by appending the conversion process at the end.

The conversion make use of an external template (template.tex) that is created on the fly when compiling the inputfilename.tex. For each invocation of \includegraphics in inputfilename.tex,

\immediate\write18{latex -jobname=#2 \unexpanded{"\def\varone{#1} \def\vartwo{#2} \input{template}"} && dvips #2 && ps2pdf -dAutoRotatePages=/None #2.ps}


will be invoked. It uses the template template.tex and gets two parameters \varone and \vartwo from #1 and #2 of \includegraphics.

However, the following code does not compile with errors that you can see by yourself. The code must be compiled with pdflatex -shell-escape inputfilename.

% inputfilename.tex
\documentclass{book}
\usepackage{filecontents}
\begin{filecontents*}{template.tex}
\documentclass[preview,border=0pt,graphics]{standalone}
\usepackage{graphicx}
%\makeatletter
%\define@key{Gin}{width}{}
%\define@key{Gin}{scale}{}
%\define@key{Gin}{height}{}
%\makeatother
\begin{document}
\includegraphics[\varone]{\vartwo}
\end{document}
\end{filecontents*}

\usepackage{graphicx}

\let\temp\includegraphics

\renewcommand\includegraphics[2][]{%
\temp[#1]{#2}%
%\immediate\write18{latex -jobname=#2 "\def\noexpand\varone{#1} \def\noexpand\vartwo{#2} \noexpand\input{template}" && dvips #2 && ps2pdf -dAutoRotatePages=/None #2.ps}%
\immediate\write18{latex -jobname=#2 \unexpanded{"\def\varone{#1} \def\vartwo{#2} \input{template}"} && dvips #2 && ps2pdf -dAutoRotatePages=/None #2.ps}%
}

\begin{document}
\chapter{A}
\begin{figure}[hbtp]
\centering
\includegraphics[scale=.5]{example-image-a}
\caption{A}
\label{fig:A}
\end{figure}
A \ldots

\chapter{B}
\begin{figure}[hbtp]
\centering
\includegraphics[scale=.75]{example-image-b}
\caption{B}
\label{fig:B}
\end{figure}
B \ldots

\chapter{B}
\begin{figure}[hbtp]
\centering
\includegraphics[scale=1]{example-image-c}
\caption{C}
\label{fig:C}
\end{figure}
C \ldots

\end{document}


How to solve it?

keyval goes to some effort not to expand macros in the argument list so

\edef\z{\noexpand\includegraphics[\varone]{\vartwo}}\z


not

\includegraphics[\varone]{\vartwo}

• Or, more briefly, \expandafter\includegraphics\expandafter[\varone]{\vartwo} since the file name is expanded. – egreg Nov 16 '13 at 20:24
• @egreg, actually mine's more brief, as \z is shorter than \expandafter – David Carlisle Nov 16 '13 at 20:25
• Mine has less tokens. :P – egreg Nov 16 '13 at 20:26
• @egreg I know:-) – David Carlisle Nov 16 '13 at 20:26