I've several times seen the recommendation to put a \relax before \ifmmode in a macro. I've tried searching for an explanation of this several times on this site, but hadn't been able to find one. An answer by David Carlisle to a different question I asked suddenly made things click, and I thought it'd be worthwhile to submit a question that might help others more effectively find the explanation of this.
Asked
Active
Viewed 286 times
7
dubiousjim
- 1,035
- 1
- 8
- 14
-
It's a nice effort, but I think that there can't be said more than in http://tex.stackexchange.com/questions/27592/ifmmode-doesnt-seem-to-work-correctly-inside-an-array-environment , which makes it a dupe IMHO... – yo' Aug 20 '14 at 13:24
-
Sure, I'm happy for the question be closed as a dupe, if it will still show up in searches and point others to the fuller answers. I considered suggesting that myself. – dubiousjim Aug 20 '14 at 13:26
1 Answers
5
In short, the explanation is that in several contexts:
\def\foo{\ifmmode alpha\else beta\fi}
...$\foo ...$ ...
it won't yet be visible that we're in math mode when \foo is invoked. But after \relax, then \ifmmode will then be able to see that we are in math mode.
Knowing the explanation, I was then able to find these further discussions of it on this site:
- \ifmmode doesn't seem to work correctly inside an array environment
- Unexpect differences between calling \ifmmode from within a command and outside a command
But these weren't easy to find until I did know the explanation.
For further discussion, one should consult Chapter 22 of The TeX Book, esp. p. 238.
dubiousjim
- 1,035
- 1
- 8
- 14
-
3note that
\relaxsolves the problem of math mode at start of alignment but can cause problems in the non math case (as it breaks ligatures and kerning) and still fails in\writeso a protected definition is usually preferable. – David Carlisle Aug 20 '14 at 14:39