# Extra space after new command using xparse

I was trying to write a macro that could take either one of two arguments and produce different outputs for both cases. For that, I used to package xparse. Here is the macro I wrote:

\documentclass[a4paper,english, makeindex, final]{memoir}

\usepackage[demo]{graphicx}

\usepackage{xspace}
\usepackage{xparse}
\DeclareDocumentCommand\fig{om}{
\IfNoValueTF{#1}
{(fig. \ref{#2})\xspace}
{(fig. \ref{#2}.#1)\xspace}
}
%------------------------------------------------------------
\begin{document}

This it text I want to type \fig[A]{fig1}. And it is the same with the only one argument as well \fig{fig1}.

\begin{figure}[!htbp]
\begin{center}
\includegraphics[width=0.8\linewidth]{}
\caption[test figure]{Test figure. A big black box}
\label{fig1}
\end{center}
\end{figure}

\end{document}


The problem is that the new command generate automatically a space after the text and I can figure out how to remove it. I tried the xspace package but it does not seem to work...

-

You have two spurious spaces:

\DeclareDocumentCommand\fig{om}{%
\IfNoValueTF{#1}
{(fig. \ref{#2})\xspace}
{(fig. \ref{#2}.#1)\xspace}%
}


Of course the definition is cleaner with

\DeclareDocumentCommand\fig{om}{%
\IfNoValueTF{#1}
{(fig. \ref{#2})}
{(fig. \ref{#2}.#1)}%
\xspace
}


There is no need to terminate the two lines where I haven't put % because TeX doesn't consider spaces when looking for arguments; they don't harm, anyway, so you may prefer

\DeclareDocumentCommand\fig{om}{%
\IfNoValueTF{#1}%
{(fig. \ref{#2})}%
{(fig. \ref{#2}.#1)}%
\xspace
}


-
It worked perfectly. Thanks a lot. One last question though: what exactly is the purpose of the % at the end of the lines? – Wiliam Nov 29 '12 at 14:59
@Wiliam An end of line counts as a space. With % we make TeX not see it. – egreg Nov 29 '12 at 14:59
OK thanks again – Wiliam Nov 29 '12 at 15:00