2008-12-10

hooks

When customizing emacs, often you might want to do something when some event occurs. For example, in the automatic timestamps entry, we used
(add-hook 'write-file-hooks 'time-stamp) ; update when saving
to automatically update the file timestamp whenever we save the file.

The mechanism (as the example suggests) is called a hook: you can add a 'hook-function' for some event, and it will be called if the event takes place. This turns out to be very useful. It is a very common way to customize emacs when some specific mode (there is also an entry about modes) is activated. For example, I like to have some specific settings when I am using text-mode, which is the mode for normal text files, and can add the following to .emacs:

(defun djcb-text-mode-hook ()
  (set-fill-column 79)                    ; lines are 79 chars long ...         
  (auto-fill-mode t)                      ; ... and wrapped around automagically
  (set-input-method "latin-1-prefix")     ; make " + e => ë etc.
and
(add-hook 'text-mode-hook 'djcb-text-mode-hook)
Note, in the example we define a new function djcb-text-mode-hook; however, you can also define the function in-line in add-hook; such a nameless function is called a lambda-function. Using a lambda-function, we could also write the above example as:
(add-hook 'text-mode-hook
       (lambda()
         (set-fill-column 79)                ; lines are 79 chars long ...         
         (auto-fill-mode t)                  ; ... and wrapped around automagically
         (set-input-method "latin-1-prefix"))) ; make " + e => ë etc.   
These things are equivalent; the only difference is that you could use djcb-text-mode-hook elsewhere as well, because we can refer to it by its name.

You can call add-hook multiple times for some event (hook); when the event occurs, the hook will be called in reverse order of adding them. It's best not to depend on that, as the emacs manual explains.

You should be able to find the hooks that some package provides from its documentation; just search for 'hook'...

No comments: