# [texhax] xspace

Morten Høgholm morten.hoegholm at gmail.com
Mon Dec 11 16:00:40 CET 2006

Hello Tom,

> I have this macro defined to test a reference and give me some alternate
> text if the label doesn't exist.
>
> \newcommand{\testref}[3]{%
>    \expandafter\ifx\csname r@#1\endcsname\relax #2\else #3\fi}
>
> It's used like this:
>
> \renewcommand{\tableref}[1]{\testref{#1}{User
> Guide\xspace}{Table~\ref{#1}\xspace}}
>
> It exists so that I can copy chunks of text from one document into
> another without having to go back and fix all the cross-references.
>
> The \xspace macro in the arguments to \testref is apparently seeing
> a token that makes it think a space is required, and inserting a space
> for me, no matter what.
>
> My questions:
>
>   o What token does the \xspace macro think is following it in a sentence
>     like "The \tableref{mg} lists the elements..."

It sees either an \else  or a \fi.  Neither of these are on the default
list of exceptions and since you're using an older version of xspace, this
makes it insert a space immediately.

>
>   o How can I persuade it to look at the token that follows the \tableref
>     macro instead of whatever it's seeing?

Upgrade to the current version of xspace will solve it because it'll try
to expand it's way out of situations like this.

Another possibility is to define \testref in such a way that the code to
be executed is moved outside of the conditional:

\newcommand{\testref}[3]{%
\expandafter\ifx\csname r@#1\endcsname\relax
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{#2}{#3}}

Even easier is to make use of the functionality provided by the LaTeX
kernel:

\newcommand{\testref}[3]{\@ifundefined{r@#1}{#2}{#3}}

Cheers,
--
Morten