12

Question

In a comment there, I learnt that

The latest \refstepcounter before \label sets the counter for \label

Is it possible to explicitly ask a \label{} command to refer to a given counter?

I see two cases where this could be useful:

  1. there are several counters and you want to be sure which one is chosen.
  2. the value of the counter is set via \setcounter.

Code and picture

\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}

enter image description here

Colas
  • 6,772
  • 4
  • 46
  • 96
  • I think I understand the question, but can you provide a simple use case with expected output (along the lines of a MWE)? – Sean Allred Apr 14 '14 at 15:28

2 Answers2

6

You can do something like this:

\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

The line with \protected@edef is taken from the definition of \refstepcounter. Usage:

\labelcounter{equation}{eq:123}

Full example:

\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}

In your example, the variant with \refsetcounter would be more useful:

\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}
yo'
  • 51,322
6
\addtocounter{foo}{-1}\refstepcounter{foo}\label{mylabel}

will associate the label mylabel with the current value of the counter foo.

David Carlisle
  • 757,742