8

How can I get a command to eat an unnecessary space, consider the below:

\documentclass{article}
\newcommand{\mycommand}[1]{#1}
\begin{document}

    %Creates single spaces
    Discussed \mycommand{before} in section 1

    %Creaetes a double space
    Discussed \mycommand{} in section 3

\end{document}

I have a more complicated command elsewhere, sometimes the result is 'empty' in which case a double space is created (which I don't want), the above is in effect what is happening.

I need some logic that detects if the argument is empty, and if so, eats one of the spaces.

Werner
  • 603,163

2 Answers2

8

In this minimal example, just declare

\newcommand{\mycommand}[1]{#1\unskip}

enter image description here

Werner
  • 603,163
  • That is what I wanted. Cheers. – Nicholas Hamilton Jun 22 '13 at 02:26
  • @ADP beware the start of a paragraph, you might want \leavevmode#1\unskip – David Carlisle Jun 22 '13 at 23:20
  • Pretty obvious, but: if you were doing more complicated stuff within the command, you should put \unskip at the end of everthing. As a silly example: \newcommand{\mycommand}[1]{\textbf{#1}\unskip}. I had a less trivial example that I thought printed #1 but ...#1\unskip... is not the answer in general! – Joe Corneli Nov 27 '13 at 18:53
2

I think this should do the trick:

\newcommand{\mycommand}[1]{%
\if\relax\detokenize{#1}\relax%
\ignorespaces%
\else%
#1%
\fi}