# Wrap many math macros into \ensuremath

I find it more natural refering to \Phi, \alpha, \sim, etc. outside math mode the same as inside math mode. I.e. writing:

Consider \Phi, \alpha{} and \sim{} in the following equation:
$$\Phi \sim \alpha$$


Consider $\Phi$, $\alpha$ and $\sim$ in the following equation:
$$\Phi \sim \alpha$$


My naive approach is to override all the macros I need with their own variant, following this post, with:

\let\NPhi\Phi % native phi
\def\Phi{\ensuremath{\NPhi}}
\let\Nalpha\alpha % native alpha
\def\alpha{\ensuremath{\Nalpha}}
\let\Nsim\sim
\def\sim{\ensuremath{\Nsim}}
..


But it is quite tedious. How could I loop over that? So that:

\magiccommand{
Phi,
alpha,
sim,
..}


would produce the same result?

• As usual, any time you will shave off with this macro will be spent when you are trying to debug the weird errors you will get because of this. – percusse Apr 19 '18 at 16:51
• @percusse Haha, of course ;) – iago-lito Apr 19 '18 at 16:54
• Related Question: When not to use \ensuremath for math macro?. – Peter Grill Apr 19 '18 at 16:56
• What is better? \alpha{} (having to remember to add {}) or just $\alpha$? I have no doubt it's the latter. – egreg Apr 19 '18 at 17:19
• @PeterGrill related indeed :) Thanks for that. I don't think it's a problem for such macros with no arguments, though, since there will be no semantic to break. – iago-lito Apr 20 '18 at 7:31

All you need is a parser for comma separated values. The following example uses \comma@parse of package kvsetkeys. The macro automatically strips spaces at the begin and end of the values.

\documentclass{article}
\usepackage{kvsetkeys}
\makeatletter
\newcommand*{\EnsureMathDef}[1]{%
% Throw error, if "\N#1" is already defined.
\expandafter\@ifdefinable\csname N#1\endcsname{%
% Save old meaning
\expandafter
\let\csname N#1\expandafter\endcsname
\csname #1\endcsname
% Define new macro
\expandafter\edef\csname #1\endcsname{%
\noexpand\ensuremath{%
\expandafter\noexpand\csname N#1\endcsname
}%
}%
}%
}
\comma@parse{
Phi,
alpha,
sim,
}\EnsureMathDef
\makeatother

\begin{document}
Consider \Phi, \alpha{} and \sim{} in the following equation:
$$\Phi \sim \alpha$$
\end{document}


The macro kernel provides \@for. Line ends must be commented to avoid additional spaces.

\documentclass{article}
\makeatletter
\@for\x:=%
Phi,%
alpha,%
sim%
\do{%
% Throw error if macro with prefix N is already defined.
\expandafter\@ifdefinable\csname N\x\endcsname{%
% Save old meaning
\expandafter
\let\csname N\x\expandafter\endcsname
\csname\x\endcsname
% Define new macro
\expandafter\edef\csname\x\endcsname{%
\noexpand\ensuremath{%
\expandafter\noexpand\csname N\x\endcsname
}%
}%
}%
}
\makeatother

\begin{document}
Consider \Phi, \alpha{} and \sim{} in the following equation:
$$\Phi \sim \alpha$$
\end{document}

• This does work! I like the version with \@for with no additional package, since I don't mind much about trailing %. Thanks a lot :) – iago-lito Apr 20 '18 at 7:39