Wednesday, June 25, 2008

Emacs word counting and tab completion

I've been doing a lot of work that's required me to keep an eye on word counts recently, so I've needed a decent word count function in Emacs. The easiest way to implement this was to use the wc command from CNU coreutils.

(defun word-count nil "Count words in buffer" (interactive)
  (let ((start (if mark-active (point) (point-min)))
        (end (if mark-active (mark) (point-max))))
    (shell-command-on-region start end "wc -w")))

If the the mark is active, it counts the number of words marked, otherwise counts the entire buffer. I have this bound to C-c C-w.

I also extended tab completion with dabbrev-expand to all file buffers, so I can use it in MATLAB, Bash, Python, etc. This was inspired by doing lots of MATLAB programming recently at my newly started summer job at Cambridge Silicon Radio.

(defun indent-or-complete ()
  "Complete if point is at end of a word, otherwise indent line."
  (if (looking-at "\\>")
      (dabbrev-expand nil)
(add-hook 'find-file-hook
          (function (lambda ()
                      (local-set-key (kbd "<tab>") 'indent-or-complete))))

1 comment:

OMouse said...

Your word-count function really shouldn't rely on a non-cross-platform tool. Emacs comes with a handy function called "how-many".

That's what I used for this snippet:

It word-counts the entire buffer, but you can easily modify it to only word-count a marked region.