views:

1843

answers:

3

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
+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
Will this work if you've got, for example, line numbers, or will they get restarted?
Edd
@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
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
+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
Thanks! This ix exactly what I needed.
Ryan Rosario
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