问题
在评论中那里,我了解到
\refstepcounter
之前最新的\label
设置计数器\label
是否可以明确要求\label{}
命令引用给定的计数器?
我发现在两种情况下这可能有用:
- 有几个计数器,您想确定选择哪一个。
- 计数器的值已设置通过
\setcounter
。
代码和图片
\documentclass{article}
\begin{document}
\newcounter{counterA} \setcounter{counterA}{0}
\refstepcounter{counterA}
\label{First_Label}
I get: \ref{Second_Label}. I would like 99.
\bigskip
\setcounter{counterA}{99}
\label{Second_Label}
I get: \ref{First_Label}. I would like 1.
\end{document}
答案1
你可以做这样的事情:
\makeatletter
\newcommand*\labelcounter[2]{\begingroup
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
\label{#2}\endgroup}
\newcommand*\refsetcounter[2]{\setcounter{#1}{#2}%
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
}
\makeatother
行\protected@edef
取自 的定义\refstepcounter
。用法:
\labelcounter{equation}{eq:123}
完整示例:
\documentclass{article}
\makeatletter
\newcommand*\labelcounter[2]{\begingroup
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
\label{#2}\endgroup}
\newcommand*\refsetcounter[2]{\setcounter{#1}{#2}%
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
}
\makeatother
\begin{document}
\subsection{Bla}
\begin{equation}a+b\end{equation}
\subsection{Blabla}
\labelcounter{equation}{eq-test}
\label{sect-test}
Should be 0.2: \ref{sect-test}
\\
Should be 1: \ref{eq-test}
\end{document}
在您的示例中,带有的变体会\refsetcounter
更有用:
\documentclass{article}
\makeatletter
\newcommand*\labelcounter[2]{\begingroup
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
\label{#2}\endgroup}
\newcommand*\refsetcounter[2]{\setcounter{#1}{#2}%
\protected@edef\@currentlabel{\csname p@#1\endcsname\csname the#1\endcsname}%
}
\makeatother
\begin{document}
\newcounter{counterA} \setcounter{counterA}{0}
\refstepcounter{counterA}
\label{First_Label}
I get: \ref{Second_Label}. I would like 99.
\bigskip
\refsetcounter{counterA}{99}
\label{Second_Label}
I get: \ref{First_Label}. I would like 1.
\end{document}
答案2
\addtocounter{foo}{-1}\refstepcounter{foo}\label{mylabel}
将标签mylabel
与计数器的当前值关联起来foo
。