修补其他宏中定义的本地命令

修补其他宏中定义的本地命令

这是后续问题,分别是导致此处(尚未)解答的问题的主要原因:\xpatchcmd 在应用于未定义的命令时定义宏

我试图修补一些命令,比如\someothercommand,它在另一个宏中本地定义,比如,\somecommand在后面的宏之外,例如在前言中。

然而这失败了。补丁跳转到错误的分支。我怀疑,这与本地分组有某种联系。

可能发生这种情况的情况是,当人们想要修补隐藏在其他宏内部的宏定义时,比如在类或包文件中。

考虑一些坏的应该更改代码,而无需复制整个外部宏或编辑.cls.sty文件

是否可以修补此类本地定义的宏?

我简化了 MWE

\documentclass{article}
\usepackage{xcolor}
\usepackage{xpatch}

\newcommand{\somecommand}[1]{%
  \newcommand{\someothercommand}[1]{\textcolor{blue}{##1}}%
  % This works
  % \xpatchcmd{\someothercommand}{blue}{red}{\typeout{Success!}}{\typeout{Nobody expects the Spanish Inquisition!!!!}}
  Inside usage: \someothercommand{#1}%
}

% Patching fails 
\xpatchcmd{\someothercommand}{blue}{red}{\typeout{Success!}}{\typeout{Nobody expects the Spanish Inquisition!!!!}}


\begin{document}
\somecommand{Outer command}

Outside usage: \someothercommand{Inside} but should be \textcolor{red}{Inside}
\end{document}

在此处输入图片描述

答案1

我会寻找一个合适的地方\somecommand放置钩子:

\documentclass{article}
\usepackage{xcolor}
\usepackage{xpatch}

\newcommand{\somecommand}[1]{%
  \def\someothercommand##1{\textcolor{blue}{##1}}%
  Inside usage: \someothercommand{#1}%
}


\xpatchcmd{\somecommand}{Inside usage:}{Inside usage: \myspecialsetup}{\typeout{Success!}}{\typeout{Nobody expects the Spanish Inquisition!!!!}}

\newcommand\myspecialsetup{\renewcommand\someothercommand[1]{\textcolor{red}{##1}}}

\begin{document}
\somecommand{Outer command}
\end{document}

答案2

您只能修补已定义的命令,因此\somecommand这里:

\documentclass{article}
\usepackage{xcolor}
\usepackage{xpatch}

\newcommand{\somecommand}[1]{%
  \newcommand{\someothercommand}[1]{\textcolor{blue}{##1}}%
  % This works
  % \xpatchcmd{\someothercommand}{blue}{red}{\typeout{Success!}}{\typeout{Nobody expects the Spanish Inquisition!!!!}}
  Inside usage: \someothercommand{#1}%
}

% Patching works 
\xpatchcmd{\somecommand}{blue}{red}{\typeout{Success!}}{\typeout{Nobody expects the Spanish Inquisition!!!!}}


\begin{document}
\somecommand{Outer command}

Outside usage: \someothercommand{Inside} but should be \textcolor{red}{Inside}
\end{document}

相关内容