我想根据是否\captionof
用于figure
或来执行这个或那个命令table
。
因此我使用 patch\captionof
来etoolbox
查看float type
参数是否为类型table
或figure
使用字符串比较。但是,由于某些我不理解的原因,我的更改没有效果。
我究竟做错了什么?
以下是 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
}%
}