如何对列表内的括号进行颜色匹配?

如何对列表内的括号进行颜色匹配?

我想要实现的是彩虹色的括号(就像Emacs 中的彩虹分隔符) 基于其深度,采用一种针对编程语言 (Racket) 的新定义样式。例如:

(define (square x) (* x x))

其中最外面的两个括号可能是红色,而里面的 4 个括号可能是绿色(如果有更深的括号对,它们可能是黄色、青色、粉红色等)。

尝试写类似的东西

\textcolor{red}{(} blabla \textcolor{red}{)}

一方面很麻烦,另一方面在启用的情况下无法lstlisting使用mathescape=true

答案1

我开始尝试以下宏

\newcount\bralevel

\def\colorizebrackets{\bgroup \catcode`\ =13 \colbraA}
\def\colbraA#1{\egroup \bralevel=0 \edef\colorizedtext{\colbraB #1{}}}
\def\colbraB#1{\ifx\relax#1\relax \else
   \ifx(#1\colbraC{#1}\else
   \ifx)#1\colbraD{#1}\else 
   #1\fi\fi \expandafter\colbraB\fi}
\def\colbraC{\immediateassignment\advance\bralevel by1 \colbraE}
\def\colbraD#1{\colbraE{#1}\immediateassignment\advance\bralevel by-1 }
\def\colbraE{\csname colbra:\the\bralevel\endcsname}
\def\declcolbra#1#2{\protected\expandafter\def\csname colbra:#1\endcsname##1{#2}}
\bgroup \lccode`~=` \lowercase{\egroup \def~{ }}

\declcolbra 1{\textcolor{red}{#1}}
\declcolbra 2{\textcolor{green}{#1}}
\declcolbra 3{\textcolor{yellow}{#1}}
\declcolbra 4{\textcolor{cyan}{#1}}
\declcolbra 5{\textcolor{pink}{#1}}

% test:

\colorizebrackets{(define (square x) (* x x))}
\colorizedtext

\show\colorizedtext

\immediateassignment我在 LuaTeX 中尝试过这个:它知道使以下内容可扩展的原语\advance。因此,宏的核心\colbraB是完全可扩展的。它可以在我们需要使用可扩展宏的另一个上下文中使用。我使用它\edef\colorizedtext{\colbraB#1{}}。如果您不使用 LuaTeX,那么您可以将标记部分添加到\colorizedtext宏中,并且宏将不可扩展。

相关内容