他のマクロ内で定義されたローカルコマンドのパッチ適用

他のマクロ内で定義されたローカルコマンドのパッチ適用

これはフォローアップの質問であり、ここでの(まだ)未回答の質問につながった主な原因です。\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}

関連情報