18

Consider the following example:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\begin{document}
\definecolor{light-gray}{gray}{0.95}
\lstset{columns=fullflexible, basicstyle=\ttfamily,
    backgroundcolor=\color{light-gray},xleftmargin=0.5cm}
\begin{lstlisting}
Test code
\\ a bit of comments
\end{lstlisting}
\end{document}

which looks like this: enter image description here

Now I have two questions:

  1. How do I get rid of this white (clearly unintentional) line?
  2. How can I add (a bit of) "gray" space inside the code box (not white space ala xleftmargin=0.5cm)? The code is right at the edge of the box, which in my opinion looks sloppy and not well-formated.

Basically I want it to look somewhat like this: enter image description here

1 Answer 1

15
  1. That line is just an artifact of the viewer.

  2. Declare an invisible frame to the left (and to the right) and use the desired value for framesep.

An example:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\begin{document}
\definecolor{light-gray}{gray}{0.95}
\lstset{columns=fullflexible, basicstyle=\ttfamily,
    backgroundcolor=\color{light-gray},xleftmargin=0.5cm,frame=lr,framesep=8pt,framerule=0pt}
\begin{lstlisting}
Test code
\\ a bit of comments
\end{lstlisting}
\end{document}

enter image description here

Using a frame in the four sides:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\begin{document}
\definecolor{light-gray}{gray}{0.95}
\lstset{columns=fullflexible, basicstyle=\ttfamily,
    backgroundcolor=\color{light-gray},xleftmargin=0.5cm,frame=tlbr,framesep=4pt,framerule=0pt}
\begin{lstlisting}
Test code
\\ a bit of comments
\end{lstlisting}
\end{document}

enter image description here

To have control over the separation on each side independently, you can use the mdframed package to surround lstlisting with a frame with the desired specifications:

\documentclass{article}
\usepackage{listings}
\usepackage{color}
\usepackage[framemethod=tikz]{mdframed}

\definecolor{light-gray}{gray}{0.95}
\lstset{columns=fullflexible,basicstyle=\ttfamily}
\surroundwithmdframed[
  hidealllines=true,
  backgroundcolor=light-gray,
  innerleftmargin=15pt,
  innertopmargin=0pt,
  innerbottommargin=0pt]{lstlisting}

\begin{document}

\begin{lstlisting}
Test code
\\ a bit of comments
\end{lstlisting}

\end{document}

enter image description here

2
  • Is it possible to adjust the top and left margin independently?
    – Phil-ZXX
    Jun 18, 2013 at 23:26
  • 1
    @Tom in this case, a better approach would be to use mdframed. Please see my updated answer. Jun 18, 2013 at 23:49

You must log in to answer this question.

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