Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

Consider the following code which deals with a 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}

Is there a way to coulour the background of line numbers (in grey for example) but not the background of the code ?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

listings doesn't have a predefined option for this, but if you are willing to use the tcolorbox package, which has a nice interaction with the listings package, here's how you can do it:

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

enter image description here

share|improve this answer
    
Thanks ! If you have an idea for this question tex.stackexchange.com/questions/176431/… It would be fantastic ! –  Vincent May 10 at 17:31
1  
@Vincent You're welcome! Right now I have to leave but in some hours I can take a look at the other question (if no one else has provided an answer by then). –  Gonzalo Medina May 10 at 17:47

Another way would be to work with frames and their margins so you can use the normal lstlisting command.

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

This snippet will result in following style:

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.