Jason (jcreed) wrote,
Jason
jcreed

Some of you might possibly be interested in this disgusting but effective TeX trick that I figured out: You can say \colorify{character}{color name} to make every instance of character a certain color in math mode. Color names work as usual for the color package. I like to do this to metavariables for different syntactic classes so that they stand out nicely.

It's moderately gross just to accomplish it for one particular choice of character, but the spectacularly gross bits are involved in packaging it up in a nice little function that takes a character as an argument and computes its math character code and sets up the right macros. I used pretty much every dirty TeX trick I know of: token lists, a counter, \expandafter, \afterassignment, \edef, and the truly wretched \lccode/\lowercase hack to get an arbitrary "active" character.

Ah, TeX. It really succeeds in combining the simple-to-understand control flow of aspect-oriented programming with the high-level expressivity of assembly language.

It has the unfortunate side-effect that you can no longer use that character in control sequences in math mode, since it relies on making it a so-called "active-character" in math mode. I think if you wanted all your Gs colored (for instance) and still wanted \Gamma you could maybe \let it to another named before you \colorifyed G? No apparently that works fine! Much to my surprise. I misjudged how active characters work. Maybe this is magic related to \mathcode "8000 that doesn't work for \catcode 13.


\documentclass{article}
\usepackage{color}


\def\makemathactive#1{\mathcode`#1="8000}

\def\rappend#1#2{{\edef\res{{\the#1\the#2}}\global#1=\res}}
\def\rprepend#1#2{{\edef\res{{\the#1\the#2}}\global#2=\res}}
\def\rbracify#1{{\edef\res{{{\the#1}}}\global#1=\res}}

\def\appaz{\rappend\atoks\ztoks}
\def\prepza{\rprepend\ztoks\atoks}

\def\bracify{\rbracify\atoks}
\def\append{\afterassignment\appaz \ztoks=}
\def\prepend{\afterassignment\prepza \ztoks=}
\newtoks\atoks
\newtoks\ztoks
\newcount\mycount

% char, mathcode, color
\def\buildatoks#1#2#3{
\atoks={\color{#3}\mathchar}
\append{#2}
\bracify
\append{\egroup}
\prepend{\bgroup}
\bracify
\prepend{\def#1}
}

% mathcode, char, color
\def\doit#1#2#3{{\lccode`~=`#2 \lowercase{\buildatoks{~}}{#1}{#3}}%
\the\atoks \makemathactive{#2}}

% char, color
\def\colorify#1#2 {\mycount=`#1 \advance\mycount by "7100
\expandafter\doit\expandafter{\the\mycount}{#1}{#2}}


\colorify{A}{red}

\begin{document}

A$ABC$

\end{document}


This yields a black A, then a red A, then a black B and C, the latter three characters in italics.
Tags: tex
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 3 comments