I need to change background color for some lines inside a listings
block. This is an example:
\documentclass{article}
\usepackage{listings} % Include the listings-package
\usepackage{xcolor}
\newcommand{\add}{\makebox[0pt]{\color{green}\rule[-1ex]{\paperwidth}{3ex}}}
\begin{document}
\lstset{ %
escapechar=|,
language=Python % the language of the code
}
\begin{lstlisting}
#!/usr/bin/env python
import sys
import os
class Foo:
def __init__(self):
x = 8
x = 9
|\add|# some additions
|\add|x = 10
|\add|if True:
|\add| x = 11
x = 20
x = 21
\end{lstlisting}
\end{document}
the problem is that instead of a single green block, it appears a "cebra" pattern with one green block for each line:
Some suggestions about how to fix this issue?
(I know there are several similar questions, but none of the found answers seems applicable).
Thanks.
Best Answer
Try the
fvextra
package (fvextra
– Extensions and patches for fancyvrb), specifically, thehighlightlines
feature. Note that you may also have to use the line numbering option in order to deduce which are the lines that you want to highlight. Of course, you can switch this option off afterwards.Here is your MWE (mind the capital V in
Verbatim
):which produces
PS: for compatible (Python) syntax colouring you might want to try the
pygments
package from the same author. It is basically a Python script that can also output LaTeX code. Many programing languages are supported.