[Tex/LaTex] listings: How to increase space between backgroundcolor-box and code

listings

As you can see, the colored box created by backgroundcolor is quite tight. How can one increase the "padding", i.e., the space between the box and its content?

This seems to be related, but I don't have a frame around the color box, and the suggestions there did not solve the problem.

The package framed can put in shaded boxes (see the comments below), so one possibility would be to redefine lstlisting. Has anyone done that?

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}
\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{framed}

\xdefinecolor{shadecolor}{rgb}{0.97,0.97,0.97}
\lstset{% setup listings
    language=R,% set programming language
        backgroundcolor=\color{yellow}% background color
}

\begin{document}
\noindent Just some text.
%\begin{shaded*}
\begin{lstlisting}
x <- c(1, 3, 2)
id <- function(x){
    x # just a dummy
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x * x^x))
y ~ x + a
\end{lstlisting}
%\end{shaded*}
\end{document}

Best Answer

You can use framexleftmargin=<len> to adjust the left margin. To adjust the top and bottom, there are similar options, but seem that you also need to specify frame=tb, to get the additional padding added on the top and bottom. Including framerule=0pt will remove the rule if that is not desired.

enter image description here

Code:

\documentclass{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[american]{babel}
\usepackage{graphicx}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{framed}

\xdefinecolor{shadecolor}{rgb}{0.97,0.97,0.97}
\lstset{% setup listings
    language=R,% set programming language
        backgroundcolor=\color{yellow},% background color
        framexleftmargin=16pt,
        framextopmargin=6pt,
        framexbottommargin=6pt, 
        frame=tb, framerule=0pt,
}

\begin{document}
\noindent Just some text.
%\begin{shaded*}
\begin{lstlisting}[caption={A first example}, label=list:ex]
x <- c(1, 3, 2)
id <- function(x){
    x # just a dummy
}
3 <= 4
3 != 4
!TRUE
y <- "foo"
(pv <- sum(x * x^x))
y ~ x + a
\end{lstlisting}
%\end{shaded*}
\end{document}