Emacs: Hook
What is Hook
- A hook is a variable. Value is a list of functions (Symbol or Lambda).
- A hook variable is associated with a specific event. When the event happens, all functions in that hook are called.
- There are hundreds of hooks. Each Major Mode usually have at least 1 hook, designed to run when the mode is activated.
For example,
- when
js-mode
is loaded, js-mode-hook's functions are called. - when any command is called, post-command-hook's functions are called.
Hook is similar to the concept of event in JavaScript . Adding functions to a hook is similar to adding event handlers. (note: emacs lisp manual also uses the term “event”, but that is lower level events to emacs.)
Hook is often used to change Keys for Major Mode . see Emacs Keys: Change Major Mode Keys
Add Function to Hook
Here's example of setting proportional width font for some modes:
;; use proportional width font for some modes (add-hook 'js-mode-hook 'variable-pitch-mode)
Remove Function in Hook
(remove-hook 'js-mode-hook 'variable-pitch-mode)
;; remove all functions in the hook (setq js-mode-hook nil)