在 tcolorbox 內的標題和 lstlisting 之間加入水平線

在 tcolorbox 內的標題和 lstlisting 之間加入水平線

我有一本書的範例清單。

在此輸入影像描述

我想要一條水平線,規定標題和清單之間 tcolorbox 的寬度。

用於生成它的程式碼:

\documentclass[letterpaper,oneside,12pt]{book}
\usepackage{listings}
\usepackage[most]{tcolorbox}
\usepackage{caption}
\usepackage{xcolor}

\definecolor{shadecolor}{gray}{0.95}
\definecolor{captionbox}{cmyk}{0.43, 0.35, 0.35,0.01}

\tcbset{colback=captionbox!5!white,colframe=captionbox!75!black}

\BeforeBeginEnvironment{lstlisting}{\begin{tcolorbox}[toprule=3mm]\vskip-.5\baselineskip}
\AfterEndEnvironment{lstlisting}{\end{tcolorbox}}

\DeclareCaptionFormat{listing}{\parbox{\textwidth}{#1#2#3}}

\captionsetup[lstlisting]{format=listing,skip=10pt}

\lstset{numbers=none}

\begin{document}

\begin{lstlisting}[caption=Sample code block]
This is a code block
\end{lstlisting}

\end{document}

我唯一的限制是我需要使用清單包和 lstlisting,因為 Pandoc 需要使用清單包和 lstlisting。我很高興替換其他任何內容,以產生與標題和清單周圍的框相同的效果,並在標題和清單之間使用規則以及類似的風格感覺。

答案1

更新:更改overlay firstoverlay unbroken and first以使該行也出現在不間斷的框中。我的錯。

太糟糕了,你不能使用tcblistings,它似乎是專門為此目的而製作的並且在內部使用listings(我已閱讀但未驗證這一點)。

儘管我不喜歡“特定”解決方案(即需要手動擺弄的解決方案),但我仍然向您推薦這個,因為它“有效”:

\documentclass[letterpaper,oneside,12pt]{book}

\usepackage{xcolor}

\usepackage{listings}
\usepackage{tcolorbox}
  \tcbuselibrary{breakable}
  \tcbuselibrary{skins}
\usepackage{caption}

\usepackage{tikz}

\usepackage{lipsum}

\definecolor{shadecolor}{gray}{0.95}
\definecolor{captionbox}{cmyk}{0.43, 0.35, 0.35,0.01}

\tcbset{%
    colback=captionbox!5!white,%
    colframe=captionbox!75!black,%
    top=1mm,%   %% Used to manually align the caption with the horizontal line
    %
    %% Create a new "style" for your titled listings tcolorbox
    mylistingwithtitle/.style = {%
        breakable,%
        %% Use tcolorbox's internal tikz object name (frame) to draw a horizontal line
        overlay unbroken and first={\draw[shorten >=1.4pt, shorten <=1.4pt] ([yshift=-3em]frame.north west) -- ([yshift=-3em]frame.north east);}%
    }%
}

\BeforeBeginEnvironment{lstlisting}{%
    \begin{tcolorbox}[enhanced, toprule=3mm, mylistingwithtitle]%
    \vskip-.5\baselineskip%
}

\AfterEndEnvironment{lstlisting}{\end{tcolorbox}}

\DeclareCaptionFormat{listing}{\parbox{\textwidth}{#1#2#3}}
\captionsetup[lstlisting]{format=listing,skip=15pt}


\begin{document}

%% This following line is only useful to execute \lipsum[1-4] inside the listing
\lstset{numbers=none, escapeinside={(*}{*)}}

\begin{lstlisting}[caption=Sample code block]
  This is a code block

  (*\lipsum[1-4]*)
\end{lstlisting}

\end{document}

如果變更標題格式,則需要手動調整垂直間距,即top=1mmtcolorbox 和[yshift=-3em]繪製水平線的選項。如果您決定更改 tcolorbox 的格式(頂線、邊框寬度、內邊距等),您還必須擺弄後一個選項以及 和shorten >=1.4pt選項。shorten <=1.4pt

我冒昧地breakable向 tcolorbox 添加了該選項,以允許它分成幾頁。

輸出:

上述程式碼產生的輸出

相關內容