2

I have defined a macro like that: \newcommand{\code}[1]{\texttt{#1}\xspace}

In some situations, I'd like to write the plural of some object and the trailing (plural) 's'-character should not be marked as code. So it should look like that: ClassInstances.

However, when I do \code{ClassInstance}s I get an extra space, i.e. it will look like: ClassInstance s.

What can I do?

Edit

Considering @egreg's answer, it seems that I have left out an essential part of the macro. In fact, the definition of \code also modifies the text color. Only then the use of \xspace seems to be necessary at all.

In order to reproduce the issue, run this minimal example:

\documentclass[10pt,a4paper]{article}
\usepackage{xcolor}
\usepackage{xspace}

\newcommand{\code}[1]{\texttt{#1}} \newcommand{\colcode}[1]{\color{blue}\texttt{#1}\color{black}} \newcommand{\colcodex}[1]{\color{blue}\texttt{#1}\color{black}\xspace}

\begin{document} Bounds are constructed by closed \code{Curve} objects.

Bounds are constructed by closed \colcode{Curve} objects.

Bounds are constructed by closed \colcodex{Curve} objects.

Sometimes we have even two \colcodex{Curve}s.

\end{document}

From this I get: enter image description here

Amos Egel
  • 155

1 Answers1

3

The only case, if any, where \xspace might be useful is when commands that take no argument are being defined.

Try with

\newcommand{\code}[1]{\texttt{#1}}

and you'll see that with

The \code{ClassInstance} is ...

\code{ClassInstance}s

the space is preserved in the first case and not added in the second one.

To put it differently, \xspace must never be used when defining commands that take arguments.


Update

The \colcode command is wrongly defined: instead, do

\newcommand{\colcode}[1]{\textcolor{blue}{\texttt{#1}}}

which would avoid both the problem of space gobbling and the need to get back to the “previous” color.

egreg
  • 1,121,712
  • Thanks for this important information. In fact, my command was slightly different from what I initially posted (I wanted to make it simpler). Please see the edited question. – Amos Egel May 27 '22 at 14:06
  • 1
    @AmosEgel \newcommand{\colcode}[1]{\textcolor{blue}{\texttt{#1}}}. See the update – egreg May 27 '22 at 14:10