Highlighting a Chunk of Code within a lstlisting

二次信任 提交于 2019-12-20 09:48:31

问题


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?


回答1:


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}



回答2:


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}



回答3:


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.



来源:https://stackoverflow.com/questions/1304315/highlighting-a-chunk-of-code-within-a-lstlisting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!