[Tex/LaTex] Pass named arguments to macro

key-valuemacros

I notice that includegraphics takes what seems to be named arguments:

\includegraphics[width=50,height=25,trim=1 2 3 4,clip]{an_img.png}

I'd like to wrap a number of my includegraphics calls in a macro, so that the following commands

\happygraphics{an_img.png}
\happygraphics{an_img.png}{rotate=90}

expand to

\includegraphics[width=50,height=25,trim=1 2 3 4,clip]{an_img.png}
\includegraphics[width=50,height=25,trim=1 2 3 4,clip,rotate=90]{an_img.png}

respectively.

I've tried using

\DeclareDocumentCommand\song{ m g }{
  \includegraphics[width=50,height=25,trim=1 2 3 4,clip,rotate=90\IfNoValueF{#2}{,#2}]{#1}
}

but I get the dreaded

! Package keyval Error: keepaspectratio,trim=0 0 0.5in 0,clip undefined.

error.

How should I go about doing this?

Best Answer

A slightly modified interface via the definition

\newcommand{\happygraphics}[2][,]{%
  \includegraphics[width=50,height=25,trim=1 2 3 4,clip,#1]{#2}}%

would allow to add options as needed to \happygraphics[<options>]{<file>}.

A similar interface is provided through xparse:

\usepackage{xparse}% http://ctan.org/pkg/xparse
\NewDocumentCommand{\happygraphics}{O{,} m}{%
  \includegraphics[width=50,height=25,trim=1 2 3 4,clip,#1]{#2}}%

The above takes advantage of supplying empty (default) key-values as ,.

Since the key-value interface is comfortable with supplying empty options (or consecutive commas ,,,...), there's no need for extra testing of the existence of an optional argument. Unless, of course, you want to do more based on whether or not the use supplied an optional argument.