3

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},
    commentstyle=\color{green},
    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 ?

enter image description here

1 Answer 1

3

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},
    commentstyle=\color{green},
    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}

enter image description here

4
  • Is it possible to remove the blank line between you two lines ?
    – Vincent
    Aug 5, 2014 at 17:20
  • 1
    @Vincent Done; I just changed the definition of \darknumbers
    – egreg
    Aug 5, 2014 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, 2014 at 17:30
  • 1
    @Vincent \makebox[\numberlengthnormal][r]{\strut#1 }, that is, add [r] and a space after #1 in the definition of \darknumbers.
    – egreg
    Aug 5, 2014 at 17:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .