# keyval error on passing macro as an optional argument to includegraphics [duplicate]

This question already has an answer here:

I am trying to include an image in my document:

\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}

\begin{document}

\def\foo{scale=0.1}
\includegraphics[\foo]{fig1.eps}

\end{document}


gives me the error

ERROR: Package xkeyval Error: scale=0.1' undefined in families Gin'.


It has something to do with macro expansion, but I was not able to solve it. Then I saw this question with the following answer

Defining a private \includegraphics allows you to call macros as optional arguments:

\protected\def\newincludegraphics{\@testopt\new@includegraphics{}}
\def\new@includegraphics[#1]{%
\begingroup
\@protected@edef\x{\endgroup
\noexpand\includegraphics
\if\relax\detokenize{#1}\relax\else[#1]\fi
}\x
}

\newincludegraphics[\scalefactor]{image}


where the new macro \newincludegraphics was defined.

MWE

\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}

\begin{document}
\protected\def\newincludegraphics{\@testopt\new@includegraphics{}}
\def\new@includegraphics[#1]{%
\begingroup
\@protected@edef\x{\endgroup
\noexpand\includegraphics
\if\relax\detokenize{#1}\relax\else[#1]\fi
}\x
}

\def\foo{scale=0.1}
\newincludegraphics[\foo]{fig1.eps}

\end{document}


Nevertheless I still get this error:

ERROR: You can't use \spacefactor' in vertical mode.

--- TeX said ---
\@->\spacefactor
\@m
l.62 \newincludegraphics
[scale=0.1]{fig1.eps}


What could be the cause of this error, and is there a workaround without defining another macro to include graphics?

-

## marked as duplicate by Werner, Masroor, Mico, Kurt, Christian HupferJul 6 at 17:04

You need \makeatletter just before your new command due to the @ letter –  Christian Hupfer Jul 6 at 9:49
rather than \def\foo{scale=0.1} the intended usage is that you use \setkeys{Gin}{scale=0.1} ... \includegraphics{fg1} –  David Carlisle Jul 6 at 9:50
@DavidCarlisle I am changing the scale this way, but for some reason it doesn't have an effect. –  nrs Jul 6 at 10:01
@ChristianHupfer I tried every combination of \makeatletter and \makeatother but cannot seem to make it work, would you care to post an answer? –  nrs Jul 6 at 10:07
–  David Carlisle Jul 6 at 10:11

the keyval parser does not expand macros, but you can do

\expandafter\includegraphics\expandafter[\foo]{fig1.eps}

to expand \foo first if you need to.

-

You can define a new key:

\documentclass[a4paper,10pt,twoside]{book}
\usepackage{graphicx}

\makeatletter
\define@key{Gin}{foo}[]{\setkeys{Gin}{scale=0.1}}
\makeatother

\begin{document}

\includegraphics[foo]{example-image.pdf}

\end{document}


The second argument to \setkeys is not expanded, and the optional argument to \includegraphics like in

\includegraphics[<whatever>]{file}


is basically managed as \setkey{Gin}{<whatever>}`.

-