Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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!

share|improve this question
add comment

3 Answers

up vote 19 down vote accepted

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:

share|improve this answer
add comment

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)

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.