141

I have gotten into the habit of using \ensuremath around math components in every macro that I define, so that I can use the same macro inside and outside of math mode. But egreg's comments in \DeclareMathOperator won't take arguments has me thinking that perhaps I should not be doing this all the time:

It's not a good idea, in my opinion, to add \ensuremath; why should it be? Disclaimer: this is part of my \ensuremath-only-when-really-needed campaign. :) - egreg

A related comment in Force line break inside a \lim argument in align environment:

Why \ensuremath? Wouldn't $\scriptstyle#1$ be easier to read? - egreg

In this case it was required to use math mode as we were within a \makebox (i.e., text mode). So, out of habit I used \ensuremath but egreg was right that in this case using $...$ would have worked just as well and was certainly easier to read. But, even in this case I still prefer to use \ensuremath so that it is more obvious that this can be used in math and text mode without having to think about \makebox being in text mode.

So, is there really any harm in always using \ensuremath, at least for any of my personal macros? I realize that there is a slight extra overhead in processing, but is there something else to consider?

If there are other considerations when they macros are coming packages that are intended for general purpose use, I would be interested in those as well. The most obvious one is that we may want to make sure that the user of the macro knows that this macro requires math mode, so require them to only use the macro in math mode.

Since this references egreg's campaign, I felt I should include a MWE for new users as per my MWE-as-often-as-possible campaign:

\documentclass{article}

\newcommand{\FunctionF}{\ensuremath{x^2}}%

\begin{document}
Text mode: \FunctionF

Math mode: $G(x) = x^3 - \FunctionF$
\end{document}
5
  • 39
    I won't answer, at least for one day, I promise. :)
    – egreg
    Commented Nov 14, 2011 at 18:13
  • 6
    I know it's a close call, but tagging this question with mathmode seemed appropriate. ;-)
    – lockstep
    Commented Nov 14, 2011 at 18:33
  • 7
    FWIW, in ConTeXt I have been campaigning to remove $ altogether and let everyone enter the math mode using \mathematics{...}, \math{...} or \m{...} (all of which are essentially equivalent to LaTeX's \ensuremath{...}. So, I am also interested in knowing if there is any harm in using the latter.
    – Aditya
    Commented Nov 14, 2011 at 18:36
  • Related Question: Wrap many math macros into \ensuremath. Commented Apr 19, 2018 at 17:03
  • As a useful tip, if you intend to use ensuremath, make sure that (a) You intend to use the command both inside and outside of mathmode; and (b) you test the command in a math environment as well as in a text setting. ensuremath commands can disrupt flow or have unexpected spacings. It might be the case that the spacing is unsatisfactory if you are not in math mode, in which case you want the editor to throw an error if you are not in it. If you are satisfied after these two conditions, use it.
    – Kraigolas
    Commented Jul 9, 2019 at 12:19

4 Answers 4

80

Two objections come to mind:

  • If you don't know you will be entering math mode, then you may write something "semantically" correct that breaks.

For example:

\documentclass{article}
\newcommand\mathmacro[1][A]{\ensuremath{{#1}_1}}
\begin{document}
 \mathmacro[$x^2$] % The dollar signs *leave* math mode
\end{document}

What's going on here is that \mathmacro[$x^2$] expands to

\ensuremath{{$x^2$}_1}

which expands to (effectively)

\ifmmode
 {$x^2$}_1
\else
 ${$x^2$}_1$
\fi

and you can see that if you write it outside of math mode, the second branch is taken, so the first dollar sign brings you into math mode and the one at the front of $x^2$ takes you out of it, with the reverse operation happening afterwards. This gives an error.

Of course, you aren't supposed to do that, since \mathmacro is actually a "math macro usable in text mode", so you should think of the thing between the brackets of its argument as being in math mode. Alas, this confuses both the author and the text editor's syntax highlighting, since it is a nonstandard assumption.

Edit: I would define this macro as:

\newcommand\mathmacro[1][A]{{#1}_1}

and use it as:

$x^2$ sub one: $\mathmacro[x^2]$.

This way, the parts that are math are clearly math.

  • In the unlikely event that you or some package sets \everymath, you will be very surprised when your apparently text-mode macros start to look different.

On the subject of semantics, though, the issue is clear: \ensuremath breaks the separation between math and text, which are two very different things. TeX even has the distinction built in: different fonts, different spacing rules, different parsing rules. You can probably construct a lot more counterexamples by exploiting these.

What I mean by this is that in the following situation:

\documentclass{article}
\newcommand\mathmacro[1][A]{\ensuremath{{#1}_1}}
\begin{document}
 A sub one: \mathmacro

 \bfseries A sub one: \mathmacro
\end{document}

you may be surprised that the bold text does not extend to the contents of the apparently text-mode \mathmacro.

What I'm saying is not so much that \ensuremath actually breaks anything as that it violates your expectations to the point that it makes things harder rather than easier.

8
  • Can you add some more detail as to why the dollar signs leave math mode? Also, how should the \mathmacro be defined for this case. Commented Nov 14, 2011 at 19:30
  • 1
    Also, not sure I understand the other comments: I am only using \ensuremath for something that always needs to be math. Perhaps you are referring to this question about what is the proper way to use ensuremath to define a macro useable in and out of math mode, but think that is a totally different issue than what you mean. Commented Nov 14, 2011 at 19:34
  • 1
    @PeterGrill: Perhaps my edit makes my intent clearer?
    – Ryan Reich
    Commented Nov 15, 2011 at 0:54
  • 1
    But in both of those cases, I would like to see a definition of \mathmacro so you don't have those issues? In the first one I don't know how it should be specified so that it can be used in the manner you used it, and in the second one the only thing I can see is that if the user explicitly entered math mode the intent would be clearer, and the user would sill be surprised and perhaps realize a bit quicker why the bold text did not extend into the math. Commented Nov 15, 2011 at 1:21
  • @PeterGrill: My point is that you can't specify it so that it can both be used "naked", without explicit $...$, and also consistently with the expected state of TeX with respect to math mode. I would define it without the \ensuremath and enter math mode explicitly with each use. In the second example, it's true that one might be surprised not to get bold math even with an explicit math shift, but then they would remember "oh, font changes don't affect math, ok". As written, they might not even realize it's a math issue for a while.
    – Ryan Reich
    Commented Nov 15, 2011 at 1:25
35

There's nothing bad about \ensuremath per se. However, if we examine this question of yours I see no advantage whatsoever in being able to say \FunctionF in both text mode and math mode, instead of always sticking to \(\FunctionF\) (or $\FunctionF$ as others might prefer). There are many other posts here on TeX.SX that do the same. Take this one: what's the advantage of being able to write the ring~\Z{n} instead of the ring~$\Z{n}$ when, maybe, one has also to write the ring $\Z{m}\times\Z{n}$, which is highly probable if one wants that command?

Another post has the following code:

\newcommand{\vrel}[3]{
\vcenter{\halign{\hfill##\hfill\cr
\ensuremath{#1}\cr
\rotatebox[origin=c]{270}{\ensuremath{#2}}\cr
\ensuremath{#3}\cr
}}}

This is bad programming, in my opinion, as what's inside \ensuremath is to be typeset in math mode; the "correct" code should be

\newcommand{\vrel}[3]{
\vcenter{\mathsurround=0pt \halign{\hfill##\hfill\cr
  $#1$}\cr
  \rotatebox[origin=c]{270}{$#2$}\cr
  $#3$\cr
}}}

Other cases in which \ensuremath makes things more complicated than necessary are this one and this one.

4
  • Since you are doing this \ensuremath-only-when-really-needed campaign, let me ask here: what if I use only \ensuremath and no $'s? Will that still mess things up? I wrote quite a bit but haven't encounter problem with that strategy, I just want to know if it will eventually go wrong.
    – h__
    Commented Feb 20, 2013 at 6:52
  • 7
    @hyh Do you mean \ensuremath{a+b=c} instead of \(a+b=c\) or $a+b=c$? I'd consider it a perversion. ;-)
    – egreg
    Commented Feb 20, 2013 at 7:29
  • I did this: \newcommand{\m}{\ensuremath} and on my editor whenever I hit m then tab I got \m{} appear and the caret is put between { and }. No messy $'s at all.
    – h__
    Commented Feb 20, 2013 at 7:32
  • 5
    You forgot to mention \Z{n} $\times$ \Z{n} ;)
    – yo'
    Commented Apr 30, 2013 at 14:13
14

This comment of user egreg to the question "Why are so many symbols restricted to math mode?" is very valuable:

If it allowed this, people would write \alpha+\beta getting the space wrong. Math should always treated as math, even single symbols; consider it as markup, if you want.

Put simply, use of \ensuremath can easily teach users of the macro in question to be lazy about explicitly switching to math mode (which is often "not needed" for all symbols to appear on the page if one has no super- or subscripts), with the consequence that spacing for an expression can be wrong if the expression should follow mathmode spacing but is typeset in horizontal textmode. This defeats one purpose of (La)TeX, namely correct typesetting of mathematical expressions.

If users can type "\myalpha+\mybeta" (or "\myalpha + \mybeta", and shouldn't it be "\myalpha{} + \mybeta{}" then? etc.) where they should be typing "\(\myalpha+\mybeta\)", that might lead to bad habits, with the spacing not being as it should.

4
  • 2
    I don't follow your claim that because \ensuremath might let some LaTeX users become lazy (in itself a debatable statement), the spacing in math expressions would somehow become incorrect.
    – Mico
    Commented Feb 25, 2013 at 2:38
  • @Mico See my edit, which should clarify things. You've never seen questionable typesetting by "casual" users of LaTeX? ;-) Especially for spacing matters, a lot of casual users make mistakes or have no good sense of what good practice is. Commented Feb 25, 2013 at 3:02
  • 2
    @Mico Maybe it isn't about encouraging laziness but, rather, about encouraging bad habits where this is not a matter of laziness. If somebody is coming from a word processor, not thinking in terms of modes is natural; thinking in terms of modes is alien. So if it more-or-less works without switching modes, you don't need to be lazy to get into the habit of not switching in LaTeX either. But I don't find the accusation of laziness a helpful or illuminating one. It chalks up to character defects what would be better understood in terms of word processor vs. LaTeX conceptual schemes.
    – cfr
    Commented Sep 15, 2015 at 22:59
  • Why even have a macro language at all if you aren't going to use it to let users be lazy and avoid having to deal with the low level details of the interface? Wouldn't the better solution be to fix the inconsistent appearance of math operators between math and TeX mode or at least warn the user? Ok, maybe you can't avoid the need to specify but surely a well designed system could spit out a warning whenever a symbol that had both math and non-math interpretations occurred between math mode elements. Commented Feb 26 at 21:00
11

I think the answer is provided in fixltx2e, although for most cases I don't see it as a problem, from the documentation:

4.4.1   Notes on the implementation strategy

Pr/3400 made \@fnsymbol decide between text-mode and math-mode, which requires a certain level of robustness somewhere as the decision between text and math must be made at typesetting time and not when inside \protected@edef or similar commands. One way of dealing with this is to make sure the value seen by \@fnsymbol is a fully expanded number, which could be handled by code such as

\def\fnsymbol#1{\expandafter\@fnsymbol
  \expandafter{\the\csname c@#1\endcsname}}

This would be a good solution if everybody used the high level commands only by writing code like \fnsymbol{footnote}. Unfortunately many classes (including the standard classes) and packages use the internal forms directly as in \@fnsymbol\c@footnote so the easy solution of changing \fnsymbol would break code that had worked for the past 20 years.

Therefore the implementation here makes \@fnsymbol itself a non-robust command again and instead uses a new robust command \TextOrMath, which will take care of typesetting either the math or the text symbol. In order to do so, we face an age old problem and unsolvable problem in TeX: A reliable test for math mode that doesn’t destroy kerning. Fortunately this problem can be solved when using eTeX so if you use this as engine for your LaTeX format, as recommended by the LaTeX3 Project, you will get a fully functioning \TextOrMath command with no side effects. If you use regular TeX as engine for your LaTeX format then we have to choose between the lesser of two evils: 1) breaking ligatures and preventing kerning or 2) face the risk of choosing text-mode at the beginning of an alignment cell, which was suppodes to be math-mode. We have decided upon 1) as is costumary for regular robust commands in LaTeX.

6
  • 3
    I replaced the .dtx source with corresponding output, hope you don't mind. Commented Nov 14, 2011 at 22:00
  • @AndreyVihrov Thanks, is a very good idea, didn't think of it:)
    – yannisl
    Commented Nov 14, 2011 at 22:29
  • So does this mean that we should be using \TextOrMath macro? Could you add an example of how to use this? Commented Nov 15, 2011 at 16:32
  • 1
    @PeterGrill IMHO yes. Example \newcommand{\mybeta}{\TextOrMath{$\beta$\xspace}{\beta}}.
    – yannisl
    Commented Nov 16, 2011 at 1:56
  • @YiannisLazarides that has one problem: \mybeta\ldots gives a small space between the β and the ellipsis. Try moving the \xspace to the end of the command, i.e. after the \TextOrMath. I also recommend using \( and \) in macros for better error messages.
    – kahen
    Commented Nov 16, 2011 at 5:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .