
最近的這個問題(在一種語言中列印藍色括號,在另一種語言中列印黑色)讓我又提出了(最多)兩個有關該listings
軟體包的問題:
- 有沒有類似的選項
opstyle
只影響一參數(使用"
,,
或;
作為第一個分隔符號和=
第二個分隔符號)和一屬於該參數的值? (用作=
第一個分隔符號和"
,,
或;
用作第二個)? - 是否可以在環境中間調整使用的顏色
listings
,而不顯示為註解或線條等?這些解決方案都定義了實際環境之外的顏色。
既沒有listings
手動的,也不維基圖書文章給出結論性的答案(並且也未能提及宏,包括\lst@thestyle
我可能添加的宏),所以我查看了listings.sty
,毫不奇怪地無濟於事,部分原因是.sty
-file 在任何行上絕對沒有註釋用於解釋。
opstyle
為了您的方便,我已經包含了前面提到的範例的 MWE和圖片。就我而言,我想將string: ()
橙色部分著色,但{}><;&
將部分著色為紅色。
\documentclass{article}
\usepackage{xcolor}
\usepackage{listings}
\newcommand\opstyle{\color{red}} % <--- customise operator style here
\makeatletter
\lstset
{%
language=C++,
alsoletter=0123456789,% to prevent \opstyle from being applied to digits
}
% Hook into listings
\lst@AddToHook{OutputOther}{\ProcessOther@silmeth}
% helper macro
\newcommand\ProcessOther@silmeth
{%
\ifnum\lst@mode=\lst@Pmode% % If we're in `Processing' mode...
\def\lst@thestyle{\opstyle}% % ... redefine the style locally
\fi%
}
\makeatother
\begin{document}
\begin{lstlisting}[]
int i = 0;
if(i > 1) && (1/2 < 2) {
// one-line comment ()={}><;&
printf("string: ()={}><;&");
/*
block comment ()={}><&;
*/
}
\end{lstlisting}
\end{document}