[Tex/LaTex] How to mark whole line or part of line with background color in a listing (listings package)

colorlistings

I want to highlight either a whole line of code in a listing, or a part of line (a subexpression) using background color (to not interfere with syntax highlighting).

I use lstlistings environment from 'listings' package.

Best Answer

Listings allow escaping to TeX, so you can put a box in the background:

\documentclass{standalone}
\usepackage{listings,xcolor}
\lstset{language=c,escapechar=|}
\begin{document}
\begin{lstlisting}
int main (int argc, char ** argv)
{
  |\makebox[0pt]{\color{yellow}\rule[-0.1ex]{30em}{2ex}}|printf("Hello, world\n");
  exit(0);
}
\end{lstlisting}
\end{document}

enter image description here