リスト内の行番号の背景色を変更しますか?

リスト内の行番号の背景色を変更しますか?

を扱う次のコードを考えてみますlstlisting

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor}
\lstset{basicstyle=\small\ttfamily,keywordstyle=\color{blue},language=C++,showstringspaces=false,tabsize=2,numbers=left}
\begin{document}

\begin{lstlisting}
#include <stdio.h>
int main(void) {
  printf("Hello World!");
  return 0;
}
\end{lstlisting}

\end{document}

コードの背景には色を付けずに、行番号の背景に色 (たとえば灰色) を付けることができる方法はありますか?

答え1

listingsこれには定義済みのオプションはありませんが、tcolorboxパッケージとうまく相互作用するlistingsパッケージを作成するには、次のようにします。

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\newtcblisting{mycpp}{
  colback=white,
  boxrule=0pt,
  arc=0pt,
  outer arc=0pt,
  top=0pt,
  bottom=0pt,
  colframe=white,
  listing only,
  left=15.5pt,
  enhanced,
  listing options={
    basicstyle=\small\ttfamily,
    keywordstyle=\color{blue},
    language=C++,
    showstringspaces=false,
    tabsize=2,
    numbers=left
  },
  overlay={
    \fill[gray!30] 
      ([xshift=-3pt]frame.south west)
      rectangle 
      ([xshift=11.5pt]frame.north west);
  }
}

\begin{document}

\begin{mycpp}
#include <stdio.h>
int main(void) {
  printf("Hello World!");
  return 0;
}
int main(void) {
  printf("Hello World!");
  return 0;
}
int main(void) {
  printf("Hello World!");
  return 0;
}
\end{mycpp}

\end{document}

ここに画像の説明を入力してください

答え2

もう 1 つの方法は、フレームとその余白を操作して、通常の lstlisting コマンドを使用することです。

\lstset {
...
frame=l,
framesep=4.5mm,
framexleftmargin=2.5mm,
fillcolor=\color{numberbg},
rulecolor=\color{ballblue},
numberstyle=\normalfont\tiny\color{numbercolor}
}

このスニペットは次のようなスタイルになります:

ここに画像の説明を入力してください

関連情報