更改涉及宏的标签的引用文本,该宏的名称依赖于宏

更改涉及宏的标签的引用文本,该宏的名称依赖于宏

我想在下一页之前更改标签的参考文本。这可以通过多次定义标签来实现,但我想摆脱警告。
因为标签是在每页末尾写入.aux文件的,所以可以通过将命令作为参考文本并在页面结束之前更改命令来实现。(我使用自定义参考文本,其前言如下埃格尔检索隐藏标签的链接标题):

\documentclass{article}
\usepackage{etoolbox}
\usepackage{refcount}
\usepackage{hyperref}
\makeatletter
\newcommand{\customlabel}[2]{% custom reference text
  \csname phantomsection\endcsname
  \def\@currentlabel{%
    \bartodo{\unexpanded{#2}}%
  }%
  \label{#1}%
}
\protected\def\bartodo#1{#1}
\newcommand{\checklabel}[2]{% macro not used in this example, no need to read it
  \begingroup
  \let\bartodo\detokenize
  \begingroup\edef\x{\endgroup
    \noexpand\ifstrequal{\getrefnumber{#1}}{\detokenize{#2}}}%
  \x{\aftergroup\@firstoftwo}{\aftergroup\@secondoftwo}%
  \endgroup
}
\makeatother

\begin{document}

\def\mycommand{A}%
\customlabel{mylabel}{\mycommand}%
\getrefnumber{mylabel}
\def\mycommand{B}%
\getrefnumber{mylabel}

\end{document}

运行 2 次 LaTeX 后,它将返回B B所需的值。(我使用\def而不是 ,\(re)newcommand因为我最终会将其放在里面的某个地方,使用\global。)

现在说我想执行两次(实际上是 1000 次),并且标签名称和命令名称依赖于其他宏,比如计数器,以便可以分别编辑两个参考文本:

%preamble as before
\begin{document}
\newcounter{mycounter}

\expandafter\def\csname mycommand\themycounter\endcsname{A}%
\customlabel{mylabel\themycounter}{\csname mycommand\themycounter\endcsname}%
\getrefnumber{mylabel\themycounter}
\expandafter\def\csname mycommand\themycounter\endcsname{B}%
\getrefnumber{mylabel\themycounter}
%
\stepcounter{mycounter}%
% the same:
\expandafter\def\csname mycommand\themycounter\endcsname{C}%
\customlabel{mylabel\themycounter}{\csname mycommand\themycounter\endcsname}%
\getrefnumber{mylabel\themycounter}
\expandafter\def\csname mycommand\themycounter\endcsname{D}%
\getrefnumber{mylabel\themycounter}
\end{document}

D D D D正如我所期望的B B D D

发生的情况是,当将标签写入文件时.aux,将使用更新的值\themycounter,而不是定义标签时的值。

所以我想扩大第二个\themycounter而不\customlabel{mylabel\themycounter}{\csname mycommand\themycounter\endcsname}扩大\mycommand0(因为后者还不能改变)。

答案1

\themycounter因此我们在宏中修复标签定义时的数量\ctr,然后使用该数量(扩展)。

\begin{document}

\newcounter{mycounter}
\newcommand{\ccclabel}[1]{\customlabel{mylabel#1}{\csname mycommand#1\endcsname}}%

\expandafter\def\csname mycommand\themycounter\endcsname{A}%
\edef\ctr{\themycounter}\expandafter\ccclabel\expandafter{\ctr}
\getrefnumber{mylabel\themycounter}
\expandafter\def\csname mycommand\themycounter\endcsname{B}%
\getrefnumber{mylabel\themycounter}
%
\stepcounter{mycounter}%
% the same:
\expandafter\def\csname mycommand\themycounter\endcsname{C}%
\edef\ctr{\themycounter}\expandafter\ccclabel\expandafter{\ctr}
\getrefnumber{mylabel\themycounter}
\expandafter\def\csname mycommand\themycounter\endcsname{D}%
\getrefnumber{mylabel\themycounter}
\end{document}

相关内容