Highlighting a Chunk of Code within a lstlisting

Ryan R. Rosario picture Ryan R. Rosario · Aug 20, 2009 · Viewed 25.5k times · Source

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?

Answer

Iulian Dragos picture Iulian Dragos · Feb 24, 2010

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}