GNU Emacs Manual. Node: Hooks

PREVEasy Customization UPVariables NEXTLocals

28.2.3: Hooks

A hook is a variable where you can store a function or functions to be called on a particular occasion by an existing program. Emacs provides a number of hooks for the sake of customization.

Most of the hooks in Emacs are normal hooks. These variables contain lists of functions to be called with no arguments. The reason most hooks are normal hooks is so that you can use them in a uniform way. Every variable in Emacs whose name ends in `-hook' is a normal hook.

Most major modes run hooks as the last step of initialization. This makes it easy for a user to customize the behavior of the mode, by overriding the local variable assignments already made by the mode. But hooks may also be used in other contexts. For example, the hook suspend-hook runs just before Emacs suspends itself (see Exiting).

The recommended way to add a hook function to a normal hook is by calling add-hook. You can use any valid Lisp function as the hook function. For example, here's how to set up a hook to turn on Auto Fill mode when entering Text mode and other modes based on Text mode:

(add-hook 'text-mode-hook 'turn-on-auto-fill)

The next example shows how to use a hook to customize the indentation of C code. (People often have strong personal preferences for one format compared to another.) Here the hook function is an anonymous lambda expression.

(setq my-c-style
  '((c-comment-only-line-offset . 4)
    (c-cleanup-list . (scope-operator
		       empty-defun-braces
		       defun-close-semi))
    (c-offsets-alist . ((arglist-close . c-lineup-arglist)
			(substatement-open . 0)))))
(add-hook 'c-mode-common-hook
  (function (lambda ()
    (c-add-style "my-style" my-c-style t))))

It is best to design your hook functions so that the order in which they are executed does not matter. Any dependence on the order is ``asking for trouble.'' However, the order is predictable: the most recently added hook functions are executed first.

PREVEasy Customization UPVariables NEXTLocals