3

How can I program a command \mycommand such, that a white space is set printed behind it if a white space is used after it and no white space is printed if no white space is used (e.g. when punctuation is used) without using {} after the command usage. I understand that this is kind of against how the LaTeX syntax works, but maybe there is a way around it.

With

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\newcommand{\mycommand}[1][i]{\ensuremath{\frac{#1}{2}}}
\begin{document}
This \mycommand[1] is \mycommand, \mycommand and \mycommand.
\end{document}

I get

enter image description here

but I would like to get

enter image description here

without having to add {} behind the third \mycommand.

Make42
  • 1,772
  • 1
    Since it is a fraction, so in math mode, you should keep it in math; there is no space problem with $\mycommand$ – egreg Mar 29 '17 at 09:43

1 Answers1

4

The xspace package is exactly what you need:

\documentclass{article}

\usepackage{xspace}
\newcommand{\mycommand}[1][i]{\ensuremath{\frac{#1}{2}}\xspace}

\begin{document}

This \mycommand[1] is \mycommand, \mycommand and \mycommand.

\end{document}

See also, however, Drawbacks of xspace.

Leo Liu
  • 77,365
  • Considering the drawbacks: In your experience: Does it often happen that there is an issue with xspace? – Make42 Mar 29 '17 at 09:38
  • @Make42: In rare cases, \xspace just does not work or it may add an extra space. And \xspaceaddexceptions might help. It isn't serious problems, but you may need to know that. – Leo Liu Mar 29 '17 at 09:45
  • For future readers: See section 1.1 in http://texdoc.net/texmf-dist/doc/latex/tools/xspace.pdf regarding \xspaceaddexceptions and see http://tex.stackexchange.com/questions/76128/xspace-doesn-t-handle – Make42 Mar 29 '17 at 09:52
  • @Make42 but as egreg commented above, it is better not to use \ensuremath then you don't need xspace either (no criticism to Leo Liu who's answered the question as asked:-) – David Carlisle Mar 29 '17 at 10:50
  • @DavidCarlisle: I don't see how not using \ensuremath is helping with the issue at hand. – Make42 Mar 29 '17 at 11:46
  • @Make42 see egreg's comment above: the standard markup would be ...$\mycommand$ and ... which has no problem with dropped space. – David Carlisle Mar 29 '17 at 12:29
  • @DavidCarlisle: Ah ok. This is what I had used so far. This approach can also be used with \ensuremath and a blank after \ensuremath. Then one only need to use $$ when punctuation is followed in the text. – Make42 Mar 29 '17 at 12:43