# \newcommand: How to determine if in math mode (and then include )?

I would like to define a new command which should determine (within a tikz plot) whether its argument is in math mode or not. If so, it should wrap the argument with . I found \ifmode to do this, but it's not working. Here is my minimal example:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[american,ngerman]{babel}
\usepackage{tikz}

\newcommand*{\yellowemph}[1]{%
\tikz[baseline=(text.base)]\node(text)[rectangle, fill=yellow, rounded
corners, inner sep=0.3mm]{\ifmmode $#1$\else #1\fi};%
}

\begin{document}
\yellowemph{word}% works
\yellowemph{$\frac{1}{2}$}% works
$\yellowemph{\frac{1}{2}}$% does not work
\end{document}


I am aware of \ensuremath, however, this always switches to math mode. I would like to keep text as is if not in math mode (see \yellowemph{word} for example).

SOLUTION

As posted below, this is a solution:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[american,ngerman]{babel}
\usepackage{tikz}

\newif\ifstartedinmathmode
\newcommand*{\yellowemph}[1]{%
\relax\ifmmode\startedinmathmodetrue\else\startedinmathmodefalse\fi
\tikz[baseline=(text.base)]\node(text)[rectangle, fill=yellow, rounded
corners, inner sep=0.3mm]
{\ifstartedinmathmode$#1$\else#1\fi};%
}

\begin{document}
\yellowemph{word}
$\int_0^\infty f(\yellowemph{x})\,dx$
\yellowemph{$\displaystyle\frac{1}{2}$}
\end{document}

-
You could use \ensuremath{} –  matth Mar 2 '12 at 11:15
Do you know about the \ensuremath command ? –  Hans-Peter E. Kristiansen Mar 2 '12 at 11:16
There's always \ensuremath :D –  qubyte Mar 2 '12 at 11:28
But \ensuremath always uses math mode right? that's not what I want for text such as in the first line, for example. –  Marius Hofert Mar 2 '12 at 11:42
Incidentally, there's not just one mathmode. See tex.stackexchange.com/q/1223/86 for where I wanted a similar functionality. –  Loop Space Mar 2 '12 at 12:13

\newcommand*{\textyellowemph}[1]{\tikz[baseline=(text.base)]\node(text)[rectangle, fill=yellow, rounded, inner sep=0.3mm]{#1};}
`