Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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...

enter image description here

share|improve this question
add comment

1 Answer

up vote 9 down vote accepted

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
}

enter image description here

share|improve this answer
    
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
1  
@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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.