[Tex/LaTex] How to center a lstlisting

horizontal alignmentlistings

I have the following problem. I want to center a listing, I tried this approach: How to center a listing?

It works but when I try to set frame or numbers specifically for each listing I get errors. HereĀ“s the M(Not)WE:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\begin{document}

\begin{figure}[thp]
 \begin{tabular}{c}
  \begin{lstlisting}[numbers=left] % Here lies the problem without the numbers=left it works
   My Code
  \end{lstlisting}
 \end{tabular}
 \centering
 \caption{Bla}
\end{figure}

\end{document}

Is there another way to center the listings and captions or how could I fix this approach?

Best Answer

The solution involving a table does not work here probably because lstlisting uses itself a table or other kind of tabular to put the numbers on the listing.

So the required solution for this case involves to save the content of the listing into a box, and then use the width of that box to size a \parbox or minipage, and put the original box inside. This new box can be centered by usual methods.

The problem is that lstlisting environment is a "verbatim-like" environment, and putting this kind of environment inside a box causes some problems. Fortunately fancybox package provides the environment Sbox devised for this kind of cases.

So my proposed solution is:

\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{fancybox}

\makeatletter
\newenvironment{CenteredBox}{% 
\begin{Sbox}}{% Save the content in a box
\end{Sbox}\centerline{\parbox{\wd\@Sbox}{\TheSbox}}}% And output it centered
\makeatother

\begin{document}

\begin{figure}[thp]
\begin{CenteredBox}
  \begin{lstlisting}[numbers=left]
  My Code
  Another line
  \end{lstlisting}
\end{CenteredBox}
\caption{Bla}
\end{figure}

\noindent X\hrulefill X\par % This is to see the page width

\end{document}

Result

Note that numbers are not part of the box (they are typeset with some kind of \llap), so they are not taken into account to center it.