[Tex/LaTex] Should LaTeX counters always be modified globally

countersetoolboxgrouping

In this answer, egreg states that "LaTeX counters should always be modified globally". However, the etoolbox package provides the \defcounter macro which will assign a value to a previously initialized counter locally (but may be prefixed with \global). I have been using this macro e.g. to change the value of the secnumdepth counter inside a group:

\documentclass{article}

\usepackage{etoolbox}

\begin{document}

\section{bla}

\begingroup
\defcounter{secnumdepth}{-2}

\section{blubb}
\endgroup

\section{foo}

\end{document}

So: Is egreg's statement about always globally modifying counters correct? If so, why? If not, is the usage of \defcounter in my MWE still bad practice?

Best Answer

As always with (La)TeX: If you know what you are doing you are allowed to do it!

Some local counter changes make perfectly sense, like in the example in the question. However I wouldn't call secnumdepth a real counter. After all it is never incremented. Here simply a counter register was used to store an integer because there is no other suitable type. Real LaTeX counters for sectioning commands, lists or other stuff should normally be global, because they express a count which goes over the whole document and is not limited to local groups. If you are so far that you need a local counter for your code you normally already know about \newdimen and can define a TeX counter instead of a LaTeX one.

A good example IMHO of a local redefinition of an otherwise global counter is shown in my answer to Cross-referencing in multiple chapters. There I use {\value{chapter}=<value>\relax\thechapter} (which is kind of a dirty hack) so I can use the current \thechapter format but with a different chapter number as the current one.

PS: I usually code after the rule "Once global, always global!", except in special cases as explained above.

Related Question