3

I am trying to create a new section that automatically updates the counter with relevant label.

newcommand-stepcounter sort of does what I am trying to do , but not quite.

When I use the code below, the counters on the sections headed "Eq" are updated as I'd like, but if I try to \label them then the section number is used rather than the counter on the new command.

How can I use the relevant counter when using label please.

\documentclass{report}    
\newcounter{mycounter}
\newcommand{\step}{\stepcounter{mycounter}\subsubsection*{Eq \themycounter}}   

\begin{document}

\section{}
\subsection{}
\step\label{eq:one}

\section{}
\subsection{}
\step

As seen in Eq~\ref{eq:one}

\end{document}

Which produces

enter image description here

3
  • I think that if you replace \stepcounter by \refstepcounter it'll work... Aug 13, 2018 at 19:50
  • @PhelypeOleinik ; that works thank you. If you would like to add it as an answer i will accept it.
    – user20650
    Aug 13, 2018 at 19:53
  • The answer, as you requested :) Aug 13, 2018 at 19:56

1 Answer 1

4

You just have to change \stepcounter to \refstepcounter.

\documentclass{report}
\newcounter{mycounter}
\newcommand{\step}{\refstepcounter{mycounter}\subsubsection*{Eq \themycounter}}

\begin{document}

\section{}
\subsection{}
\step\label{eq:one}

\section{}
\subsection{}
\step

As seen in Eq~\ref{eq:one}

\end{document}

enter image description here

\stepcounter just adds 1 to the counter but \refstepcounter makes the \@currentlabel be that counter:

\def\refstepcounter#1{\stepcounter{#1}%
    \protected@edef\@currentlabel
       {\csname p@#1\endcsname\csname the#1\endcsname}%
}

so when you are using \labels, \stepcounter alone isn't enough because LaTeX doesn't know that the counter is a label.

4
  • Dear Phelype; how could I tweak this to increment letters instead of numerics please. I thought something like \newcommand{\step}{\refstepcounter{mycounter} (\alph{\themycounter})} would work but with no joy. Thanks
    – user20650
    Mar 5, 2020 at 17:46
  • This seems to work \newcounter{mycounter}; \renewcommand{\themycounter}{(\alph{mycounter})}; \newcommand{\step}{\refstepcounter{mycounter} \themycounter}
    – user20650
    Mar 5, 2020 at 18:16
  • @user20650 Yes, if you want to change how a counter <counter> looks you redefine the command \the<counter>. Your first approach didn't work because the argument to \alph (and \roman and \arabic) are counter names (so <counter>, not \the<counter>). Mar 5, 2020 at 19:15
  • Great, thanks for the explanation. I just chucked a few things a it till one stuck -- very robust code.
    – user20650
    Mar 5, 2020 at 19:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .