[Tex/LaTex] Shrink lstlisting frames to code content

framedlistings

I use lstlistings to include code in my document. I'd like my code to be framed and its frame to be adjusted to the size of the actual code content. Here is what I have as of now :

\lstset{numbers=left, numberstyle=\small, numbersep=8pt, frame = single, language=Pascal, framexleftmargin=15pt}

\begin{lstlisting}
PROGRAM afficher_bonjour; 
BEGIN WRITE('Bonjour'); 
END.
\end{lstlisting}

The frame is being drawn across the entire width of the page instead of being shrinked to the listing contents. There's a lot of useless empty space on the right.

I could manually set the linewidth of the listing or wrap it in a manually sized minipage. This however results in a lot of manual work when using many listings and I would like to avoid that.

Is there any way to have the frame size or the linewidth of a listing automatically be fitted to the listing's content?

Best Answer

Another option is to use the linewidth option for lstlisting to control the width:

\documentclass{article}
\usepackage{listings}

\lstset{
numbers=left, 
numberstyle=\small, 
numbersep=8pt, 
frame = single, 
language=Pascal, 
framexleftmargin=15pt}

\begin{document}

\begin{lstlisting}
PROGRAM afficher_bonjour; 
BEGIN WRITE('Bonjour'); 
END.
\end{lstlisting}

\begin{lstlisting}[linewidth=5.4cm]
PROGRAM afficher_bonjour; 
BEGIN WRITE('Bonjour'); 
END.
\end{lstlisting}

\end{document}​

enter image description here