如何使用 etoolbox 自动将编号和未编号的章节添加到图表列表中

如何使用 etoolbox 自动将编号和未编号的章节添加到图表列表中

https://tex.stackexchange.com/a/52747/232319它们描述了如何仅当章节至少包含一个图时才在 LOF 中包含编号章节(带有编号和标题)。关键思想是使用 修补\chapter命令etoolbox

近期的等效描述https://tex.stackexchange.com/a/255684/232319xpatch

tex.stackexchange.com 中有许多问题涉及此任务。

但是,如何包含未编号的章节( \chapter* 命令)?即,etoolbox当章节未编号时,如何完成以下修补命令以向 LOF 添加内容行?

\documentclass{book}
\usepackage{etoolbox}  % or xpatch

\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

\mainmatter

\chapter{Introduction with no Figures}

\chapter{Test Chapter with Figures}

\begin{figure}
  \caption{caption text}
\end{figure}
\begin{figure}
  \caption{caption text}
\end{figure}

\chapter{Test Chapter with no Figures}

\chapter{Another Test Chapter with Figures}

\begin{figure}
  \caption{caption text}
\end{figure}
\begin{figure}
  \caption{caption text}
\end{figure}
\begin{figure}
  \caption{caption text}
\end{figure}
\begin{figure}
  \caption{caption text}
\end{figure}
\begin{figure}
  \caption{caption text}
\end{figure}

\chapter*{Test Unnumbered Chapter with Figures}
\addcontentsline{toc}{chapter}{Test Unnumbered Chapter with Figures}

\begin{figure}
  \caption{Unnumbered chapter fig1}
\end{figure}
\begin{figure}
  \caption{Unnumbered chapter fig2}
\end{figure}

\end{document}

请注意(正如预期的那样),最后一个编号章节在 LOF 中包含下一个未编号章节的图片,而正文中则不是这样。您甚至可以使用没有图片的最后一个编号章节进行测试,它仍然会在 LOF 中包含下一个未编号章节的图片。

相关内容