0

I would like to execute a macro whenever a specific counter changes value. For example:

\newcommand{\process}[1]{do something with argument}
% ??? (What should I write here?)
\stepcounter{somecounter} % --> This should execute \process{\value{somecounter}}
                          %     after increasing the value here.

Ideally, this would happen not just when \stepcounter is used, but if somecounter is set in any way, e.g. via \setcounter, or if another counter causes it to reset.

Is there a supported way of doing this, or is the only option to hack some internal command? In the first case, what is it, or in the second case, what is the basic internal command that is called every time a counter's value is set?

  • 2
    What is the purpose of this? maybe there is a better way... – harryparp Jun 19 at 15:00
  • I would like to have a command (\mycommand) whose behaviour is dependent on a particular value (\myval) reflecting where in the document it is called. This value should be automatically updated whenever, say, a new chapter starts, but should also be able to be set manually, so it is not enough to simply refer to \value{chapter} in \mycommand. – Taederias Jun 19 at 15:18
0

I think patching chapter to increase your counter is an easier approach:

\documentclass{report}
\usepackage{xpatch}

\newcounter{myval}

\makeatletter
\xpatchcmd{\@chapter}% <cmd>
  {\refstepcounter{chapter}}% <search>
  {\refstepcounter{chapter}\addtocounter{myval}{1}}% <replace>
  {}{}% <success><failure>
\makeatother
\begin{document}

\themyval

\chapter{First chapter}

\themyval

\chapter{First chapter}

\themyval

\addtocounter{myval}{10}

\themyval

\chapter{First chapter}

\themyval


\end{document}

(which command to patch may depend on the documentclass)

  • Now you just broke references to chapters. You probably do not want refstep on myval – daleif Jun 19 at 17:40
  • @daleif Repaired. Thanks for commenting! – harryparp Jun 20 at 14:11
  • Just use stepcounter, just not refstepcounter in this case – daleif Jun 20 at 14:15

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.