6

I'd like to be able to make a macro \foo whose definition would look something like

\newcommand{\foo}{
  \ifintextmode{abc}
  \ifinmathmode{x\cdot y\otimes z}
}

so that

\foo $\foo$

produces

enter image description here

This TeX.SE question seems somewhat related, but I didn't quite understand the answer and it does not directly solve my issue. I'm sorry I don't have anything more to offer, in terms of making any progress myself.

11
  • 1
    Can you make a significant example for this?
    – egreg
    Apr 2, 2013 at 22:05
  • The question you linked at is trying to do the opposite : detect if there is math inside the arguments of the macro. Its solution could be adapted if there was no predefined macro for this, though.
    – T. Verron
    Apr 2, 2013 at 22:05
  • 1
    @egreg: I'm not sure what you mean - are you asking how I'm actually planning to use this? If so, the use I had in mind was making the macro \adeles produce ad\'eles in text mode and \mathbb{A} in math mode. I generally try to abstract such specifics away in my questions, if they don't seem like they'd be important. Apr 2, 2013 at 22:09
  • Related Question: How do I make a macro require math mode?. Apr 2, 2013 at 22:34
  • @ZevChonoles That's what I feared. You gain nothing by having a macro that does very different things according to the context. You're bound to lose track of where you are. But of course it's only my opinion. After 25+ years of TeX. ;-)
    – egreg
    Apr 2, 2013 at 22:39

1 Answer 1

12
\DeclareRobustCommand{\foo}{%
  \ifmmode
   x\cdot y\otimes z%
  \else
  abc%
   \fi
}

I should say though it's generally a bad idea to do this (or use the similar \ensuremath command) as TeX has a built in distinction between text and math and really the author needs to know at all times whether the document is in text or math mode, and use suitable commands in each case.

Consider the accent commands; \hat could have been defined as above to work in text or math mode, but instead plain TeX (and LaTeX) define \hat for math mode and \^ for text mode. The implementation and semantics of the two commands are very different and superficially using the same syntax for text and math would not have been helpful.

2
  • In addition, I strongly suggest to implement the macro in a single line as so: \DeclareRobustCommand{\forcemmode}[1]{\ifmmode#1\else$#1$\fi} to avoid any troubles with extra inserted spaces or tab.
    – Welgriv
    May 24, 2022 at 9:34
  • @Welgriv I wouldn't, it makes the code very hard to maintain, and the version as I posted here will not add any spaces. May 24, 2022 at 9:38

You must log in to answer this question.

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