12.13 xspace package

This is an add-on package, not part of core LaTeX. Synopsis:

\usepackage{xspace}
  ...
\newcommand{...}{...\xspace}

The \xspace macro, when used at the end of a command definition, adds a space unless the command is followed by certain punctuation characters.

After a control sequence that is a control word (see Control sequence, control word and control symbol, as opposed to control symbols such as \$), TeX gobbles blank characters. Thus, in the first sentence below, the output has ‘Vermont’ placed snugly against the period, without any intervening space, despite the space in the input.

\newcommand{\VT}{Vermont}
Our college is in \VT .
\VT{} summers are nice.

But because of the gobbling, the second sentence needs the empty curly braces or else there would be no space separating ‘Vermont’ from ‘summers’. (Many authors instead use a backslash-space \ for this. See Backslash-space, \ .)

The xspace package provides \xspace. It is for writing commands which are designed to be used mainly in text. It must be placed at the very end of the definition of these commands. It inserts a space after that command unless what immediately follows is in a list of exceptions. In this example, the empty braces are not needed.

\newcommand{\VT}{Vermont\xspace}
Our college is in \VT .
\VT summers are nice.

The default exception list contains the characters ,.'/?;:!~-), the open curly brace and the backslash-space command discussed above, and the commands \footnote or \footnotemark. You can add to that list as with \xspaceaddexceptions{\myfni \myfnii} which adds \myfni and \myfnii to the list; and you can remove from that list as with \xspaceremoveexception{!}.

A comment: many experts prefer not to use \xspace. Putting it in a definition means that the command will usually get the spacing right. But it isn’t easy to predict when to enter empty braces because \xspace will get it wrong, such as when it is followed by another command, and so \xspace can make editing material harder and more error-prone than instead of always inserting the empty braces.


Unofficial LaTeX2e reference manual