我想\newcommand
在align
环境中使用。此外,我需要在对齐环境之外使用新定义的命令。虽然这对于的情况很容易,\def
因为我可以简单地在其前面加上前缀\global
。此解决方案不适用于\newcommand
。但是,有解决方案提出这里,这里, 和这里所有这些解决方案在equation
环境中都能很好地运行。但是,它们在align
环境中会失败。在下面的 MWE 中,我注释掉了失败的命令。
\documentclass{article}
\usepackage{amsmath}
% taken from https://tex.stackexchange.com/a/51750/22187
\usepackage{etoolbox}
\makeatletter
\def\gnewcommand{\g@star@or@long\gnew@command}
\def\grenewcommand{\g@star@or@long\grenew@command}
\def\g@star@or@long#1{\@ifstar{\let\l@ngrel@x\global#1}{\def\l@ngrel@x{\long\global}#1}}
\def\gnew@command#1{\@testopt{\@gnewcommand#1}0}
\def\@gnewcommand#1[#2]{\kernel@ifnextchar [{\@gxargdef#1[#2]}{\@argdef#1[#2]}}
\let\@gxargdef\@xargdef
\patchcmd{\@gxargdef}{\def}{\gdef}{}{}
\let\grenew@command\renew@command
\patchcmd{\grenew@command}{\new@command}{\gnew@command}{}{}
\makeatother
% taken from https://tex.stackexchange.com/a/51751/22187
\makeatletter
\def\reset@l@texglobal{\let\l@texglobal\relax}
\reset@l@texglobal
\def\latexglobal{\let\l@texglobal\global}
\long\def\@yargd@f#1#2{%
\def\reserved@a##1#1##2##{%
\expandafter\def\expandafter#2\reserved@b##1#1%
}%
\afterassignment\reset@l@texglobal
\l@texglobal\l@ngrel@x\reserved@a 0##1##2##3##4##5##6##7##8##9###1%
}
\long\def\@xargdef#1[#2][#3]#4{%
\@ifdefinable#1{%
\l@texglobal\expandafter\def\expandafter#1\expandafter{%
\expandafter\@protected@testopt\expandafter#1\csname\string#1\endcsname{#3}%
}
\expandafter\@yargdef\csname\string#1\endcsname\tw@{#2}{#4}%
}%
}
\makeatother
% testing functions
\newcommand\GlobalDef[1]{
\global\expandafter\def\csname GlobalDef#1\endcsname{GlobalDef#1}
}
\newcommand\GlobaldefsNewcommand[1]{
\globaldefs=1
\expandafter\newcommand\csname GlobaldefsNewcommand#1\endcsname{GlobaldefsNewcommand#1}
\globaldefs=0
}
\newcommand\Gnewcommand[1]{
\expandafter\gnewcommand\csname Gnewcommand#1\endcsname{Gnewcommand#1}
}
\newcommand\LatexglobalNewcommand[1]{
\latexglobal\expandafter\newcommand\csname LatexglobalNewcommand#1\endcsname{LatexglobalNewcommand#1}
}
\begin{document}
\begin{equation}
\GlobalDef{Equation}
\GlobaldefsNewcommand{Equation}
\Gnewcommand{Equation}
\LatexglobalNewcommand{Equation}
\end{equation}
\begin{align}
\GlobalDef{Align}
% \GlobaldefsNewcommand{Align} % does not work
% \Gnewcommand{Align} % does not work
% \LatexglobalNewcommand{Align} % does not work
\end{align}
\GlobalDefEquation{} \GlobalDefAlign{}
\GlobaldefsNewcommandEquation{} % \GlobaldefsNewcommandAlign{}
\GnewcommandEquation{} % \GnewcommandAlign{}
\LatexglobalNewcommandEquation{} % \LatexglobalNewcommandAlign{}
\end{document}