how to crop background color in listings to the longest line in the code?

listings package allows one to put background color to the code listing. The problem is that the background color extents to the as large as the text area the code listings happened to be in. This can make it look ugly if the code was short in width, but the area it is in is large. Here is MWE

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{color}
\usepackage{listings}
\definecolor{bg}{RGB}{240,240,240}

\begin{document}
\begin{tabular}{|p{0.8\textwidth}|p{.2\textwidth}|}\hline
\begin{lstlisting}[language=Mathematica,backgroundcolor=\color{bg}]
f[x_] := Sin[x];
Plot[f[x],{x,-Pi,Pi}]
\end{lstlisting}
&
plot command
\\\hline
\end{tabular}
\end{document}


gives this

What I'd like to get is this

(ps. I used my highly developed skills in paint.exe to do the above manually).

The problem is one does not know how "wide" the code will be, in order to may be put maybe a minipage around it of that specific width or a frame or such trick in order to limit the area.

Any tricks one can do to help solve this?

Does Latex have a command to find what is the length of longest line in the listing? If so, then one can use this length (plus a little bit more) to make a frame or minipage with it.

• I don't know any automated way to do this, but you can limit the width of the background with the lstlisting parameter linewidth=14em . May 29, 2016 at 20:46

You can use tcblisting environment from tcolorbox package. With hbox key it'll be sized according to the dimensions of the content.

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{color}
\usepackage{listings}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\definecolor{bg}{RGB}{240,240,240}

\begin{document}

\begin{tabular}{|p{0.8\textwidth}|p{.2\textwidth}|}\hline
\begin{lstlisting}[language=Mathematica,backgroundcolor=\color{bg}]
f[x_] := Sin[x];
Plot[f[x],{x,-Pi,Pi}]
\end{lstlisting}
&
plot command
\\\hline
\end{tabular}

\begin{tabular}{|p{0.8\textwidth}|p{.2\textwidth}|}\hline
\begin{tcblisting}{colback=bg,size=minimal,hbox,listing only,listing options={language=Mathematica}}
f[x_] := Sin[x];
Plot[f[x],{x,-Pi,Pi}]
\end{tcblisting}
&
plot command
\\\hline
\end{tabular}

\end{document}


• Thanks. Nice solution. For some reason it does not work in longtable which I am using, so I posted separate question on that issue here. I am actually using longtable and not tabular. May 30, 2016 at 17:49