# Caption package destroys center/varwidth

I have received a wonderful comment how to get listings centered:

\documentclass[a4paper]{book}
%\usepackage[hang,small,it,hypcap=true]{caption}  % screw hypcap
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{listings}
\lstset{
fancyvrb=true,%
}
\usepackage{varwidth}

\lstset{
fancyvrb=true,%
captionpos=b
}

\begin{document}

\begin{center}\begin{varwidth}{\linewidth}%
\begin{lstlisting}[caption={I want to be centered},label={lst:label2}]
trait Sys[S <: Sys[S]] {
type Tx     <: stm.Txn[S]
type Var[A] <: stm.Var[S#Tx, A]
type ID     <: stm.Identifier[S#Tx]
type Acc
...
}
\end{lstlisting}\end{varwidth}
\end{center}

\end{document}


So far so good:

If I add the caption package (uncomment in the example above) which I must do because a lot of stuff relies on it, the centering is destroyed:

I also found that adding the showframe package has the same problem, so perhaps the culprit is center or varwidth and not caption. How to fix this?

varwidth is not able to cope with arbitrary contents and you get the warning

Package varwidth Warning: Failed to reprocess entire contents


In these cases the environment becomes simply a minipage with the stated width. You can do with the caption outside the lstlisting environment:

\documentclass[a4paper]{book}
\usepackage[T1]{fontenc}

\usepackage[
hang,
small,
it,
hypcap=true
]{caption}
\usepackage{fancyvrb}
\usepackage{listings}
\lstset{
fancyvrb=true,
}
\usepackage{varwidth}

\lstset{
fancyvrb=true,
captionpos=b
}

\begin{document}

\begin{center}
\begin{varwidth}{\linewidth}
\begin{lstlisting}
trait Sys[S <: Sys[S]] {
type Tx     <: stm.Txn[S]
type Var[A] <: stm.Var[S#Tx, A]
type ID     <: stm.Identifier[S#Tx]
type Acc
...
}
\end{lstlisting}\end{varwidth}
\captionof{lstlisting}{I want to be centered}\label{lst:label2}
\end{center}

\end{document}


Watch out about possible page breaks between the listing and the caption. A float would be better; figure (with \captionof{lstlisting}) would be good.

• Thanks. I have a problem with this solution when adding the color package. It seems to break the alignment (see this question). I found another variant which I will post below. – Emit Taste Aug 13 '14 at 19:44

Here is another solution:

\documentclass[a4paper]{book}
\usepackage[T1]{fontenc}

\usepackage{caption}
\usepackage{fancyvrb}
\usepackage{listings}

\begin{document}

\begin{figure}
\centering
\lstset{xleftmargin=0.18\textwidth,xrightmargin=0.18\textwidth}
\begin{lstlisting}
trait Sys[S <: Sys[S]] {
type Tx     <: stm.Txn[S]
type Var[A] <: stm.Var[S#Tx, A]
type ID     <: stm.Identifier[S#Tx]
type Acc
...
}
\end{lstlisting}
\captionof{lstlisting}{Type members of the system abstraction}\label{lst:scala_system_decl}
\end{figure}

\end{document}