# No space present after ensuremath

When I insert a short maths section in a sentence, it renders fine with a space each side as expected:

...returned $\mathcal{P}$ from...


If I define a command to do the same thing, it also renders with a space each side:

\newcommand{\pc}{\mathcal{P}}
...
...returned $\pc$ from...


However, if I define a function with ensuremath, the space following the expression disappears:

\newcommand{\pc}{\ensuremath{\mathcal{P}}}
...
...returned \pc from...


Why does ensuremath do this? Is there a way to make it more analogous to manually entering math mode?

Thanks!

-

This has nothing to do with \ensuremath. Spaces after macros are ignored independent of whether they contain math or not.

Of course, you can't simply add a space to the definition, since this will incorrectly add spaces before e.g. punctuation marks, where you don't want them. So there are two ways around this. One is to simply insert an overt space whenever you need on using \:

returned \pc\ from...


The other solution is to use the xspace package, which inserts a space automatically and takes care not to insert the space before punctuation.

\usepackage{xspace}
\newcommand*{\pc}{\ensuremath{\mathcal{P}}\xspace}


Then you don't need to type the explicit space yourself.

Please note that there are various disadvantages to using both \ensuremath and xspace. See:

-
There's another option of course, and that's using some braces: \pc{} or {\pc}. – Joshua Taylor Jun 27 '14 at 21:02

I would recommend you not to use \ensuremath for such thing, or you'll be tempted to write Let \pc = 3 be given... instead of Let $\pc=3$ be given... (The first variant will always leed to incorrect spacing.)

You can simply say:

\newcommand\pc{\mathcal{P}}


and use it as I suggested before:

Here, $\pc$ is ...


This way, it is most consistent, you are in control of things, and two dollars are not so much more to type. As well, you can do without the xspace which again makes you lose some control over your TeX code.

-

A simple workaround, could be to simple add {} after the macro or to ensure that the macro has an argument. I had the same problem with

\newcommand{\veca}{\ensuremath{\mathbf{a}}}


but using

\newcommand{\ve}[1]{\ensuremath{\mathbf{#1}}}


I would have liked to use

\newcommand{\vec}[1]{\ensuremath{\mathbf{#1}}}


but \vec was already taken, and I didnt want to redefine it.

-
This is a very short answer ;-) Welcome to TeX.SX! – Christian Hupfer Sep 26 '14 at 13:19
Thanks. I have received so much help here, I hope can help out in return... Just to keep karma on my side and all... :-) – Quantifeye Sep 26 '14 at 14:01

Another improvement could be to redefine the \ensuremath command itself with something like

\newcommand{\enmath}[1]{\ensuremath{#1}\xspace}


This way you can define your own command

\newcommand{\pc}{\enmath{\mathcal{P}}}


(I know this IS trivial, but I think it could be a useful suggestion for beginners, as it is now for me)

-