0

I'm using a custom counter which I increment every now and then :

\newcounter{MyCounter}[subsection]
\newcommand{\stepTheCounter}{%
    % do stuff, whatever
    \refstepcounter{MyCounter}
}

Then, if I use a \label{someLabel} somewhere, I would like to be able to have a custom command \theReference{someLabel}, so that if I have a line like Lorem ipsum dolor \theReference{someLabel} sit amet, it shows something like

Lorem ipsum dolor X.Y.Z (page W) sit amet

where X is the section number, Y is the subsection number, Z is the value gotten from \ref{someLabel}, and W is the value gotten from \pageref{someLabel}.

So the thing is : there is a \pageref command, but (supposedly ?) no \etionref nor \subsectionref commands. But I feel like it should be normal to be able to achieve this easily...

None of the threads opened on the TeXExchange helped me... Thanks for the kind replies !

1
  • the usual format is to define \theMyCounter as \thesubsection.\arabic{MyCounter} then \ref will give the full section.subsection.Mycounter value Jan 22, 2020 at 0:13

1 Answer 1

1

I propose two ways depending on what you want \theMyCounter to do.

First way

If you want \theMyCounter to print the plain counter number, you can use:

\documentclass{article}

\newcounter{MyCounter}
\labelformat{MyCounter}{\thesubsection.#1}

\newcommand{\stepTheCounter}{%
 % do stuff, whatever
 \refstepcounter{MyCounter}%
}
\newcommand*{\myRef}[1]{\ref{#1} (page~\pageref{#1})}

\begin{document}

\section{First section}
\subsection{A subsection}

Foo bar.\stepTheCounter\label{first}
\verb|\theMyCounter| yields \theMyCounter.
The second use of \verb|\stepTheCounter| is \myRef{second}.
\newpage

\section{Second section}
\subsection{A subsection}

Bla. \stepTheCounter\label{second}
\verb|\theMyCounter| yields \theMyCounter.
The first use of \verb|\stepTheCounter| is \myRef{first}.

\end{document}

enter image description here

...

enter image description here

Second way

If you prefer \theMyCounter to print something like 2.1.2 (assuming the \stepTheCounter call preceding the \label was in section 2, subsection 1), then simply replace the line:

\labelformat{MyCounter}{\thesubsection.#1}

with:

\renewcommand{\theMyCounter}{\thesubsection.\arabic{MyCounter}}

and the output will be as follows.

enter image description here

...

enter image description here

Of course, you'll probably want to call these inside a subsection (if you use \stepTheCounter inside a section but not inside a subsection, the subsection counter will be zero).

2
  • That's amazing, exactly what I needed, thank you so much ! Jan 22, 2020 at 13:53
  • Glad to help. :-)
    – frougon
    Jan 22, 2020 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.