
這是後續問題,分別是導致此處(尚未)未回答的問題的主要原因:\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}