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.


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

int main (int argc, char ** argv)
  |\makebox[0pt]{\color{yellow}\rule[-0.1ex]{30em}{2ex}}|printf("Hello, world\n");

enter image description here

  • if the listing environment has background, this solution may not work well -- there may be spaces that break the listing background. Feb 10 '14 at 3:48

Here is one easy-to-use solution built on posts from this site.

Sources :

  1. Creating a zebra effect using listings
  2. Listing, zebra effect and broken lines
  3. Highlighting line ranges in a lstlisting: partial solution, but expansion issues

The code:




% Define backgroundcolor

    \definecolor{bggray}{rgb}{0.85, 0.85, 0.85}
        leftmargin = 20pt,
        rightmargin = 20pt,
        backgroundcolor = bggray,
        middlelinecolor = black,
        roundcorner = 15

% \btIfInRange{number}{range list}{TRUE}{FALSE}
% Test if int number <number> is element of a (comma separated) list of ranges
% (such as: {1,3-5,7,10-12,14}) and processes <TRUE> or <FALSE> respectively

            \foreach \range in \bt@rangelist {%
                \pgfmathtruncatemacro\result{ ( #1 >= \bt@rangea) && (#1 <= \bt@rangeb) }%


                \bt@rangeb=100000%   \maxdimen is too large for pgfmath

% \btLstHL{range list}

% \btInputEmph[listing options]{range list}{file name}
            }% \only

% Patch line number key to call line background macro
                \kern\linewidth \kern\lst@numbersep
                \PackageError{Listings}{Numbers #1 unknown}\@ehc%

% New keys

% Line Background macro
                    \color{-.}% By default use the opposite (`-`) of the current color (`.`) as background



    language = C,
    linebackgroundcolor = {\btLstHL{4-6,9}},
* Prints Hello World.
#include <stdio.h>
int main(void) {
    printf("Hello World!");  
    return 0;


enter image description here

  • Was thinking about a similar solution, but realized that it will work only with highlighting full lines, not partial lines. Still very useful to have. One suggestion: can you make the sources on this site as part of the text (as opposed to part of the code) so that they are click able links, and post an image. Dec 2 '11 at 18:16
  • But this seems not working when I tried these code in Overleaf.
    – Instein
    Aug 29 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.