添加颜色包会破坏列表居中

添加颜色包会破坏列表居中

我正在使用@egreg回答使列表居中:

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

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

\lstset{
    basicstyle=\linespread{0.94}\ttfamily,
    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}

乍一看还不错:

在此处输入图片描述

然而:发生了一些奇怪的事情。当我添加color包时,对齐被破坏了:

\usepackage{color}  % add somewhere to above document

结果:

在此处输入图片描述

请帮忙。我需要包含颜色包。它怎么会破坏对齐?

答案1

这会添加一个额外的括号组,使框设置为\lst@DeInit“颜色安全”,然后删除,\normalcolor如评论中 egreg 所述。似乎适用于此示例。

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

\usepackage{color}

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

\lstset{
    basicstyle=\linespread{0.94}\ttfamily,
    fancyvrb=true,
    captionpos=b
}
\makeatletter
\def\lst@DeInit{%
    \lst@XPrintToken \lst@EOLUpdate
    \global\advance\lst@newlines\m@ne
    \lst@ifshowlines
        \lst@DoNewLines
    \else
        \setbox\@tempboxa\vbox{{\lst@DoNewLines}}%extra group for color
    \fi
    \lst@ifdisplaystyle \par\removelastskip \fi
    \lsthk@ExitVars\everypar{}\lsthk@DeInit\normalbaselines
    \lst@MakeCaption b%
    \lst@ifbox
        \egroup $\hss \egroup
        \vrule\@width\lst@maxwidth\@height\z@\@depth\z@
    \else
        \lst@ifdisplaystyle
            \par\penalty-50\vspace\lst@belowskip
        \fi
    \fi
    \ifx\lst@multicols\@empty\else
        \def\lst@next{\global\let\@checkend\@gobble
                      \endmulticols
                      \global\let\@checkend\lst@@checkend}
        \expandafter\lst@next
    \fi
    \ifx\lst@float\relax\else
        \expandafter\lst@endfloat
    \fi
    \endgroup}
\makeatother
\begin{document}

\begin{center}
\begin{varwidth}{\linewidth}
\tracingmacros2
\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}

相关内容