![在调用时如何强制执行 \refstepcounter 的评估?](https://linux22.com/image/425583/%E5%9C%A8%E8%B0%83%E7%94%A8%E6%97%B6%E5%A6%82%E4%BD%95%E5%BC%BA%E5%88%B6%E6%89%A7%E8%A1%8C%20%5Crefstepcounter%20%E7%9A%84%E8%AF%84%E4%BC%B0%EF%BC%9F.png)
\themycounter
我对评估太晚有一个问题:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\newcounter{mycounter}
\newcommand{\defineXX}[3]{%
\refstepcounter{mycounter}
\expandafter\def\csname#1@id\endcsname{FSR \themycounter}
\expandafter\def\csname#1@definition\endcsname{#2}
\expandafter\def\csname#1@misc\endcsname{#3}
}
\newcommand{\printXX}[2]{%
\hypertarget{#1}{%
\subsection{\csname#1@id\endcsname}\label{#1}}
\csname#1@definition\endcsname
Test: \csname#1@misc\endcsname
#2
}
\begin{document}
\defineXX{test-1}{Definition 1}{Bla bla}
\defineXX{test-2}{Definition 2}{Bla bla}
\printXX{test-1}{Additional remark 1}
\printXX{test-2}{Additional remark 2}
\end{document}
产量
但我想FSR 1
看到FSR 2
答案1
您需要先扩展,\themycounter
然后再存储。以下是使用古老\begingroup\edef\x{\endgroup...}\x
扩展技术的一种方法:
\documentclass{article}
\usepackage{hyperref}
\newcounter{mycounter}
\makeatletter
\newcommand{\defineXX}[3]{%
\refstepcounter{mycounter}%
\begingroup\edef\x{\endgroup\noexpand\@namedef{#1@id}{FSR \themycounter}}\x
\@namedef{#1@definition}{#2}
\@namedef{#1@misc}{#3}
}
\makeatother
\newcommand{\printXX}[2]{%
\hypertarget{#1}{%
\subsection{\csname#1@id\endcsname}\label{#1}}
\csname#1@definition\endcsname
Test: \csname#1@misc\endcsname
#2
}
\begin{document}
\defineXX{test-1}{Definition 1}{Bla bla}
\defineXX{test-2}{Definition 2}{Bla bla}
\printXX{test-1}{Additional remark 1}
\printXX{test-2}{Additional remark 2}
\end{document}
\@namedef{<cmd name>}{<stuff>}
(来自内核)只是 的一个方便/更简短的替代方案\expandafter\def\csname <cmd name>\endcsname{<stuff>}
。
答案2
使用\edef
而不是\def
。另一方面,\refstepcounter
的作用只不过是\stepcounter
,因为它是在 执行的,\defineXX
而当您使用时\label
已经太晚了。
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\newcounter{mycounter}
\newcommand{\defineXX}[3]{%
\stepcounter{mycounter}%
\expandafter\edef\csname#1@id\endcsname{FSR \themycounter}%
\expandafter\def\csname#1@definition\endcsname{#2}%
\expandafter\def\csname#1@misc\endcsname{#3}%
}
\newcommand{\printXX}[2]{%
\hypertarget{#1}{%
\subsection{\csname#1@id\endcsname}\label{#1}}%
\csname#1@definition\endcsname
Test: \csname#1@misc\endcsname
#2
}
\begin{document}
\defineXX{test-1}{Definition 1}{Bla bla}
\defineXX{test-2}{Definition 2}{Bla bla}
\printXX{test-1}{Additional remark 1}
\printXX{test-2}{Additional remark 2}
\end{document}