在我的\lstset{...}
代码中morecomment=[l][{\color[rgb]{0.1, 0.2, 0.8}}]{\#},
,我看到有人用它来给预处理器命令添加颜色。这种方法很好用,但我想让多行宏也能突出显示,例如:
\begin{lstlisting}
#define MAX(a, b) \
((a)>(b)?(a):(b))
\end{lstlisting}
listings
匹配多行宏的好方法是什么?
[编辑]
很好,这里有一个完整的例子\documentclass
等等……:P
\documentclass{article}
\usepackage{color}
\usepackage{listings}
\lstset{language=C,
morecomment=[l][{\color[rgb]{0.1, 0.2, 0.8}}]{\#}
}
\begin{document}
\begin{lstlisting}
#define MAX(a, b) \
((a)>(b)?(a):(b))
\end{lstlisting}
\end{document}
\
根据与 相关的规则,我希望宏的第二行也呈蓝色。
答案1
该listings
软件包不直接提供突出显示多行编译器指令的方法。如果您认为这是一个理想的功能,您可能需要与维护者联系。
与此同时,这里有一个可能的实现。它使用两个具有自解释名称的开关来跟踪上下文和补丁,listings
以便在打印任何内容之前检查我们是否仍在编译器指令中;如果是,则应用指令样式。
\documentclass{article}
\usepackage{etoolbox}
\usepackage{xcolor}
\usepackage{listings}
\lstloadaspects{directives}
% ---------- Beginning of ugly internals ----------
\makeatletter
% switches to keep track of context
\newif\if@LastCharWasBackslash
\newif\if@DirectiveContinued
% --- hooking into listings ---
\lst@AddToHook{OutputOther}%
{%
\ifx\lst@lastother\lstum@backslash% % if the last character in
% \the\lst@token is a backslash...
\global\@LastCharWasBackslashtrue%
\else
\global\@LastCharWasBackslashfalse%
\fi
\@condApplyDirectiveStyle % Apply directive style if needed
}
\lst@AddToHook{Output}%
{%
\global\@LastCharWasBackslashfalse% % Reset switch
\@condApplyDirectiveStyle% % Apply directive style if needed
}
% `listings' automatically exits CDmode at the EOL hook;
% we patch \lsthk@EOL so that it checks whether a compiler directive
% is continued on the next line and set the relevant switch accordingly.
\patchcmd{\lsthk@EOL}
{\ifnum\lst@mode=\lst@CDmode \lst@LeaveMode \fi}
{%
\global\@DirectiveContinuedfalse%
\ifnum\lst@mode=\lst@CDmode%
\lst@LeaveMode
\else
\if@LastCharWasBackslash%
\global\@DirectiveContinuedtrue%
\fi
\fi
}
{}{\@latex@error{\string\lsthk@EOL\space patch failed!}{}}
% --- two helper macros ---
\newcommand\@condApplyDirectiveStyle
{%
\ifnum\lst@mode=\lst@CDmode%
\@applyDirectiveStyle%
\fi
\if@DirectiveContinued%
\@applyDirectiveStyle%
\fi
}
\newcommand\@applyDirectiveStyle{\let\lst@thestyle\lst@directivestyle}
\makeatother
% ---------- End of ugly internals ----------
\lstset
{
language = C,
directivestyle = \color{blue},
}
\begin{document}
\begin{lstlisting}
#define MAX(a, b) \
((a)>(b)?(a):(b))
#define \
bar \
baz
foo \ bar
baz
\end{lstlisting}
\end{document}
答案2
这不是一个答案,而是一个解决方法......
\documentclass{article}
\usepackage{color}
\usepackage{listings}
\lstset{language=C,
morecomment=[l][{\color[rgb]{0.1, 0.2, 0.8}}]{\#},
moredelim=[il][{\color[rgb]{0.1, 0.2, 0.8}}]{@},
}
\begin{document}
\begin{lstlisting}
#define MAX(a, b) \
@ ((a)>(b)?(a):(b))
\end{lstlisting}
\end{document}
不确定这是否是给任意线条着色的正确方法,但moredelim
带有选项i
会隐藏@
宏中的字符并像一样为其余线条着色morecomment
。