polishing ruby by ryan davis

My Emacs Setup, pt 4: Hooks

Published 2013-06-21 @ 12:00

Tagged emacs

This is part of the My Emacs Setup series.

I have this innocent looking line in my .emacs.el:

1
(rwd-autohooks)

and I said I’d go into it later. Well… That little function call is this doozy:

1
2
3
4
5
6
7
8
9
10
11
12
;;;###autoload
(defun rwd-autohooks ()
  (interactive)
  (dolist (path (directory-files (concat user-init-dir "hooks") t ".*el$"))
    (let* ((mode       (file-name-nondirectory (file-name-sans-extension path)))
           (hook-name  (intern (concat mode "-hook")))
           (defun-name (intern (concat "rwd-" mode "-hook")))
           (lisp       (read-file-to-string path)))
      (eval (read (concat "(defun " (symbol-name defun-name) " () " lisp ")")))
      (and (functionp defun-name)
           (remove-hook hook-name defun-name))
      (add-hook hook-name defun-name))))

You don’t need to understand it. The gist is that there is an (eval (read ...)) followed by (add-hook ...). What’s that do? It allows me to organize all of my hooks in a way that makes sense for me and my VCS. Instead of having a big file with a bunch of unrelated stuff across it, I get to organize everything like so:

elisp/hooks:

  after-init.el           after-save.el  dired-mode.el     emacs-lisp-mode.el
  enh-ruby-mode.el        erc-mode.el    grep-setup.el     haml-mode.el
  inferior-scheme-mode.el io-mode.el     mediawiki-mode.el paredit-mode.el
  ruby-mode.el            scheme-mode.el shell-mode.el     ssh-mode.el
  text-mode.el

Where each file is just the code I need to execute when I open a file in that mode. For example, here’s ruby-mode.el:

1
2
3
4
5
6
7
8
9
10
(inf-ruby-setup-keybindings)

(define-key ruby-mode-map (kbd "C-c C-a") 'autotest-switch)
(define-key ruby-mode-map (kbd "C-c C-p") 'pastebin)
(define-key ruby-mode-map (kbd "C-c C-r") 'rcov-buffer)
(define-key ruby-mode-map (kbd "C-c C-b") 'ruby-run-buffer-clean)
(define-key ruby-mode-map (kbd "C-c C-t") 'ri-show-term-composite-at-point)

(imenu-add-menubar-index)
(flyspell-prog-mode)

There’s one place to look. No searching. No excess boiler-plate for each mode. All of that is handled by rwd-autohook.

This works great for me, but is this good for you? Not necessarily. But maybe it is something to think about on your next overhaul.