Skip to content

Counting words in Emacs

It’s long hassled me that Emacs doesn’t support word count by default. This morning I got tired of using wc to count words and did a little search via Google. Right at the top of the list is DJ Delorie’s “Programming in Emacs Lisp”. This page teaches how to create this function, with a bug-free complete code chunk for use in your ~/.emacs file:

;;; First version; has bugs!
(defun count-words-region (beginning end)
  "Print number of words in the region.
Words are defined as at least one word-constituent
character followed by at least one character that
is not a word-constituent.  The buffer's syntax
table determines which characters these are."
  (interactive "r")
  (message "Counting words in region ... ")

;;; 1. Set up appropriate conditions.
  (save-excursion
    (goto-char beginning)
    (let ((count 0))

;;; 2. Run the while loop.
      (while (< (point) end)
        (re-search-forward "\\w+\\W*")
        (setq count (1+ count)))

;;; 3. Send a message to the user.
      (cond ((zerop count)
             (message
              "The region does NOT have any words."))
            ((= 1 count)
             (message
              "The region has 1 word."))
            (t
             (message
              "The region has %d words." count))))))

Do a quick byte-compile-file to make your ~/.emacs.elc file, restart Emacs, you are ready to count.