我在 lstlisting 环境中有一堆代码。如何在环境中仅突出显示(彩色背景)一段特定的代码?
问问题
27035 次
5 回答
44
您可以在列表中使用 \colorbox 和转义字符:
添加到您的序言中
\usepackage{color}
\definecolor{light-gray}{gray}{0.80}
然后在您的文档中像这样使用它:
\begin{lstlisting}[escapechar=!]
def mult(m: Matrix[Int], n: Matrix[Int]) {
val p = !\colorbox{light-gray}{new MatrixInt}!(m.rows, n.cols)
}
\end{lstlisting}
于 2010-02-24T14:44:50.997 回答
11
这有点麻烦,但是您可以将代码分成几个lstlisting
环境。
\begin{lstlisting}
line
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}[backgroundcolor=\color{pink}]
very
interesting
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}
line
line
\end{lstlisting}
于 2009-08-21T19:03:06.747 回答
2
这是使用以下方法突出显示(部分)单行的解决方案tikz
:
\documentclass[pdftex,11pt,a4paper]{article}
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
% Command to place a TikZ anchor at the current position
\newcommand{\mytikzmark}[1]{%
\tikz[overlay,remember picture,baseline] \coordinate (#1) at (0,0) {};}
\newcommand{\highlight}[2]{%
\draw[yellow,line width=14pt,opacity=0.3]%
([yshift=4pt]#1) -- ([yshift=4pt]#2);%
}
\begin{document}
\begin{lstlisting}[escapechar=@, language=C]
@\mytikzmark{hl1Start}@struct@\mytikzmark{hl1End}@ S {
double @\mytikzmark{hl2Start}@salary_@\mytikzmark{hl2End}@;
};
\end{lstlisting}
\begin{tikzpicture}[remember picture, overlay]
\highlight{hl1Start}{hl1End}
\highlight{hl2Start}{hl2End}
\end{tikzpicture}
\end{document}
你得到
所以lstlisting
保留了 's 的语法高亮。
于 2021-04-14T08:33:23.667 回答
1
有一个包可以lstlinebgrd
做到这一点
% !TEX encoding = UTF-8 Unicode
% !TEX TS-program = xelatex
\documentclass{article}
\usepackage[a4paper]{geometry}
\usepackage{lstlinebgrd}
\usepackage{listings, xcolor}
\lstset{tabsize = 4, showstringspaces = false, breaklines = true, numbers = left, numberstyle = \tiny, basicstyle = \small \ttfamily, keywordstyle = \color{blue}, stringstyle = \color{red}, commentstyle = \color{green}, rulecolor = \color{black}}
\begin{document}
\begin{lstlisting}[language = python, frame = tRBl, basicstyle = \ttfamily \scriptsize, linebackgroundcolor = {\ifnum \value{lstnumber} = 8 \color{yellow} \fi, \ifnum \value{lstnumber} = 10 \color{yellow} \fi, \ifnum \value{lstnumber} = 12 \color{yellow} \fi}, linebackgroundsep = 2.2 em, linebackgroundwidth = 15 em]
import numpy
from tensorflow.keras.layers import Dense, Activation, Dropout, Input
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.optimizers import Adam
model_input = Input(shape = x_train[0].shape)
x = Dense(120, activation = 'relu')(model_input)
x = Dropout(0.01)(x)
x = Dense(120, activation = 'relu')(x)
x = Dropout(0.01)(x)
x = Dense(120, activation = 'relu')(x)
x = Dropout(0.01)(x)
model_output = Dense(numpy.shape(y_train)[1])(x)
model = Model(model_input, model_output)
\end{lstlisting}
\end{document}
你得到
但是,它仍然没有优化,您必须手动调整高亮条的左右边缘,并且设置多行高亮是很麻烦的。
于 2020-07-17T03:36:14.660 回答
0
Listings 包提供了 backgroundcolor=\color{} 作为一个选项,但我确信这会使整个 BG 颜色,而不是一个块。
你可以看看把它放在一个带颜色的 parbox 或 colorbox 包。
于 2009-08-20T16:10:08.883 回答