15

(This may be a duplicate, but I could not find an answer among the pile of similar questions...)

Suppose we have the following command:

% <month> <year> <month> <year>
\newcommand{\timeperiod}[4] {%
#1 #2 -- #3 #4%
}

As long as all arguments are provided, everything works fine. But were one to omit e.g. the second month argument (#3), an extra space would appear between the dash and the ending year:

June 2000 – July 2001
June 2000 –  2001

How could I suppress that extra space? Or better yet, how could I make LaTeX ignore any spacing between empty command arguments?

thkala
  • 415

3 Answers3

16

Let's see what happens:

\timeperiod{June}{2000}{July}{2001}

becomes

June•2000•--•July•2001

(where I use to make spaces more visible). With

\timeperiod{June}{2000}{}{2001}

you get

June•2000•--••2001

Indeed consecutive spaces are reduced to one only when TeX is reading input and converting it to tokens; the definition text has already been tokenized, so those two spaces remain. You can avoid the double space by saying

\newcommand{\timeperiod}[4]{%
  #1 #2 -- #3\unskip\space#4%
}

If #3 is empty, the \unskip will remove the space between -- and the (empty) argument. If #3 is not empty, \unskip will do nothing.

egreg
  • 1,121,712
9

use

\newcommand\timeperiod[4] {#1 #2 -- \ifx\relax#3\relax\else#3~\fi#4}

0

You can also use the xspace package (Insert a space after a command: {}, vs \ , vs \space):

\usepackage{xspace}

% <month> <year> <month> <year>
\newcommand{\timeperiod}[4] {%
#1\xspace#2\xspace--\xspace#3\xspace#4%
}

But do not forget about Drawbacks of xspace

user
  • 4,745