Dealing with space after commands
Posted Tue Oct 09 18:03:56 -0500 2007
Customised commands are an important tool for saving time and ensuring consistency in LaTeX documents, particularly for those die-hard hand coders like me who don't use LyX... :)
The nature of TeX is such, though, that whitespace after a command will be ignored; and this can be a problem if we are using a command to expand a fixed string that is awkward to rewrite each time it is needed. For example, take the definition
\newcommand{\dfn}{\textrm{$\delta$-function}}
The problem is that if we later want to write something like “...lorem ipsum dolor \dfn sit amet...” (unlikely, I admit), then the space after the command will get eaten up and the result will be equivalent to “...lorem ipsum dolor $\delta$-functionsit amet...”.
One simple but inelegant solution is to remember to stick another backslash after the command, so that the trailing space becomes a backslash-space and is therefore always present. Hence, “...dolor \dfn\ sit...”. Integrating this into the command, viz.
\newcommand{\dfn}{\textrm{$\delta$-function}\ }
may seem like a good idea, but if the command appears at the end of a sentence somewhere we will get the opposite problem—a space where we don't want one.
The best solution for most such purposes is to use the xspace package, which will usually be able to guess when you want a space and when you don't. So, try
\usepackage{xspace}
\newcommand{\dfn}{\textrm{$\delta$-function}\xspace}
and you should be able to use the \dfn command wherever it's needed without having to remember to add an extra backslash or worry if it falls at the end of a sentence. The \xspace command can be used in all sorts of similar scenarios. I've certainly found it very useful.
