This is a card in Dave's Virtual Box of Cards.

chapterwords.rb

Created: 2024-01-21
Updated: 2024-03-30

Here’s a little Ruby script I made this morning to give me a word count for just the current day’s writing.

For this to work, you need at least one line in your document that starts with "Chapter". Everything from that line to the end of the document will be counted.

(For the 2023 NaNoWriMo (National Novel Writing Month), I got in the habit of starting each day’s writing with a new chapter, even if it didn’t make any sense at all.)

You can (and are encouraged to) change this to fit your own habits:

#!/usr/bin/ruby

if ARGV.length < 1
  puts "Usage: chapterwords.rb <filename>"
  puts ""
  puts "This finds the last line that starts with 'Chapter'"
  puts "and counts the words after that."
  exit 2
end

# Find last "Chapter" line
txt = File.read(ARGV[0])
last_chapt = txt.rindex(/^Chapter/)
if !last_chapt
  puts "Text did not contain even a single line that started"
  puts "with 'Chapter', so I can't do anything. Sorry. :-("
  exit 3
end

# Get last chapter text
chapt_txt = txt[last_chapt..]

# Print last chapter line ("Chapter xxx")
puts chapt_txt.lines.first

# Word count - split uses whitespace by default
puts "WORDS: #{chapt_txt.split.length}"

I put this in my own personal ~/bin/ directory, which is in my $PATH, so it is executable by name only.

Then I put it in Vim as a handy shortcut:

nnoremap <leader>wc :!chapterwords.rb %<CR>

Note that I changed my "leader" sequence to the comma character ','. So for me, typing ,wc gives me a "chapter" word count for the current document.

Back to ruby or writing