I have a bunch of code in a lstlisting environment. How can I highlight (color background) just a particular chunk of code within the environment?
A:
the listings package provides backgroundcolor=\color{} as an option, but i'm sure that makes the whole BG color, not a chunk.
you could have a look at putting it a parbox with color, or the colorbox package.
Mica
2009-08-20 16:10:08
+1
A:
It's a bit cumbersome, but you can break the code into several lstlisting
environments.
\begin{lstlisting}
line
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}[backgroundcolor=\color{pink}]
very
interesting
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}
line
line
\end{lstlisting}
Anton Geraschenko
2009-08-21 19:03:06
Will this work if you've got, for example, line numbers, or will they get restarted?
Edd
2009-08-21 19:06:34
@Edd: By default, they will get restarted, but you can use the `firstnumber` keyword to fix that. In this example, you'd use `firstnumber=2` and `firstnumber=4` in the second and third `lstlisting` environments, respectively. Using `firstnumber=last` is supposed to continue the numbering from the previous `lstlisting` environment, but when I try it, it's off by one.
Anton Geraschenko
2009-08-21 19:52:21
It turns out there's an even better solution to the numbering problem: use the `name` keyword (eg `\begin{lstlisting}[name=asdf, ...`). The name doesn't get displayed, and `lstlisting` environments with the same name share a line counter by default.
Anton Geraschenko
2009-08-21 20:11:50
+4
A:
You can use \colorbox and an escape character inside your listing:
Add to your preamble
\usepackage{color}
\definecolor{light-gray}{gray}{0.80}
then use it like this in your document:
\begin{lstlisting}[escapechar=!]
def mult(m: Matrix[Int], n: Matrix[Int]) {
val p = !\colorbox{light-gray}{new MatrixInt}!(m.rows, n.cols)
}
\end{lstlisting}
Iulian Dragos
2010-02-24 14:44:50
I need something extra. I am using Beamer package for my presentation and I have to highlight code present in lstlisting. The difference in my need is I can't change the code inside lstlisting, like escaping or having special comment definition.The code is present inside a different file which can't be changed. Copying the code and making modifications is not an option as there are many of them.Can we indicate from outside (i.e. in \begin{lstlisting}) which lines to highlight?
thequark
2010-07-20 11:22:17