列表中数字背后的颜色

列表中数字背后的颜色

目前,我的列表使用这种样式:

\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,
}}%

如何像以下示例一样为数字的背景着色?

在此处输入图片描述

答案1

你几乎就到了。

\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}

在此处输入图片描述

相关内容