Stripes in background color drawn by listings package [closed]
Asked Answered
A

1

10

I'm trying to create a verbatim environment with a colored background and which can span across pages (so using a colorbox is not an option). It seemed that the listings package was a good way towards it, but the background is drawn one line at a time, such that, when I view the PDF, I see annoying white-ish "stripes" between the lines as well as where the invisible (0pt) frame rule was not to be drawn:

http://a.imageshack.us/img202/9928/lststrips.png

Here's the minimal code I used to create the output shown in the image:

\documentclass{minimal}
\usepackage[pdftex]{xcolor}
\usepackage[a4paper,hmargin=6cm]{geometry}
\usepackage{listings}
\lstset{backgroundcolor=\color{gray},
  frame=single, framerule=0pt, framesep=5pt}
\begin{document}

\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}

\end{document}

Is there any workaround against these 'stripes'?

Anglesite answered 30/7, 2010 at 17:54 Comment(3)
Off topic. Belongs on tex.SEAmain
Since when is LaTeX off-topic here...Allerie
It is at tex.SE: tex.stackexchange.com/questions/403147.Ellita
S
4

A simple workaround would be to not specify a color for the listings themselves, put instead use a \colorbox, but for that to work, you either need to use \lstinputlisting or store the result in a box using e.g. lrbox.

\newbox{\mybox}
\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}
\end{minipage}
\end{lrbox}
\colorbox{gray}{\usebox{\mybox}}

UPDATE: However, a more beautiful solution is to use Donald Arseneau's framed.sty, which also allows the source-code to span multiple pages.

\documentclass{minimal}
\usepackage[pdftex]{xcolor}
\usepackage[a4paper,hmargin=6cm]{geometry}
\usepackage{listings}
\usepackage{framed}
\begin{document}

\definecolor{shadecolor}{named}{gray} 
\begin{shaded}
\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}
\end{shaded}

\end{document}
Slapjack answered 3/8, 2010 at 15:40 Comment(2)
The problem is that, by wrapping it inside a \colorbox, the lstlisting environment loses the possibility of spanning across pages.Anglesite
Hi grddev. I like your solution using the framed package. One problem is that the line numbers and lstlistings caption are occluded, in whole or in part, by the shaded box. Do you know a work-around? Thanks.Provincialism

© 2022 - 2024 — McMap. All rights reserved.