# Custom command with space and following punctuation?

I want to write a custom command to produce a species name but I am having trouble getting it to work with punctuations.

The specifications for my desired output are:

• Text in italic font
• No linebreaks
• if used in text keep space after the name, if punctuation follows no space

I used

\newcommand{\rip}{\mbox{\textit{C. riparius }}}


but this produces spaces before punctuations.

I read about the \xspace package but I cant seem to get it to work correctly.

Whats the correct way to achieve this?

• Did you try \newcommand{\rip}{\emph{C.~riparius}\xspace}? – frougon Jun 30 '18 at 11:20
• Thank you, that seems to work. I could swear I tried every possible combination of \xspace and still had spaces before punctuation. :) – voiDnyx Jun 30 '18 at 11:35
• Okay, I've posted the answer with some explanations. :) – frougon Jun 30 '18 at 11:55
• – David Carlisle Jun 30 '18 at 14:32

I propose this:

\newcommand{\rip}{\textit{C.~riparius}\xspace}

• \xspace at the end does what you want with respect to whitespace and punctuation.
• Spaces inside \mbox are at natural width, which is likely to be different from other spaces on the same line. Using ~ instead of \mbox avoids this problem, i.e., with ~, your unbreakable space will have the same width as other interword spaces on the same line—which is a good thing. On the other hand, the ~ (called a tie) doesn't prevent hyphenation of “riparius”, so if you do want to prevent it, you have to take other measures (I'd say either the \mbox, or an explicit \hyphenation{riparius} in the preamble[1], which would be better for the spacing reasons I explained).

(you might want to use \emph instead of \textit if you wish the argument to be typeset in upright shape when the surroundings are already in italics, but according to egreg, this is incorrect for species names, so leaving this alternative out of the proposed solution :)

[1] If you use babel and switch between languages, \babelhyphenation may be better than \hyphenation, see this message for an example.

• Species names should always be in italics, \textit is right in this case. – egreg Jun 30 '18 at 12:12
• @egreg Okay, I've edited the answer accordingly, thanks for your comment. :) – frougon Jun 30 '18 at 12:16

I'd suggest using a command such as \species{rip}, so no issue with spaces would arise. This is also much more flexible. With the following code you can define abbreviated strings for commonly used species, but \species also allows to input one without an abbreviation.

The markup is not much heavier and it pays in terms of flexibility and semantics.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\tl_new:N \g_voidnyx_species_tl

{
\tl_gput_right:Nn \g_voidnyx_species_tl { {#1}{#2} }
}

\NewDocumentCommand{\species}{m}
{
\textit
{
\str_case:nVF { #1 } \g_voidnyx_species_tl { #1 }
}
}

\ExplSyntaxOff