# How to define a macro conditionally based on whether it is being used in text mode or math mode?

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

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.

-
Can you make a significant example for this? –  egreg Apr 2 '13 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 '13 at 22:05
@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. –  Zev Chonoles Apr 2 '13 at 22:09
Related Question: How do I make a macro require math mode?. –  Peter Grill Apr 2 '13 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 '13 at 22:39

\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.

-