![如果已加载包标题,则无法修补“\caption”](https://linux22.com/image/438387/%E5%A6%82%E6%9E%9C%E5%B7%B2%E5%8A%A0%E8%BD%BD%E5%8C%85%E6%A0%87%E9%A2%98%EF%BC%8C%E5%88%99%E6%97%A0%E6%B3%95%E4%BF%AE%E8%A1%A5%E2%80%9C%5Ccaption%E2%80%9D.png)
我受到启发这个问题使章节名称出现在图表列表中。
caption
如果未加载该软件包,此解决方案非常有效。但是,如果subcaption
加载了此软件包(或),则我无法修补,\caption
并且\pretocmd
似乎etoolbox
不起作用。
可以修复这个问题吗?
以下是 MWE:
\documentclass{book}
\usepackage{etoolbox, mwe}
\usepackage{caption, subcaption}
\makeatletter
\newcommand{\thechaptername}{}
\newcounter{chapter@figure}
\newcounter{chapter@table}
\newif\ifinsideFigure
\newif\ifinsideTable
\AtBeginEnvironment{figure}{\insideFiguretrue}
\AtBeginEnvironment{table}{\insideTabletrue}
\renewcommand{\chaptermark}[1]{\markboth{#1}{}\renewcommand{\thechaptername}{#1}}
\pretocmd{\caption}{%
\ifnumequal{\value{chapter}}{\value{chapter@figure}}%
{}%
{\ifinsideFigure%
\addtocontents{lof}{\protect\numberline{\bfseries\thechapter\quad\thechaptername}}%
\setcounter{chapter@figure}{\value{chapter}}%
\fi}%
{}{}%
\ifnumequal{\value{chapter}}{\value{chapter@table}}%
{}%
{\ifinsideTable%
\addtocontents{lot}{\protect\numberline{\bfseries\thechapter\quad\thechaptername}}%
\setcounter{chapter@table}{\value{chapter}}%
\fi}%
{}{}%
}{}{\typeout{Fail}}
\makeatother
\begin{document}
\listoffigures
\listoftables
\chapter{Chapter one}
\begin{figure}
\includegraphics{example-image}
\caption{This is figure 1.}
\end{figure}
\begin{figure}
\includegraphics{example-image}
\caption{This is figure 2.}
\end{figure}
\chapter{Chapter two}
\begin{table}
A
\caption{This is a table.}
\end{table}
\chapter{Chapter three}
\begin{figure}
\includegraphics{example-image}
\caption{This is figure 3.}
\end{figure}
\end{document}
答案1
caption
\caption
在 处重新定义,因此之前\begin{document}
的任何修补都将被覆盖。使用来延迟修补有效。\caption
\begin{document}
\AtBeginDocument{\pretocmd...}
或者,您可以使用\AddToHook{cmd/caption/before}{\ifnumequal ...}
,它需要 latex2e 2021-06-01 或更新版本。