使用 tocloft 修改目錄中章節編號的格式

使用 tocloft 修改目錄中章節編號的格式

我正在使用 tocloft 包來更改目錄的樣式。我想將章節編號排版為羅馬數字。但是,對於目錄,我將使用romanbars包來排版它們。

這個包提供了一個命令,它接受輸入(羅馬數字)並在底線和頂線上使用水平條對其進行格式化,我覺得這很賞心悅目。該命令採用單一參數。但是,該tocloft命令僅提供使用無參數命令(如 )更改(章節)編號格式的命令\bfseries

我的 MWE 是:

\documentclass{scrbook}

\renewcommand{\thechapter}{\Roman{chapter}}

\usepackage[usedvipsnames]{xcolor}
\usepackage{tocloft}
\usepackage{romanbar}

\renewcommand{\cftchappresnum}{\color{red}\Romanbar}

\usepackage{lipsum}

\begin{document}

\tableofcontents

\chapter{First Chapter}
\lipsum[2]

\chapter{Second Chapter}
\lipsum[2]

\chapter{Third Chapter}
\lipsum[2]

\end{document}

其產生:

例子

如您所見,每個羅馬數字的第一個字母都使用該命令正確格式化,而任何後續字母都使用正常字體格式化。

是否可以以\Romanbar某種方式包裝命令,以便它讀取後面的整個數字?或以其他方式配置tocloft以實現所需的格式?

答案1

一個有點hacky的解決方案:

\documentclass{scrbook}

\renewcommand{\thechapter}{\Roman{chapter}}

\usepackage[usedvipsnames]{xcolor}
\usepackage{tocloft}
\usepackage{romanbar}

\newsavebox{\tocnr}
\renewcommand{\cftchappresnum}{\color{red}\begin{lrbox}{\tocnr}}
\renewcommand{\cftchapaftersnum}{\end{lrbox}\expandafter\Romanbar\expandafter{\usebox{\tocnr}}\relax}

\usepackage{lipsum}

\begin{document}

\tableofcontents

\chapter{First Chapter}
\lipsum[2]

\chapter{Second Chapter}
\lipsum[2]

\chapter{Third Chapter}
\lipsum[2]

\end{document}

在此輸入影像描述

答案2

你可以修補\addchaptertocentry

\documentclass{scrbook}

\renewcommand{\thechapter}{\Roman{chapter}}

\usepackage[usedvipsnames]{xcolor}
\usepackage{romanbar}
\RedeclareSectionCommand[
  tocentrynumberformat=\def\autodot{}\textcolor{red}
]{chapter}

\usepackage{xpatch}
\xpatchcmd{\addchaptertocentry}
  {\addtocentrydefault{chapter}{#1}{#2}}
  {\ifstr{#1}{}{\addtocentrydefault{chapter}{#1}{#2}}
    {\addtocentrydefault{chapter}{\protect\Romanbar{#1}}{#2}}%
  }{}{\PatchFailed}

\usepackage{lipsum}

\begin{document}
\tableofcontents

\chapter{First Chapter}
\lipsum[2]
\chapter{Second Chapter}
\lipsum[2]
\chapter{Third Chapter}
\lipsum[2]
\end{document}

在此輸入影像描述

請注意,我使用了 KOMA-Script 指令\RedeclareSectionCommand來更改目錄中章節編號的顏色。tocloft不建議將套件與 KOMA-Script 類別一起使用。但如果您確實想使用軟體包,tocloft請將軟體包xpatch和補丁添加\addchaptertocentry到您的 MWE 中。

相關內容