我想将章节标题添加到图表列表中。@GonzaloMedina 之前回答过这个问题使用titletoc。但是,并非所有章节都已编号,因此我希望 lof 中的章节标题能够像在目录中一样显示。
以下是 Gonzalo Medina 的序言:
\documentclass{report}
\usepackage{chngcntr}
\counterwithout{figure}{chapter}
\usepackage{etoolbox} % or xpatch
\usepackage{titletoc}
\makeatletter
% initial definitions of the chapter info (name and number)
\def\thischaptertitle{}\def\thischapternumber{}
\newtoggle{noFigs}
\apptocmd{\@chapter}%
{\gdef\thischaptertitle{#1}\gdef\thischapternumber{\thechapter}%
\global\toggletrue{noFigs}}{}{}
% the figure environment does the job: the first time it is used after a \chapter command,
% it writes the information of the chapter to the LoF
\AtBeginDocument{%
\AtBeginEnvironment{figure}{%
\iftoggle{noFigs}{
\addtocontents{lof}{\protect\contentsline {chapter}%
{\protect\numberline {\thischapternumber} {\thischaptertitle}}{}{} }
\global\togglefalse{noFigs}
}{}
}%
}
\makeatother
并创建以下文档:
\begin{document}
\tableofcontents
\listoffigures
\setcounter{secnumdepth}{-1}
\chapter{Preface with a figure}
\setcounter{chapter}{0}
\setcounter{secnumdepth}{2}
\begin{figure}
\caption{caption text}
\end{figure}
\chapter{Test Chapter with Figures}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{figure}
\caption{caption text}
\end{figure}
\end{document}
产量
和
我的问题是
- 如何隐藏前言章节号的显示?
- 如何将其与
hyperref
包结合起来,让 lof 中的章节成为超链接?
答案1
该示例通过计数器控制章节编号secnumdepth
。它还可用于定义\thischapternumber
一个特殊值(空宏 = \@empty
),以判断是否应隐藏章节编号。中的代码将\addtocontents
检查\thischapternumber
是否应隐藏章节编号\numberline
。
的变化hyperref
很小。锚点在 中被记住\thischapterHref
并在 中使用\contentsline
:
\documentclass{report}
\usepackage{chngcntr}
\counterwithout{figure}{chapter}
\usepackage{etoolbox} % or xpatch
\usepackage{titletoc}
\makeatletter
% initial definitions of the chapter info (name and number)
\def\thischaptertitle{}\def\thischapternumber{}
\newtoggle{noFigs}
\apptocmd{\@chapter}{%
\gdef\thischaptertitle{#1}%
\ifnum\value{secnumdepth}>-1 %
\gdef\thischapternumber{\thechapter}%
\else
\global\let\thischapternumber\@empty
\fi
\global\let\thischapterHref\@currentHref % hyperref
\global\toggletrue{noFigs}%
}{}{}
% the figure environment does the job: the first time it is used after a
% \chapter command,
% it writes the information of the chapter to the LoF
\AtBeginDocument{%
\AtBeginEnvironment{figure}{%
\iftoggle{noFigs}{%
\addtocontents{lof}{%
\protect\contentsline{chapter}{%
\ifx\thischapternumber\@empty
\else
\protect\numberline{\thischapternumber}%
\fi
\thischaptertitle
}{}{%
\thischapterHref % hyperref
}%
}%
\global\togglefalse{noFigs}%
}{}%
}%
}
\makeatother
\usepackage[colorlinks]{hyperref}
\begin{document}
\tableofcontents
\listoffigures
\setcounter{secnumdepth}{-1}
\chapter{Preface with a figure}
\setcounter{chapter}{0}
\setcounter{secnumdepth}{2}
\begin{figure}
\caption{caption text}
\end{figure}
\chapter{Test Chapter with Figures}
\begin{figure}
\caption{caption text}
\end{figure}
\begin{figure}
\caption{caption text}
\end{figure}
\end{document}