![列表中数字背后的颜色](https://linux22.com/image/295695/%E5%88%97%E8%A1%A8%E4%B8%AD%E6%95%B0%E5%AD%97%E8%83%8C%E5%90%8E%E7%9A%84%E9%A2%9C%E8%89%B2.png)
目前,我的列表使用这种样式:
\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}