[XeTeX] newcommand with optional arguments

Ross Moore ross at ics.mq.edu.au
Mon Mar 3 22:30:51 CET 2008


Hi Sven,

On 03/03/2008, at 11:42 PM, Sven Siegmund wrote:

> Well, actually I had do change it a bit: The whitespace shoud have
> been put to the else stuff:
>
> \newcommand{\nuu}[2][]{%
>        \textit{#2}%
>        \ifx#1\empty
>        \else
>               \ `#1'
>        \fi
> }

In fact this is not correct.
There are at least 2 problems with this coding.

Firstly, look at the result of   \nuu[22]{this} .
What do you expect?
What do you actually get?


Secondly, it doesn't generalise easily.
Suppose you want to issue a message (or do something else)
whenever there is no optional argument provided.
Presumably you would adjust the coding to be something
like:

        \ifx#1\empty
           \typeout{no 1st argument for \string\nuu{#2}}%
        \else
               \ `#1'
        \fi

But with this coding you will never see the message,
except in sporadic cases where there *is* an optional
argument; e.g.,

    \nuu[22]{this 1}
    \nuu[\empty]{this 2}



Better coding (why?) would be:

        \ifx\empty#1\empty
           \typeout{no 1st argument for \string\nuu{#2}}%
        \else


But this still gets it wrong on things like:

    \nuu[\empty and then some]{this 3}



A more bullet-proof approach is:

\makeatletter
\def\myempty@{}
\makeatother
\let\testtheargument\relax

\newcommand{\nuu}[2][]{%
   \def\testtheargument{#1}%
   \textit{#2}%
   \expandafter\ifx\expandafter\myempty@\testtheargument\myempty@
    \typeout{no 1st argument for \string\nuu{#2}}%
   \else
    \ `#1'
   \fi
}

But even this has the side-effect of leaving \testtheargument
with a value different from what it was before \nuu is encountered.


This technicality is overcome using the following:


\newcommand{\nuu}[2][]{%
  \begingroup
   \def\testtheargument{#1}%
   \textit{#2}%
   \expandafter\ifx\expandafter\myempty@\testtheargument\myempty@
    \typeout{no 1st argument for \string\nuu{#2}}%
   \else
    \ `#1'
   \fi
  \endgroup
}



> S.

And this may not be the end of the story; but enough for now.


Hope this helps,

	Ross

------------------------------------------------------------------------
Ross Moore                                         ross at maths.mq.edu.au
Mathematics Department                             office: E7A-419
Macquarie University                               tel: +61 +2 9850 8955
Sydney, Australia  2109                            fax: +61 +2 9850 8114
------------------------------------------------------------------------




More information about the XeTeX mailing list