引用计数器但不增加

引用计数器但不增加

我正在尝试引用一个计数器而不增加它。我有

\newcounter{procstep}
\newcommand{\refproc}[1]{\addtocounter{procstep}{-1}\refstepcounter{procstep}\label{#1}}

这是正确的做法吗?我想知道是否有更简单的方法?我有点期待宏\refcounter

答案1

与 John Kormylo 的答案类似,但略短一些。(请参阅本文末尾的扩展版本)

\documentclass{article}

\newcounter{procstep}
\usepackage{hyperref}

\providecommand{\phantomsection}{}



\makeatletter
\newcommand{\statlabel}[1]{%
  \phantomsection
  \protected@edef\@currentlabel{\theprocstep}%
  \protected@edef\@currentlabelname{procstep}%
  \label{#1}%
}
\makeatother

\usepackage{blindtext}

\begin{document}

See \ref{first}

\blindtext[10]
\setcounter{procstep}{100} \fbox{Here is the label\statlabel{first}}



\end{document}

适用于任何计数器的扩展版本

\documentclass{article}

\newcounter{procstep}
\usepackage{xparse}
\usepackage{blindtext}
\usepackage{hyperref}

\providecommand{\phantomsection}{}

\makeatletter
\NewDocumentCommand{\statlabel}{omm}{%
  \phantomsection%
  \protected@edef\@currentlabel{\csname the#2\endcsname}%
  \IfValueT{#1}{%
    \protected@edef\@currentlabelname{#1}%
  }%
  \label{#3}%
}
\makeatother


\begin{document}

See \ref{first} or \nameref{first} or \ref{seclabel} and \nameref{seclabel} or \autoref{seclabel} 

\blindtext[10]

\setcounter{section}{17}% Just for fun
\statlabel[Some foo text]{section}{seclabel}


\setcounter{procstep}{100}\fbox{Here is the label\statlabel[Static Label to procstep]{procstep}{first}}

\end{document}

在此处输入图片描述

答案2

我不会称其为更简单,除非你抛弃 hyperref 选项。

\documentclass{article}
%\usepackage{hyperref}

\newcounter{procstep}

\makeatletter
\@ifpackageloaded{hyperref}%
    {\newcommand{\refproc}[1]{\protected@edef\@currentlabelname{procstep}%
    \Hy@MakeCurrentHrefAuto{procstep}%
    \Hy@raisedlink{\hyper@anchorstart{\@currentHref}\hyper@anchorend}%
    \protected@write\@auxout{}{\string\newlabel{#1}{{\theprocstep}{\thepage}%
      {\@currentlabelname}{\@currentHref}{}}}}}%
  {\newcommand{\refproc}[1]{\protected@write\@auxout{}{\string\newlabel{#1}{{\theprocstep}{\thepage}}}}}
\makeatother


\begin{document}
\ref{test}
\setcounter{procstep}{23}
\refproc{test}
\end{document}

相关内容