I want to create an environment that will search through all of the math in it, to make some changes. So, I want something like a way to apply \regex_extract_all
to search through everything which is in math mode in my environment.
I'm leaning towards using latex3, however I'm also considering luatex if that would be considerably easier. In that case, something like Automatically colourize all occurrences of certain strings (different colouring for different sets of words) is similar to what I want, however I want to apply it only within math mode, rather than to the whole document.
I've looked into applying commands to math mode, and it's been looking like I could perhaps use a combination of \regex_extract_all
and \everymath
however I'm worried about how it would work with other math environments like align
equation
or even just display mode. These questions:
\everymath, AMS equations, beamer, and tikz not working together
How to color certain commands/environments?
seem to indicate that it's non-trivial to operate on all math-mode text, and they both seem to use workarounds that might not work universally? I'm not sure. Would using \everymath, \everydisplay work for this case?
As a minimal example, if I were trying to make every occurrence of i as a variable red I'd want this code
\DeclarePairedDelimiter\norm{\lVert}{\rVert}
\begin{document}
$i+2=3$
\begin{myEnv}
This is a test about i
$\sin(\theta)+\sum_{i=0}^\infty ix^i$
\begin{equation*}
\norm{i} = \begin{cases}
i & \text{if } i \geq 0 \\
-i & \text{if } i < 0
\end{cases}
\end{equation*}
$$(x_i) = 1/i$$
\end{myEnv}
\end{document}
to generate a document where the "i"s in "i+2=3" on top and in "This is a test about i" are untouched, the "i"s in the words "if" are untouched, and the commands \sin
and \infty
still work, but the other "i"s used as a variable are made red.
l3regex
to search your string and replace it by a (protected) command\myi
that tests using\ifmmode
(or\mode_if_math:TF
) whether it is in math mode and acts accordingly. Note thatl3regex
is quite slow.i
also appears in\begin{equation}
and\end{equation}
. So my idea above is not good; perhaps it can be salvaged by\def\myi{\ifincsname i\else\ifmmath{\color{red}i}\else i\fi\fi}
.