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.
One solution is to modify \DefineNamedFunction to strip out the $$ if it is included in the macro call using the xstring pacakge, but this to me feels like a hack, and am thinking that there is probably a cleaner TeX way to do this.
So to summarize: How do I change \DefineNamedFunction such that I can use both the commented and uncommented calls to this macro, and still be able to use the definition inside and outside of math mode?
\documentclass{article}
\usepackage{amsmath}
\usepackage{xcolor}
\newcommand{\DefineNamedFunction}[2]{% {FunctionName}{FunctionExpression}
\expandafter\providecommand\expandafter{\csname#1\endcsname}{\textcolor{red}{\ensuremath{#2}}}%
}
\begin{document}
\DefineNamedFunction{FunctionF}{y = 2 \sin x}
%\DefineNamedFunction{FunctionF}{$y = 2 \sin x$}
I can use FunctionF inside math mode as $\FunctionF$,
but can also use this outside of math mode as \FunctionF.
\end{document}

\newcommand, but I need\providecommandin my real usage. – Peter Grill Jun 06 '11 at 18:22\DefinedNamedFunction{FunctionFF}{$y=x$}(with the dollar signs) as it is more natural to do so. I didn't want to have to remember that when I use this macro I do not put the$$, but for all the other macros where I have math, I do put the$$. – Peter Grill Jun 06 '11 at 20:16DNFnormlooks simpler. – Peter Grill Jun 06 '11 at 20:45#2starts with$; in this case it is substituted by\DNFnormithat throws away the two$, otherwise it does nothing. – egreg Jun 06 '11 at 20:51