27

How can I create the environment that could count words inside itself? More specifically, I want to write an enviroment called "assignment" such that the code

\begin{assignment}
Some words here.
\end{assignment}

will result in "Some words here." in the text and, say, "3 words" in a margin paragraph.

I tried searching for that, but found only (external) tools to count words in the entire document, while I need to do this with LaTeX code and for a single environment (possibly repeated several times in a document).

2

2 Answers 2

22

How about counting white spaces? This seems easier to implement.

Here is a simple implement. You can improve it to deal with more complex texts.

\documentclass{article}
\begingroup
\lccode`\~=`\ %
\lowercase{%
  \gdef\assignment{\setcounter{word}{0}%
    \catcode`~=\active
    \def~{\space\stepcounter{word}}}}%
\endgroup
\newcounter{word}
\def\endassignment{\stepcounter{word}%
  \marginpar{\arabic{word} words}}
\begin{document}

\begin{assignment}
Here are some words.
\end{assignment}

\end{document}
0
12

Here's an environment that counts word inside. It uses the xesearch package, so it requires XeLaTeX.

Searching is kept local to the environment, that's why it's defined inside.

\documentclass{article}
\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}}
\begin{document}
\begin{assignment}
Here are a few words for a word count demonstration.
\end{assignment}
\end{document}

word count example

3
  • I have been using this environment without problem until suddenly getting a Tex capacity exceeded, sorry [save size=50000]. I think it might be related to the fact that every page is generating an Underfull \vbox (badness 10000) has occurred while \output is active error.
    – DGarside
    Feb 22, 2013 at 10:36
  • 1
    This environment doesn't seem to work with the version of XeLaTeX packaged in TeXLive 2016. Can anyone update it for the recent changes? Feb 7, 2017 at 3:48
  • tex.stackexchange.com/questions/324151/… contains the relevant fix for current XeLaTeX. Mar 22, 2017 at 22:56

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.