I am trying to make characters active in math mode, but can't seem to get past the most basic of examples. I would like to define a macro which is passed:
the character to make active and
the macro that should be executed once that macro is encountered.
The MNWE below attempts to make =, + and ! active and color code them. The desired output is that those characters get colored in math mode as. Thus, the input
a=+b $c=+4+d+3!$ e=+f
yields:
where the characters are not altered outside of math mode (the leading a=+b and trailing e=+f).
Notes:
- There is a separate, but related (as it is in the context of active characters) question in the
\MyPlusmacro to detect a binary addition+versus a unary positive+. Perhaps that should be a separate question?
Related Questions:
- Macro to take a character as argument, make it active, then \def it.
- How do you define macros to toggle a character active and define a macro for it?
- "Activate" active characters in argument passed as macro
Code (non-working):
\documentclass{article}
\usepackage{mathtools}
\usepackage{xparse}
\usepackage{xcolor}
\NewDocumentCommand{\MakeActiveChar}{%
m% char to make active
m% code to execute for this character
}{%
\catcode`\#1=13\relax%
\def#1{#2}%
}%
\let\OldEqual=
\newcommand*{\MyEqual}[1][green]{\mathrel{\textcolor{#1}{\OldEqual}}}%
\let\OldPlus+
\newcommand*{\MyPlus}[1][blue]{%
%\catcode`\+=12% reset catcode so we can use it (not needed with \OldPlus?)
%% Perhaps this if-then construct should be a separate question?
%% if binary addition operator
\mathbin{\textcolor{#1}{\OldPlus}}%
%% if unary positive operator
%% \mathrel{\textcolor{red}{\OldPlus}}%
}%
\let\OldFactorial!
\newcommand*{\MyFactorial}{\textcolor{brown}{\OldFactorial}}%
\everymath{%
\MakeActiveChar{=}{\MyEqual}%
\MakeActiveChar{+}{\MyPlus}%
\MakeActiveChar{!}{\MyFactorial}%
}%
\begin{document}
The ``math'' outside here is just to test that characters are active \emph{only} in math mode:
a=+b $c=+4+d+3!$ e=+f
\end{document}

