4

Is there any way to include the number of words in a ConTeXt document excluding table of contents, other listings, etc.? I found the spellchecker feature that offers word counts but it includes the listings as well.

1
  • A workaround would be to comment your lists. You'll have your word count.
    – sztruks
    Oct 27, 2017 at 10:48

2 Answers 2

5

You can simply disable the state of spell checker to not count the words in ToC etc. Here is an example illustrating this:

\define\enablewordcount
    {\setupspellchecking[state=start,method=2]
     \ctxlua{languages.words.threshold=1}}

\define\disablewordcount
    {\setupspellchecking[state=stop]}

\define\showwordcount
  {\ctxlua{
    local data = table.load(file.addsuffix(tex.jobname,"words"))
    context(data and data.total or "nothing")
  }}

\starttext

\completecontent

\enablewordcount

\dorecurse{10}
  {\expanded{\startchapter[title=Chapter \recurselevel]}
    \dorecurse{4}
     {\expanded{\startsection[title=Section \recurselevel]}
       \input ward
     \stopsection}
   \stopchapter}

This document has \showwordcount\ words.

\stoptext

Note that you need two runs to get the right word count. Since the word count is stored in a separate file (and not the .tuc file), you may need to manually run context one more time.

3
  • Our answers are very similar. Should I delete mine? Oct 29, 2017 at 3:05
  • @HenriMenke No, don't! There is extra info in and I find your answer easier to understand for beginners.
    – DP.
    Oct 29, 2017 at 10:33
  • @HenriMenke: I agree with DP.
    – Aditya
    Oct 29, 2017 at 17:16
6

Just guard the lists in your document with

\setupspellchecking[state=stop]
% the list here
\setupspellchecking[state=start]

This way the spellchecker will inhibit its work for the list. The overall word count is not reset by \setupspellchecking[state=stop].

\setupspellchecking[state=start,method=2]
\ctxlua{languages.words.threshold=1}

\starttext

\setupspellchecking[state=stop]
\completecontent
\setupspellchecking[state=start]

\startsection[title=Knuth]
  \input knuth
\stopsection

\startsection[title=Ward]
  \input ward
\stopsection

\startsection[title=Zapf]
  \input zapf
\stopsection

\startluacode
local report_words = logs.reporter("word count")
local wordfile = "\jobname.words"
if file.is_readable(wordfile) then
    local data = dofile(wordfile)
    report_words("Total words: " .. data.total)
end
\stopluacode

\stoptext

The log reports

word count      > Total words: 281

When I comment out the list guards it shows

word count      > Total words: 285

You must log in to answer this question.

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