3

I have this code in LaTeX and I am dealing with some dynamic work with labels and references. This code works - first reference references to the first text and second to the second but I want to reset the contentCounter within each section.

\documentclass{article}
\usepackage{hyperref}

\newcounter{contentCounter}
\renewcommand{\thesection}{\arabic{section}}

\newcommand{\inserttext}{%
    \refstepcounter{contentCounter}
    \par This is inserted text widh ID \thesection.\thecontentCounter. \\
    \label{text:\thesection.\thecontentCounter}
}

\begin{document}

\setcounter{section}{1}
\inserttext

\setcounter{section}{2}
\inserttext

\newpage
\textbf{References}

\setcounter{section}{1}
\hyperref[text:\thesection.1]{first text}

\setcounter{section}{2}
\hyperref[text:\thesection.2]{second text}

\end{document}

I tried to reset the counter but second reference is not working. Where's the problem? Thank you.

\documentclass{article}
\usepackage{hyperref}

\newcounter{contentCounter}
\renewcommand{\thesection}{\arabic{section}}

\newcommand{\inserttext}{%
    \refstepcounter{contentCounter}
    \par This is inserted text with the ID \thesection.\thecontentCounter. \\
    \label{text:\thesection.\thecontentCounter}
}

\begin{document}

\setcounter{section}{1}
\inserttext

\setcounter{section}{2}
\setcounter{contentCounter}{0}
\inserttext

\newpage
\textbf{References}

\setcounter{section}{1}
\hyperref[text:\thesection.1]{first text}

\setcounter{section}{2}
\hyperref[text:\thesection.1]{second text}

\end{document}
4
  • 5
    To set a 'sub'-counter, the normal syntax is: \newcounter{countername}[supercounter] (where supercounter here probably should be section).
    – jon
    May 21, 2016 at 18:18
  • @jon: So simple solution! Thank you very much.
    – sssss
    May 21, 2016 at 19:09
  • @jon, can you convert your comment to answer?
    – Zarko
    May 21, 2016 at 19:26
  • 4
    \label{text:\thesection.\thecontentCounter} is very odd. do you just have this in the test file or are you really using labels based on the counter value? May 21, 2016 at 20:29

1 Answer 1

2

(If this is not a duplicate....)

All that is needed in this case is to use the optional argument to \newcounter:

\newcounter{contentCounter}[section]

Where the [section] indicates that contentCounter should be reset to zero with each use of \section.

Note that if you need to modify a counter initially defined without the optional argument (or, conversely, to modify a counter defined with the optional argument), you can use the chngcntr package and its commands: \counterwithin and \counterwithout. Both commands include a 'starred' variant, which suppresses redefinition of the related \the<counter> commands.

You must log in to answer this question.

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