TransWikia.com

Advancing a pseudo-counter in an align environment

TeX - LaTeX Asked on April 14, 2021

I’m getting some strange results I don’t really understand with the following code:

documentclass{article}
usepackage{pgfmath}
usepackage{amsmath}
newcommandinitializecount{defaecnt{0}}
newcommandaenextify{%%
  pgfmathparse{int(aecnt+1)}%%
  xdefaecnt{pgfmathresult}%%
  typeout{>> aecnt}%%
}

begin{document}

initializecount
Current: aecnt
begin{align*}
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
end{align*}

end{document}

Resulting in the following

enter image description here

It’s as if each aenextify command is being expanded once when the align* environment is first parsed and then again as each line of the environment is expanded. What I would like to do is start the counter at zero and after each line of the align* environment, advance this counter.

I tried inserting a noexpand, but then the pseudo-counters are completely ignored or had no noticeable effect. (In this MWE, the noexpand itself just seems to be ignored.)

aecnt && aecntnoexpandaenextify

Please note that I’m not interested in actually using LaTeX’s native counters, this is just a MWE that illustrates my problem. If you can get this MWE to work or explain why it’s failing without resorting to using real counters, then I’ll be very appreciative.

One Answer

Some AMS environments such as align process the contents twice, once in a "measuring" phase and then "for real". You want to step the counter only once.

documentclass{article}
usepackage{amsmath}
makeatletter
newcommandinitializecount{defaecnt{0}}
newcommandaenextify{%%
unlessifmeasuring@%
  xdefaecnt{thenumexpraecnt+1}%%
  typeout{>> aecnt}%%
fi  
}
makeatother
begin{document}

initializecount
Current: aecnt
begin{align*}
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
  aecnt && aecntaenextify
end{align*}

end{document}

enter image description here

P.S. You do not need pgf to increase the number, but the code of course also works with pgf.

Correct answer by user238301 on April 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP