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

Some words here.

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 Answers 2


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.

\lccode`\~=`\ %
  \marginpar{\arabic{word} words}}

Here are some words.


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.

  \marginpar{\arabic{words} words}}
Here are a few words for a word count demonstration.

word count example

  • 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
    Commented 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? Commented Feb 7, 2017 at 3:48
  • tex.stackexchange.com/questions/324151/… contains the relevant fix for current XeLaTeX. Commented Mar 22, 2017 at 22:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .