修补 \captionof 失败

修补 \captionof 失败

我想根据是否\captionof用于figure或来执行这个或那个命令table

因此我使用 patch\captionofetoolbox查看float type参数是否为类型tablefigure使用字符串比较。但是,由于某些我不理解的原因,我的更改没有效果。

我究竟做错了什么?

以下是 MWE:

\documentclass{article}
\usepackage{caption,etoolbox}
\newif\iffigure
\newif\iftable

\AtBeginDocument{
    \pretocmd{\captionof}{%
        \ifstrequal{#2}{table}{%
            \global\tabletrue%
            %... execute some code
        }
        {}%
        \ifstrequal{#2}{figure}{%
            \global\figuretrue%
            %... execute some code
        }
        {}%
    }
    {}
    {}
}

\begin{document}
{\captionof{figure}{A caption.}}

\iffigure Yes \else No \fi
\end{document}

答案1

正如 daleif 在评论中提到的那样,实际处理参数的宏\captionof不是\captionof它本身,而是\caption@of;已经做了一些前期工作来检查是否可能需要未编号(带星号)的标题。因此,您需要修补\caption@of

在此处输入图片描述

\documentclass{article}

\usepackage{caption,etoolbox}
\newif\iffigure

\makeatletter
\pretocmd{\caption@of}{%
  \ifstrequal{#2}{table}{%
    \global\tabletrue%
    %... execute some code
  }
  {}%
  \ifstrequal{#2}{figure}{%
    \global\figuretrue%
    %... execute some code
  }
  {}%
}
{}% Success
{}% Failure
\makeatother

\begin{document}

{\captionof{figure}{A caption.}}

\iffigure Yes \else No \fi

\end{document}

\captionof另一种方法是通过重新定义来捕获参数:

\AtBeginDocument{%
  \let\oldcaptionof\captionof% Store \captionof in \oldcaptionof
  \RenewDocumentCommand{\captionof}{s m m}{% Redefine \captionof
    \ifstrequal{#2}{table}{%
      \global\tabletrue%
      %... execute some code
    }
    {}%
    \ifstrequal{#2}{figure}{%
      \global\figuretrue%
      %... execute some code
    }
    {}%
    \IfBooleanTF{#1}% Check if star was used
      {\oldcaptionof*{#2}{#3}}% Starred \captionof
      {\oldcaptionof {#2}{#3}}% Unstarred \captionof
  }%
}

相关内容