# How can I add code highlighting for listings with different colour lines?

How can I create a listing design in LaTeX, with numbers on the left, and each line separated with colours like in the picture? I could not find such listing style for LaTeX.

As mentioned in the comments, for alternating line background colors the lstlinebgrd package can be used (see also this thread). For the line numbers' background color we can use an extra wide frame only on the left side of the listing, for the separator rule we can combine the frame separator with the fill color.

We use the following options to adjust the layout (I think the rest is self-explaning):

• framexleftmargin indents the code a bit, linebackgroundsep and linebackgroundwidth compensate the background coloring for this indentation.
• framesep sets a small gap between the code and the left frame which is filled by fillcolor.
• framerule is the width of the left frame, rulecolor is its color and numbersep is the distance of the line numbers from the right side of the frame plus gap. There's an extra macro \numberstyle for styling the line numbers itself to test for numbers smaller than ten and pad them with a leading zero if necessary.
• xleftmargin pushes the whole listings to the right by the width of the frame, the gap and the indentation such that the line numbers aren't printed in the left margin.

Full example code:

\documentclass{article}

\usepackage{listings}
\usepackage{lipsum}
\usepackage{xcolor}
\usepackage{lstlinebgrd}

\lstset{
basicstyle = \ttfamily\small,
numbers=left,
numberstyle=\numberstyle,
linebackgroundcolor=\linebgstyle,
frame=l,
% code indentation
framexleftmargin=0.5em,
linebackgroundsep=0.5em,
linebackgroundwidth=\dimexpr\linewidth+0.5em\relax,
% separation rule
framesep=3pt,
fillcolor=\color{green!80!black},
% numbers background
framerule=4em,
numbersep=\dimexpr 1.5em+3pt\relax,
rulecolor=\color{lightgray!50!white},
% don't put numbers into margin
xleftmargin=\dimexpr 4em+3pt+0.5em\relax,
}
\newcommand\linebgstyle{%
\ifodd\value{lstnumber}%
\color{white}%
\else
\color{lightgray!10!white}%
\fi
}
\newcommand\numberstyle[1]{%
\small\ttfamily
\color{gray!60!black}%
\ifnum#1<10 0\else\fi
#1.%
}

\begin{document}

\lipsum[1]

% example code from http://esd.cs.ucr.edu/labs/tutorial/DRIVER.vhd
\begin{lstlisting}
library ieee;
use ieee.std_logic_1164.all;

entity Driver is
port(   x: in std_logic;
F: out std_logic
);
end Driver;

architecture behv1 of Driver is
begin

process(x)
begin
-- compare to truth table
if (x='1') then
F <= '1';
else
F <= '0';
end if;
end process;

end behv1;

architecture behv2 of Driver is
begin

F <= x;

end behv2;
\end{lstlisting}

\end{document}


outputs

• It only works if I remove the \usepackage{lstlinebgrd}. And also it is not aligned on the left of the page which makes the code get out of the page. Thanks for the try though ! Nov 27 '19 at 3:43