Emacsで語数を数える

Emacsには、行数を数えるcount-lines-regionはあるが、単語数を数える機能は用意されていない。

調べると、"An Introduction to Programming in Emacs Lisp"でサンプルとして、count-words-regionという関数が見つかった。

http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/count-words-region.html

これは1語ごとに再帰呼び出しを使っており、ちょっと語数が多くなると、max-lisp-eval-depthの制限にひっかかってしまう。設定を変えるのもひとつのテだが、再帰を使わないで適当に書き直してみた(元のcount-words-regionを変更せずに使っているため、recursiveという名前が残っているが)。

(defun recursive-count-words (region-end)
  (let ((count 0))
    (while (and (< (point) region-end)
                (re-search-forward "\\w+\\W*" region-end t))
      (setq count (+ count 1))
      )
    count
    )
  )

(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 ... ")
  (save-excursion
    (goto-char beginning)
    (let ((count (recursive-count-words end)))
      (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))))))