我正在使用listings
insidebeamer
来排版一些 Octave 代码。因为我想在浏览幻灯片时将覆盖规范应用于列表的某些部分(出于突出显示的目的),所以我应用了如何使覆盖在 lstlisting 环境中仍然有效?
但是,我注意到覆盖不适用于正常代码行末尾的单行注释。如果我将分隔符放在下一行,它可以工作,但它会产生不需要的额外空格,并且使用emptylines=1
并不能消除后者。
有没有办法也可以突出显示与普通代码在同一行的注释?
以下是 MWE:
\documentclass[dvipsnames,cmyk]{beamer}
\usepackage{arev}
\usepackage{listings}
% remove navigation symbols
\setbeamertemplate{navigation symbols}{}
\lstdefinestyle{highlight}{
keywordstyle=\color{red},
commentstyle=\color{green},
}
\lstdefinestyle{base}{
language=Octave,
emptylines=1,
breaklines=true,
basicstyle=\tiny\ttfamily\color{black!40},
keywordstyle=\color{red!40},
commentstyle=\color{green!40},
moredelim=**[is][\only<+>{\color{black}\lstset{style=highlight}}]{@}{@},
}
\begin{document}
\begin{frame}[fragile]%{Listings overlay}
\begin{lstlisting}[style=base, gobble=0]
@% This comment will be highlighted; it is also bigger than the frame size so it is expected that line is breaked into at least two. Note that unwanted empty line may be generated
@
@a = 2@ % aaa
@b = 1 % aaa @
@c = 1 % aaa @
@c = 1 % aaa
@
\end{lstlisting}
\end{frame}
\end{document}
如您所见,代码中的注释 (a=... % comment) 未突出显示。我该怎么做,而不生成额外的行(下一行中的 @)?
答案1
迟到总比不到好:)
正如 Qrrbrbirlbel 所说他的评论,问题在于,因为%
是语言中的(单行)注释分隔符Octave
,listings
所以将您的结束覆盖分隔符@
视为注释的一部分。
一种解决方法是取消将其定义%
为注释分隔符,但literate
在遇到该字符时使用以应用注释样式。您还需要在每行开头重置样式。
这种方法有两个注意事项:
- 字符串文字中出现的任何
%
字符都会扰乱突出显示, - 即使在评论中关键词也会被突出显示。
\documentclass[dvipsnames,cmyk]{beamer}
\usepackage{arev}
\usepackage{listings}
% remove navigation symbols
\setbeamertemplate{navigation symbols}{}
\lstdefinestyle{highlight}{
keywordstyle=\color{red},
commentstyle=\color{green},
}
\makeatletter
\lstdefinestyle{base}{
language = Octave,
emptylines = 1,
breaklines = true,
basicstyle = \tiny\ttfamily\color{black!40},
keywordstyle = \color{red!40},
commentstyle =\color{green!40},
moredelim = **[is][\only<+>{\color{black}\lstset{style=highlight}}]{@}{@},
%
% Undefine % as a comment delimiter, but still apply comment style when it's encountered.
deletecomment =[l]\%,
literate ={\%}{{\lst@commentstyle\%}}1,
}
% Reset the style at the beginning of every ``true'' line
\lst@AddToHook{EveryPar}{\lst@basicstyle}
\makeatother
\begin{document}
\begin{frame}[fragile]%{Listings overlay}
\begin{lstlisting}[style=base, gobble=0]
@% This comment will be highlighted; it is also bigger than the frame size so it is expected that line is breaked into at least two. Note that unwanted empty line may be generated
@
@a = 2@ % aaa
@b = 1 % aaa @
@c = 1 % aaa @
@d = 1 % aaa @
\end{lstlisting}
\end{frame}
\end{document}