TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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).

share|improve this question
My "obligatory latex3 answer"-sense is tingling. – Seamus Feb 1 '11 at 16:00
This is a soluion for ConTeXt, maybe it can be adapted to LaTeX, as well: Dynamically count and return number of words in a section – Marco Apr 11 '12 at 16:57
up vote 21 down vote accepted

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.

share|improve this answer
Thank you, it would suffice. – Dmitry Feb 1 '11 at 16:33

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

share|improve this answer
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 '13 at 10:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.