Highlighting a Chunk of Code within a lstlisting

Here's a solution for highlighting (parts of) individual lines using tikz:

\documentclass[pdftex,11pt,a4paper]{article}

\usepackage{listings}

\usepackage{tikz}
\usetikzlibrary{tikzmark}

% Command to place a TikZ anchor at the current position
\newcommand{\mytikzmark}[1]{%
  \tikz[overlay,remember picture,baseline] \coordinate (#1) at (0,0) {};}

\newcommand{\highlight}[2]{%
  \draw[yellow,line width=14pt,opacity=0.3]%
    ([yshift=4pt]#1) -- ([yshift=4pt]#2);%
}

\begin{document}
    \begin{lstlisting}[escapechar=@, language=C]
@\mytikzmark{hl1Start}@struct@\mytikzmark{hl1End}@ S {
    double @\mytikzmark{hl2Start}@salary_@\mytikzmark{hl2End}@;
};
    \end{lstlisting}
        
    \begin{tikzpicture}[remember picture, overlay]
        \highlight{hl1Start}{hl1End}
        \highlight{hl2Start}{hl2End}
    \end{tikzpicture}   
        
\end{document}

and you get

enter image description here

so the lstlisting's syntax highlighting is retained.


There is a package called lstlinebgrd that does this

% !TEX encoding = UTF-8 Unicode
% !TEX TS-program = xelatex
\documentclass{article}
\usepackage[a4paper]{geometry}

\usepackage{lstlinebgrd}
\usepackage{listings, xcolor}
\lstset{tabsize = 4, showstringspaces = false, breaklines = true, numbers = left, numberstyle = \tiny, basicstyle = \small \ttfamily, keywordstyle = \color{blue}, stringstyle = \color{red}, commentstyle = \color{green}, rulecolor = \color{black}}

\begin{document}

\begin{lstlisting}[language = python, frame = tRBl, basicstyle = \ttfamily \scriptsize, linebackgroundcolor = {\ifnum \value{lstnumber} = 8 \color{yellow} \fi, \ifnum \value{lstnumber} = 10 \color{yellow} \fi, \ifnum \value{lstnumber} = 12 \color{yellow} \fi}, linebackgroundsep = 2.2 em, linebackgroundwidth = 15 em]
import numpy
from tensorflow.keras.layers import Dense, Activation, Dropout, Input
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.optimizers import Adam

model_input = Input(shape = x_train[0].shape)
x = Dense(120, activation = 'relu')(model_input)
x = Dropout(0.01)(x)
x = Dense(120, activation = 'relu')(x)
x = Dropout(0.01)(x)
x = Dense(120, activation = 'relu')(x)
x = Dropout(0.01)(x)
model_output = Dense(numpy.shape(y_train)[1])(x)
model = Model(model_input, model_output)
\end{lstlisting}

\end{document}

and you get

highlight code

it is however, still not optimized, you have to manually adjust the left and right edge of highlight bar, and setting multiple lines to highlight is cumbersome.


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}

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}