Colorize material in math-mode subscript and superscripts
You are looking for 'math active' codes:
\documentclass{article}
\usepackage{color}
\newcommand{\amat}{\mathbf{A}}
\newcommand{\bmat}{\mathbf{B}}
\newcommand{\cmat}{\mathbf{C}}
\begingroup
\catcode`_=\active
\catcode`^=\active
\gdef_#1{\sb{\begingroup\color{magenta}#1\endgroup}}
\gdef^#1{\sp{\begingroup\color{cyan}#1\endgroup}}
\endgroup
\mathcode`\^="8000 %
\mathcode`\_="8000 %
\catcode`\^=12 %
\catcode`\_=12 %
\begin{document}
Some ^_ text.
\(
\cmat_{i}^{k} = \amat^{i}_{j} \bmat^{j}_{k}
\)
\end{document}
This works as in math mode any character with mathcode "8000 is treated as an active char. The global definition of the behaviour of _
and ^
when active therefore applies even though in text mode they do nothing special.
Here's a LuaLaTeX-based solution. The main input syntax requirements are that (a) the sub- and superscript terms are always encased in curly braces and (b) the arguments of _
and ^
immediately follow these characters, i.e., intervening whitespace is not allowed. It is also assumed that if _
and ^
occur outside of math mode, say, in a URL string, these characters are not immediately followed by a left curly brace.
The solution doesn't modify the catcodes of _
and ^
. Instead, it consists of a Lua function that uses Lua's powerful string.gsub
function to perform the actual colorizing work and two LaTeX macros, named \sbspcolorsOn
and \sbspcolorsOff
, that activate and deactivate the operation of this Lua function.
\documentclass{article}
\usepackage{luacode,xcolor}
%% The Lua function 'sbspcolors' does most of the work:
\begin{luacode}
function sbspcolors ( s )
s = string.gsub ( s , "%_(%b{})" , "_{\\textcolor{magenta}%1}" )
s = string.gsub ( s , "%^(%b{})" , "^{\\textcolor{cyan}%1}" )
return ( s )
end
\end{luacode}
%% Two helper macros to activate and deactivate the Lua function:
\newcommand{\sbspcolorsOn}{\directlua{luatexbase.add_to_callback(
"process_input_buffer" , sbspcolors , "sbspcolors" )}}
\newcommand{\sbspcolorsOff}{\directlua{luatexbase.remove_from_callback(
"process_input_buffer" , "sbspcolors" )}}
%% A few math-mode macros
\newcommand{\amat}{\mathbf{A}}
\newcommand{\bmat}{\mathbf{B}}
\newcommand{\cmat}{\mathbf{C}}
\begin{document}
$\cmat_{i_{u}}^{k^{\ell}} = \sum_{j=1}^{k} \amat^{i}_{j^{M}} \bmat^{j_{N}}_{k}$ \quad
\sbspcolorsOn % activate the Lua function
$\cmat_{i_{u}}^{k^{\ell}} = \sum_{j=1}^{k} \amat^{i}_{j^{M}} \bmat^{j_{N}}_{k}$ \quad
\sbspcolorsOff % deactivate the Lua function
$\cmat_{i_{u}}^{k^{\ell}} = \sum_{j=1}^{k} \amat^{i}_{j^{M}} \bmat^{j_{N}}_{k}$
\end{document}