@namedef 和数学模式

@namedef 和数学模式

我正在尝试做一些简单的事情:我希望能够通过标签存储和检索文本和方程式。具体来说,我想要类似

\labelput{<label>}{<text>}  % sets the label. Associates text to label. 
\labelget{<label>}    % replaces by the text associated to label. 

在以下 MWE 中,定义在文本模式下工作正常。但在数学模式下却不起作用。

\documentclass{article}

\makeatletter
\newcommand\labelput[2]{%
  \label{#1}%
  \@namedef{label@store@content@#1}{#2}%
  #2}
\newcommand\labelenvput[3]{%
  \@namedef{label@store@content@#2}{#3}%
  \begin{#1}%
  \label{#2}%
  #3%
  \end{#1}}
\newcommand\labelget[1]{\@nameuse{label@store@content@#1}}
\makeatother

\begin{document}

Test this first in \labelput{test1}{text mode}.

Does \labelget{test1} work?  % yes, it does

Test this again in math mode.

\begin{equation}\labelput{eq1}{e = mc^2}
\end{equation}

Now let us try to retrieve equation \ref{eq1} with
$\labelget{eq1}$   % the \ref works, but the \labelget fails silently


But the following works 
\labelenvput{equation}{eq2}{e = mc^3}

Retrieve
\[ \labelget{eq2} \]
\end{document}

所以我的问题是

  1. 如何\@namedef在数学模式下正确使用?我是否应该使用其他命令?
  2. 我是不是想重新发明轮子?

答案1

您的\@namedef是在组内发出的,因此控制序列在组末尾消失:每个环境都形成一个组。\@namedef以 为前缀\global

\documentclass{article}

\makeatletter
\newcommand\labelput[2]{%
  \label{#1}%
  \global\@namedef{label@store@content@#1}{#2}%
  #2}
\newcommand\labelenvput[3]{%
  \global\@namedef{label@store@content@#2}{#3}%
  \begin{#1}%
  \label{#2}%
  #3%
  \end{#1}}
\newcommand\labelget[1]{\@nameuse{label@store@content@#1}}
\makeatother

\begin{document}

Test this first in \labelput{test1}{text mode}.

Does \labelget{test1} work?  % yes, it does

Test this again in math mode.

\begin{equation}\labelput{eq1}{e = mc^2}
\end{equation}

Now let us try to retrieve equation \ref{eq1} with
$\labelget{eq1}$   % the \ref works, but the \labelget fails silently


But the following works 
\labelenvput{equation}{eq2}{e = mc^3}

Retrieve
\[ \labelget{eq2} \]
\end{document}

在此处输入图片描述

相关内容