1

I'm trying to use @egreg's answer to this question about obtaining a uniform background colour with the listings package. In my MSE I'm using the acmart class to reproduce the problem from the original question (and thus motivate my use of tcolorbox in the first place), but the problem also arises with article.

The problem is that using tcolorbox to provide a listings environment produces an additional blank line of "padding" above and below the listed code, as shown in the second listing below:

enter image description here

There are two other problems with the tcolorbox solution: the placement of the line numbers differs from the plain lstlistings version, and the width of the shaded region doesn't quite run to the edge of the column. (The latter is not hugely problematic.)

\documentclass{acmart}

\usepackage{xcolor}
\usepackage{listings}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\definecolor{verylightgray}{gray}{0.9}

\newtcblisting{graylstlisting}[1][]
{
  spartan,
  frame empty,
  boxsep=0mm,
  listing only,
  colback=verylightgray,
  listing options={
    #1
  },
}

\begin{document}

\begin{lstlisting}[
  numbers=left,
  backgroundcolor=\color{verylightgray}
]
f g h
\end{lstlisting}

\begin{graylstlisting}[
  numbers=left,
  backgroundcolor=\color{verylightgray}
]
f g h
\end{graylstlisting}

\end{document}

Is there a way to use the tcolorbox solution for listings backgrounds, without introducing these other differences?

1 Answer 1

2
\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\usepackage[many]{tcolorbox}
\tcbuselibrary{listings}

\definecolor{verylightgray}{gray}{0.9}

\newtcblisting{graylstlisting}[1][]
{
  spartan,
  frame empty,
  boxsep=0mm,
  listing only,
  colback=verylightgray,
  top = 0pt, %<-
  bottom = 0pt,%<- 
  left=0pt,%<- 
  listing options={
   numbersep=10pt,% <-
   xleftmargin=0pt,%<-
   aboveskip = 0pt,%<-
   belowskip = 0pt,%<-
    #1
  },
}

\begin{document}

\begin{lstlisting}[
  numbers=left,
  backgroundcolor=\color{verylightgray}
]
f g h
\end{lstlisting}

\begin{graylstlisting}[
  numbers=left,
  backgroundcolor=\color{verylightgray}
]
f g h
\end{graylstlisting}

\end{document}

enter image description here

1
  • That does it for me. Thanks!
    – Roly
    Commented Jul 30, 2019 at 10:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .