# Proper way to use \ensuremath to define a macro useable in and out of math mode

Based on this solution related to defining a macro I came up with this macro to help me define a macro that I can use either in or outside of math mode.

The example as is functions as I want. However, this solution requires me to NOT put $$ around the second parameter to to the \DefineNamedFunction macro. I would like to be able to include the$$, or not include it.

show 1 more comment
\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}
\makeatletter
\def\DefineNamedFunction#1#2{\expandafter\DefineNamedFunction@i#1\@nil#2\@nil}
\def\DefineNamedFunction@i#1\@nil{%
\@ifnextchar${\DefineNamedFunction@ii{#1}}{\DefineNamedFunction@iii{#1}}} \def\DefineNamedFunction@ii#1$#2$\@nil{% \@namedef{#1}{\ifmmode\textcolor{red}{#2}\else\textcolor{red}{$#2$}\fi}} \def\DefineNamedFunction@iii#1#2\@nil{% \@namedef{#1}{\ifmmode\textcolor{red}{#2}\else\textcolor{red}{$#2$}\fi}} \makeatother \DefineNamedFunction{FunctionF}{y = 2 \sin x} \DefineNamedFunction{FunctionFF}{$y = 2 \sin x$} \begin{document} I can use \FunctionF\ inside math mode as$\FunctionF$, but can also use this outside of math mode as$\FunctionFF$and \FunctionFF. \end{document}  -  This works great. Thanks. So, is this basically doing the job of \ensuremath manually? – Peter Grill Jun 6 '11 at 18:27 more or less ... the problem is \textcolor when it is used in math mode with a math argument – Herbert Jun 6 '11 at 18:30 @Herbert: apart from making the + an ordinary atom, $\textcolor{blue}{a}\textcolor{red}{+}\textcolor{green}{b}$ works perfectly. – egreg Jun 6 '11 at 20:08 @egreg: I was talking about $\textcolor{blue}{$a$}\$ ... – Herbert Jun 7 '11 at 4:25 @Herbert: I see; \textcolor is smart enough to know when it's called in math mode: maybe a pair \textcolor and \mathcolor would have been better. – egreg Jun 7 '11 at 8:16
show 3 more comments