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}
\ensuremath{}– matth Mar 02 '12 at 11:15\ensuremathcommand ? – hpekristiansen Mar 02 '12 at 11:16\ensuremath:D – qubyte Mar 02 '12 at 11:28\ensuremathalways uses math mode right? that's not what I want for text such as in the first line, for example. – Marius Hofert Mar 02 '12 at 11:42mathchoiceyesterday, which is kind of related. – qubyte Mar 02 '12 at 12:33