10

As scientific species names should be written in italic, I have adopted a shortcut to do this in LaTex by creating a definition in the preamble:

\def\GM{{\it Gadus morhua~}} 

Then it's easy to call for \GM is a fish, which returns "Gadus morhua is a fish". Note that I have added ~ to the definition, so that I won't need to write \GM~. This works except, if I want to write The fish is called \GM., which would return "The fish is called Gadus morhua ." (with a space between morhua and period). In order to maximize my lazy writing style I would like to find a way to "eat away" that space I defined earlier. I know that a negative space exists in math mode, but writing $\GM\!$ does not lead to a right result. Is there a way adding a negative space to text mode?

Martin Scharrer
  • 262,582
Mikko
  • 735

2 Answers2

15

This is exactly what the xspace package is for. The manual says:

»After defining \newcommand{\gb}{Great Britain\xspace}, the command \gb will determine when to insert a space after itself and when not.«

Keks Dose
  • 30,892
  • Thanks! It seems not to work with \def, though. If I define \def\GM{{\it Gadus morhua\xspace}}, I'll get Gadus morhuais a fish without space – Mikko May 21 '12 at 10:41
  • 1
    @Largh Don't use \def, first of all, nor the deprecated command \it. Use \newcommand{\GM}{\textit{Gadus morhua}\xspace} instead. – egreg May 21 '12 at 10:47
  • Ops, I placed it inside \it{}. That's why it didn't work. Thanks for help! – Mikko May 21 '12 at 10:49
  • Well, thanks to David Carlisle and Morten Høgholm, who wrote the package! – Keks Dose May 21 '12 at 10:56
  • 1
    @Largh: Also \xspace must be the very last thing in the macro definition in order to be able to check for a following space. Having a } or anything after it will make it useless. – Martin Scharrer May 21 '12 at 11:54
3

Adding to what's already been said, while using xspace, I have discovered that if a macro which contains \xspace as its last argument is followed by text inside {}, then it does not insert a space between the two. In such a situation, one has to use the macro followed by an additional \ and then the text inside {}.

For instance, if I have a macro defined as -- \newcommand{\sdst}{steady-state\xspace} and I use it as -- \sdst {DYNAMICS} then the result would be "steady-stateDYNAMICS" (note the absence of space); whereas, if I use it as -- \sdst\xspace {DYNAMICS} OR \sdst\ {DYNAMICS} then I will get the desired result as -- "steady-state DYNAMICS" (note the inserted space). Just thought I should mention this xspace quirk I noticed during my use of it!

See this insightful comment by the package author David Carlisle, regarding the "oddities of xspace".

Amar
  • 956