1

What is a simple way to make a lstlisting centered? Like

\documentclass{article}
\usepackage{verbatimbox}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{listings}

\lstset{
    fancyvrb=true,%
    captionpos=b, % captions at the bottom
}

\begin{document}

\begin{lstlisting}[caption={I want to be centered},label={lst:label}]
object Stream {
  def cons[A](hd: A, tl:...
     def head = hd
     lazy val tail = tl
     ...
  }
}
abstract class Stream[A] {
  def head: A
  def tail: Stream[A]
  def take(n: Int): Stream[A]
  def foreach(fun: A...
}
\end{lstlisting}

\end{document}

Note: Putting it inside a tabular inside a figure neither works (captions are screwed), nor does it fall under my idea of simple. The other answer in that question (using \begin{center}) also doesn't work for me. Also taking the caption out of listing and into the figure is not an option, because I am precisely using lstlisting because I want separate enumerations for separate table of figures versus table of listings.

If this can be done in a macro and without corner case, I am happy to have another macro. Thanks!

Emit Taste
  • 4,404
  • 1
    The following works: \begin{center} \begin{varwidth}{\linewidth} \begin{lstlisting} ... \end{lstlisting} \end{varwidth} \captionof{lstlisting}{I want to be centered\label{lst:label}} \end{center} (adding the caption and varwidth packages to your preamble). – Werner Nov 05 '13 at 21:50
  • Perfect, can you post that as an answer? BTW captionof doesn't work here, probably needs another package, but the regular lstlisting options for caption and label still work fine. – Emit Taste Nov 05 '13 at 21:56
  • Damn. It works isolated, but not in my thesis. Shows up left aligned :-( – Emit Taste Nov 05 '13 at 22:01
  • It seems that \begin{varwidth}{\linewidth} has wrong information. I can find a concrete value, like \begin{varwidth}{10cm} for which it works. Why might varwidth be broken? – Emit Taste Nov 05 '13 at 22:09
  • As you can see, I put the \caption outside the varwidth environment, just like in @egreg's answer... is that not sufficient? – Werner Nov 05 '13 at 23:06

0 Answers0