I am new to TeX
and here is my attempt to (ab)use mfirstuc
to define an environment that counts the words. I am looking for suggestions on how to improve the implementation.
\documentclass{article}
\usepackage{mfirstuc}
\newcounter{wordcount}
%Make sure we don't accidentally overwrite things with \def and \let
\newcommand\cwaux\relax
\newcommand\oldgmfu\relax
\newcommand\temppar\relax
%
\newtoks\temppar
\def\cwaux#1\par{\capitalisewords{#1}\par}
\newcommand*\myglsmakefirstuc[1]{\stepcounter{wordcount}#1}
\newenvironment{countwords}{%
\setcounter{wordcount}{0}\let\oldgmfu\glsmakefirstuc\let\glsmakefirstuc\myglsmakefirstuc\temppar\everypar\everypar{\cwaux}%
}{%
\everypar\temppar\let\glsmakefirstuc\oldgmfu Word count:\arabic{wordcount}%
}
\begin{document}
\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}
\begin{countwords}
One paragraph.
Another paragraph which is longer.
\end{countwords}
\begin{countwords}
The third paragraph.
I am glad to see this works.
\end{countwords}
\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}
\end{document}