我正在使用这个listings
包。使用下面的代码我得到了这样的结果
另外,如果可能的话,我想改变行号的背景颜色。
我使用的代码如下
\documentclass[12pt, a4paper]{report}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\lstdefinestyle{mystyle}{
basicstyle=\ttfamily\footnotesize,
escapeinside={(*}{*)},
frame=single,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=2,
numbers=left,
numbersep=5pt,
framexleftmargin=1.5em,
xleftmargin=2em,
backgroundcolor=\color{backcolour},
commentstyle=\color{codegreen},
keywordstyle=\color{magenta},
numberstyle=\color{codegray},
stringstyle=\color{codepurple}
}
\lstset{style=mystyle}
\begin{document}
\begin{lstlisting}[language=python]
for j=2 to A.length
key=A[j]
i=j-1
while i>0 and A[i]>key
A[i+1]=A[i]
i=i-1
A[i+1]=key
\end{lstlisting}
\end{document}
答案1
我建议使用 tcolorbox 包作为框架。
\lstdefinestyle{mystyle} 中的说明
%frame=single, %framexleftmargin=1.5em, %xleftmargin=2em, %backgroundcolor=\color{backcolour} 不再使用
数字的背景颜色例如为 \colorlet{mycodebacknum}{gray!70}
\documentclass{standalone} \usepackage{listings} \usepackage{xcolor} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \usepackage{tcolorbox} \tcbuselibrary{skins,listings,breakable} \definecolor{codegreen}{rgb}{0,0.6,0} \definecolor{codegray}{rgb}{0.5,0.5,0.5} \definecolor{codepurple}{rgb}{0.58,0,0.82} \definecolor{backcolour}{rgb}{0.95,0.95,0.92} \lstdefinestyle{mystyle}{ basicstyle=\ttfamily\footnotesize, escapeinside={(*}{*)}, %frame=single, breakatwhitespace=false, breaklines=true, captionpos=b, keepspaces=true, showspaces=false, showstringspaces=false, showtabs=false, tabsize=2, numbers=left, numbersep=5pt, %framexleftmargin=1.5em, %xleftmargin=2em, %backgroundcolor=\color{backcolour}, commentstyle=\color{codegreen}, keywordstyle=\color{magenta}, numberstyle=\color{codegray}, stringstyle=\color{codepurple} } \lstset{style=mystyle} \colorlet{mycodebacktitre}{backcolour} \colorlet{mycodebacktrait}{gray!70} \colorlet{mycodebacknum}{gray!70} \newtcolorbox{mycode}[1]{ % breakable, hbox boxed title, enhanced, colbacktitle=mycodebacktitre, fonttitle=\bfseries, coltitle=black, attach boxed title to top center={yshift=-2mm}, % colback=mycodebacktitre, colframe=mycodebacktrait, % title={#1}, overlay={\begin{tcbclipinterior}\fill[mycodebacknum] (frame.south west) rectangle ([xshift=1.5em]frame.north west);\end{tcbclipinterior}}% pour colorer la zone numéro} } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{document} \begin{mycode}{title} \begin{lstlisting}[language=python] for j=2 to A.length key=A[j] i=j-1 while i>0 and A[i]>key A[i+1]=A[i] i=i-1 A[i+1]=key \end{lstlisting} \end{mycode} \end{document}