I recently posted this answer to How to highlight all words of the form [0-9][A-Za-z0-9]* immediately following an equal sign?. It works, but it suffers from (a lot) of code duplication.
What I have at the moment
More specifically, I have to use a line of the form
\lst@DefSaveDef{`<char>}\jubobs@<char>{\jubobs@<char>\foo}
no fewer than 52 times, for <char>
in A
-Z
and a
-z
. For information, \lst@DefSaveDef
is a listings
internal macro with the following syntax:
\lst@DefSaveDef{<charcode>}<some-macro>{<replacement-text>}
Using my newfound understanding of \expandafter
, I've managed to somewhat reduce the code by defining a macro that takes a letter as argument and performs the same thing as the line show above:
\makeatletter
\newcommand\addtoletterdef[1]
{%
\expandafter\expandafter\expandafter\lst@DefSaveDef%
\expandafter\expandafter\expandafter{%
\expandafter\expandafter\expandafter`%
\expandafter\expandafter\expandafter#1%
\expandafter\expandafter\expandafter}%
\expandafter\csname jubobs@#1\expandafter\endcsname%
\expandafter{\csname jubobs@#1\endcsname\foo}%
}
\makeatother
However, that didn't help much in reducing code duplication: I still have to invoke \addtoletterdef
52 times... ;...(
What I want
I would like to define a macro similar to my \addtoletterdef
but that would accept a charcode instead of a character. That way, it would be easy to loop through charcodes 65 to 90 (A-Z) and 97 to 122 (a-z) and perform all those 52 operations without any code duplication.
I've got a feeling that the answer lies in using the \begingroup\lccode
trick, but that trick is very new to me, and I'm far from mastering it.
How can I redefine \addtoletterdef
to accept a charcode instead of a character?
MWE:
\documentclass{article}
\usepackage{listings}
% dummy macro
\def\foo{foo}
\makeatletter
\newcommand\addtoletterdef[1]
{%
\expandafter\expandafter\expandafter\lst@DefSaveDef%
\expandafter\expandafter\expandafter{%
\expandafter\expandafter\expandafter`%
\expandafter\expandafter\expandafter#1%
\expandafter\expandafter\expandafter}%
\expandafter\csname jubobs@#1\expandafter\endcsname%
\expandafter{\csname jubobs@#1\endcsname\foo}%
}
\makeatother
\lstdefinestyle{mycode}
{
language=C,
SelectCharTable=
\addtoletterdef{A}
% ...
\addtoletterdef{Z}
\addtoletterdef{a}
% ...
\addtoletterdef{z}
}
\begin{document}
\begin{lstlisting}[style=mycode]
a1 = 6.12234Z
a2 = Z1324124
\end{lstlisting}
\end{document}
listings
. It is really good. I see many packages (like matlab prettifier) as the out come. Keep it up and all the best :)listings
package, and further, compiler construction.