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."
  (interactive)
  (if (looking-at "\\>")
      (dabbrev-expand nil)
    (indent-for-tab-command)))
(add-hook 'find-file-hook
          (function (lambda ()
                      (local-set-key (kbd "<tab>") 'indent-or-complete))))