I use this piece of code in the preamble, obtained from Environment that counts words inside:
\usepackage{xesearch}
\newcounter{words}
\newenvironment{assignment}{%
\setcounter{words}{0}
\SearchList!{wordcount}{\stepcounter{words}}
{a?,b?,c?,d?,e?,f?,g?,h?,i?,j?,k?,l?,m?,
n?,o?,p?,q?,r?,s?,t?,u?,v?,w?,x?,y?,z?}
\UndoBoundary{'}
\SearchOrder{p;}}{%
\StopSearching
\marginpar{\arabic{words} words}}
I use this in my main file that includes several chapters. If I include up to the end chapter 4 (33599 words) then the counting environment works fine. If I include the next chapter (~6K words) I get the TeX capacity exceeded
error. Having tested and excluded all other options it is definitely down to the assignment
environment reaching a buffer(?) limit at some point over 33.599K words. I am not sure how to create a MWE for this particular case without sharing my actual work which for obvious reasons I cannot do.
PUT 100k OF TEXT HERE
instead of the long text.\blindtext
also takes an optional repetition argument which could be made large enough to trigger the problem.