[Tex/LaTex] \includegraphics: a command in the optional argument

expansiongraphics

I want to pass some arguments to \includegraphics via a command, but I can't get it working as I would expect. My M(n)WE:

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

\newcommand{\widthText}{,width=3cm}
\includegraphics[scale=0.5 \widthText]{picture}

\end{document}

I guess that the point would be to expand \widthText before…

In my actual code, the command \widthText is actually either the one given above, or empty, depending on some boolean, and I have also a \heightText to set the height.

Best Answer

Staying with the desire of the OP, here is a solution.

\documentclass{article}
\usepackage{graphicx}
\makeatletter
\protected\def\includeGraphics{\@testopt\roy@includegraphics{}}
\def\roy@includegraphics[#1]#2{%
  \begingroup
  % Every expandable token in #1 may be expanded here:
  \edef\x{\endgroup\noexpand\includegraphics[#1]}\x{#2}%
}
\makeatother
\begin{document}
\newcommand{\widthText}{,width=3cm}
% Since double comma (,,) in the key-value pairs doesn't hurt both keyval and 
% xkeyval packages, and since the user of \widthText might forget to insert
% a comma before 'width', let us add a potentially redundant comma in the 
% following:
\includeGraphics[viewport=20 21 590 400,scale=0.5, \widthText]{./Graphics/comet1}
\end{document}