Emacs Word Count


How Many?

A function that's missing from Emacs which is sometimes needed is "Word Count". If you have to submit an article and it needs to be a minimum or precise number of words, Emacs won't help you.

You could save the piece and run "wc" in unix or linux, but that's a pain. We need a function inside Emacs to carry out this task.

I found an Emacs Lisp function at Gnu's website:

;;; Final version: while

(defun count-words-region (beginning end)
"Print number of words in the region."
(interactive "r")
(message "Counting words in region ... ")

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

;;; 2. Run the while loop.
(while (and (< (point) end)
(re-search-forward "\\w+\\W*" end t))
(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))))))

;; Count the words in the entire document
(defun count-words-buffer ()
"Count all the words in the buffer"
(interactive)
(count-words-region (point-min) (point-max) )
)


(global-set-key "\C-c\C-c" 'count-words-buffer)

To bind the function, use

(global-set-key "keystroke" 'function)

Here we'll bind it to Ctrl-c Ctrl-c

(global-set-key "\C-c\C-c" 'count-words-buffer)

To launch the function in Emacs, use:

Ctrl-c Ctrl-c

. . .