# Color behind numbers in lstlisting

Currently, my listings use this style :

\definecolor{lstgrey}{RGB}{217, 217, 217}
\definecolor{lstback}{RGB}{246, 246, 246}
\newlength{\numberlengthnormal}
\setlength{\numberlengthnormal}{\widthof{\fontfamily{cmtt}\selectfont 999}}
\setlength{\numberlengthnormal}{0.25\numberlengthnormal}
\lstnewenvironment{lstcpp}
{\lstset{%
language = C++,
tabsize=2,
basicstyle=\fontfamily{cmtt}\selectfont,
keywordstyle=\color{blue},
morekeywords={constexpr, kind, parameter, allocatable},
showstringspaces = false,
backgroundcolor=\color{lstback},
numbers = left,
numbersep = 2\numberlengthnormal,
xleftmargin = 6\numberlengthnormal,
}}%


How to color the background of numbers as in the following example ?

You were almost there.

\documentclass{article}
\usepackage{xcolor,listings,calc}
\definecolor{lstgrey}{RGB}{217, 217, 217}
\definecolor{lstback}{RGB}{246, 246, 246}
\newlength{\numberlengthnormal}
\setlength{\numberlengthnormal}{\widthof{\fontfamily{cmtt}\selectfont 999}}
\lstnewenvironment{lstcpp}[1][]
{\lstset{%
language = C++,
tabsize=2,
basicstyle=\fontfamily{cmtt}\selectfont,
numberstyle=\darknumbers,
keywordstyle=\color{blue},
morekeywords={constexpr, kind, parameter, allocatable},
showstringspaces = false,
backgroundcolor=\color{lstback},
numbers = left,
numbersep = 0pt,
xleftmargin = \numberlengthnormal,
#1,
}}{}

\newcommand{\darknumbers}[1]{%
\begingroup\fboxsep=0pt
\colorbox{lstgrey}{\makebox[\numberlengthnormal]{\strut#1}}%
\endgroup
}

\begin{document}

\begin{lstcpp}
#include <iostream>
#include <cmath>
\end{lstcpp}

\end{document}


• Is it possible to remove the blank line between you two lines ? – Vincent Aug 5 '14 at 17:20
• @Vincent Done; I just changed the definition of \darknumbers – egreg Aug 5 '14 at 17:27
• and how to align the numbers on the right (and not on the center of the box) as when there is a non null numbersep ? – Vincent Aug 5 '14 at 17:30
• @Vincent \makebox[\numberlengthnormal][r]{\strut#1 }, that is, add [r] and a space after #1 in the definition of \darknumbers. – egreg Aug 5 '14 at 17:31