使用tcolorbox时List of Listings标题与页码间距异常问题
解决List of Listings中标题与页码无间距的问题
问题原因
你手动通过\addcontentsline向List of Listings(lol)添加条目时,未借助listings或tocloft的条目格式机制,导致标题文本与页码直接拼接,没有预留间距。同时你的myColorFrame环境调用存在参数格式错误(颜色参数未用[]包裹)。
解决方案
方案一:用tocloft规范配置格式(推荐)
利用已加载的tocloft包统一定义List of Listings的条目样式,自动处理标题与页码的间距:
- 在导言区添加配置代码:
% 统一List of Listings的名称与样式 \renewcommand{\lstlistingname}{Listing} \renewcommand{\lstlistlistingname}{List of Listings} % 设置编号前缀、宽度,以及标题与页码的填充方式 \renewcommand{\cftlistingpresnum}{Code~} \renewcommand{\cftlistingnumwidth}{4em} % 调整编号区域宽度,避免挤压标题 \renewcommand{\cftlistingfillnum}{\cftdotfill{\cftlistingdotsep}} % 用省略号填充,替换为\hfill可实现无省略号的右对齐
- 修改
myColorFrame中的\addcontentsline,仅传递编号与标题:
\addcontentsline{lol}{listing}{\thelisting:~#2}
- 修正环境调用:颜色是可选参数,需用
[]包裹:
\begin{myColorFrame}[red]{Example listing} This is a simulated listing. \end{myColorFrame}
方案二:快速手动修复
如果不想调整整体格式,直接在\addcontentsline的标题末尾添加\protect\hfill,强制生成间距:
\addcontentsline{lol}{listing}{Code~\thelisting:~#2\protect\hfill}
完整修正代码(方案一)
\documentclass{article} \usepackage{tcolorbox} % Package for colored boxes \usepackage{listings} % Package for listings (we use our own commands for lists) \usepackage{tocloft} % Package for managing lists of contents % 配置List of Listings的条目样式 \renewcommand{\lstlistingname}{Listing} \renewcommand{\lstlistlistingname}{List of Listings} \renewcommand{\cftlistingpresnum}{Code~} \renewcommand{\cftlistingnumwidth}{4em} \renewcommand{\cftlistingfillnum}{\cftdotfill{\cftlistingdotsep}} % Definition of the myColorFrame environment \newcounter{listing} \newenvironment{myColorFrame}[2][blue]{% \refstepcounter{listing}% \addcontentsline{lol}{listing}{\thelisting:~#2}% Adds entry to the list of listings \begin{tcolorbox}[colframe=#1,title={Listing~\thelisting: #2}]% }{% \end{tcolorbox} } \begin{document} \section{Intro} \begin{myColorFrame}[red]{Example listing} This is a simulated listing. \end{myColorFrame} % Adding the list of listings \lstlistoflistings \end{document}
内容的提问来源于stack exchange,提问作者limies
相关产品推荐
相关产品推荐

