![在 tcolorbox 內的標題和 lstlisting 之間加入水平線](https://rvso.com/image/305787/%E5%9C%A8%20tcolorbox%20%E5%85%A7%E7%9A%84%E6%A8%99%E9%A1%8C%E5%92%8C%20lstlisting%20%E4%B9%8B%E9%96%93%E5%8A%A0%E5%85%A5%E6%B0%B4%E5%B9%B3%E7%B7%9A.png)
我有一本書的範例清單。
我想要一條水平線,規定標題和清單之間 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 first
為overlay 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=1mm
tcolorbox 和[yshift=-3em]
繪製水平線的選項。如果您決定更改 tcolorbox 的格式(頂線、邊框寬度、內邊距等),您還必須擺弄後一個選項以及 和shorten >=1.4pt
選項。shorten <=1.4pt
我冒昧地breakable
向 tcolorbox 添加了該選項,以允許它分成幾頁。
輸出: