listings 包:突出显示由字母和数字部分组成的单词

listings 包:突出显示由字母和数字部分组成的单词

我想用不同的颜色突出显示字母和数字部分的几个关键字。

我的问题是关键字的数量可能会变得非常大,例如从 r0 到 r191。而且我有好几个关键字。有没有办法跳过写出所有可能的关键字?

有没有办法只为单词定义左分隔符而不是为行定义左分隔符?

下面的示例完全符合我的要求,但写了所有的关键字(例如关键字[2]和关键字[3])...

\documentclass[a4paper, 12pt,english]{article}
\usepackage{color}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkgreen}{rgb}{0.0,0.4,0.0}
\definecolor{darkred}{rgb}{0.6,0.0,0.0}

\usepackage{listings}
\lstdefinelanguage{mylanguage}
                  {keywords=[1]{add,sub,test},
                    keywords=[2]{r0,r1,r2},
                    keywords=[3]{p00,p01,p10,p11},
                    moredelim=[s][\footnotesize\textit]{<}{>},
                    keywordstyle=[1]\normalsize\color{gray}\bfseries\ttfamily,
                    keywordstyle=[2]\color{darkgreen},
                    keywordstyle=[3]\color{darkred}}

\begin{document}

\lstset{numbers=left, numberstyle=\tiny, stepnumber=1, numbersep=5pt,language=mylanguage}
\begin{lstlisting}
  p00 add r0 , r1 , r2
\end{lstlisting}


\end{document}

答案1

巨大的首先,感谢 David 提供解决方案一个棘手的中级问题。没有他的帮助我不可能做到这一点。

你可以很容易地通过用 LaTeX 本身生成列表来做到这一点(毕竟它是图灵完备的,呵呵)。请注意,这需要包forloop(实际上是一个非常简单的宏)。

\documentclass[a4paper, 12pt,english]{article}
\usepackage{color,forloop}
\definecolor{gray}{rgb}{0.4,0.4,0.4}
\definecolor{darkgreen}{rgb}{0.0,0.4,0.0}
\definecolor{darkred}{rgb}{0.6,0.0,0.0}

\newcounter{ct}
\makeatletter
% Since we don't want an initial comma in the list, we use \@gobble
\def\rlist{\@gobble}
%  Using the counter ct, range its value from 0 to 191
\forloop{ct}{0}{\value{ct} < 192}{%
    % \edef expands the definition before it actually 
    % binds the two.  Thus, \rlist expands like a chameleon's tongue.
    \edef\rlist{\rlist,r\arabic{ct}}
  }

\makeatother
\def\listwithrs#1\relax{%
\lstdefinelanguage{mylanguage}
                  {keywords=[1]{add,sub,test},
                   keywords=[2]{#1},  % we stick in the list here
                   keywords=[3]{p00,p01,p10,p11},
                   moredelim=[s][\footnotesize\textit]{<}{>},
                   keywordstyle=[1]\normalsize\color{gray}\bfseries\ttfamily,
                   keywordstyle=[2]\color{red},
                   keywordstyle=[3]\color{darkred}}}

\usepackage{listings}

% Since we want to know the value of \rlist before we define the language,
% we use \expandafter to 'skip' \listwithrs so \rlist can be evaluated.
\expandafter\listwithrs\rlist\relax

\begin{document}

\lstset{numbers=left, numberstyle=\tiny, stepnumber=1, numbersep=5pt,language=mylanguage}
\begin{lstlisting}
  p00 add r0 , r1 , r2 , r3 , r4
\end{lstlisting}

\end{document}

相关内容