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
orminipage
, 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. Fortunatelyfancybox
package provides the environmentSbox
devised for this kind of cases.So my proposed solution is:
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.