Math mode is used in many places behind the scenes, for example in tabular
. I would say something like
\newcommand{\ContainsMathMode}[1]{\begingroup\MMusedfalse
\everymath=\expandafter{\the\everymath\MMusedtrue}%
\sbox0{#1}\endgroup}
\let\ifMMused\iffalse
\def\MMusedtrue{\global\let\ifMMused\iftrue}
\def\MMusedfalse{\global\let\ifMMused\iffalse}
Of course this is not expandable, so one has to first say \ContainsMathMode{arg}
and then use \ifMMused
to branch or, with ifthen, the test \boolean{MMused}
.
With the input
\ContainsMathMode{H$_2$O}
\ifMMused Yes\else No\fi
\ContainsMathMode{abc}
\ifMMused Yes\else No\fi
\ContainsMathMode{\begin{tabular}{c}a\end{tabular}}
\ifMMused Yes\else No\fi
we get
Yes
No
Yes
The contents of the token list \everymath
is inserted each time TeX enters in-line math mode. We add (locally) to it the command that sets the boolean to true. This boolean must be set globally, so we also need to set it to false at each call of \ContainsMathMode
.
A more LaTeX way consists in adding to the above
\makeatletter
\newcommand{\IfContainsMathMode}[1]{%
\ContainsMathMode{#1}%
\ifMMused
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother
\IfContainsMathMode{H$_2$O}{Yes}{No}
\IfContainsMathMode{abc}{Yes}{No}
\IfContainsMathMode{\begin{tabular}{c}a\end{tabular}}{Yes}{No}
This would give the same output as before.
\texorpdfstring
can do for bookmarks.