Emacs: What is Hook

By Xah Lee. Date: . Last updated: .

A hook is a variable, its value is a list of functions (lisp symbols or lambda).

Hook is designed to “run” when some event happens. When a hook “run”, all functions in that hook are called.

For example,

There are hundreds of hooks. Each major mode usually have at least 1 hook, designed to run when the mode is loaded.

Hook is similar to the concept of event in other systems. 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 (such as pressing a key), not events from emacs.)

Add Function to Hook

Here's example of setting proportional width font for some modes:

;; use proportional width font for some modes
(add-hook 'emacs-lisp-mode-hook 'variable-pitch-mode)
(add-hook 'js-mode-hook 'variable-pitch-mode)

Note, hook is most often used to change Keys for Major Mode. see Emacs: Change Major Mode Keys

See also: Emacs: Avoid Lambda in Hook

Remove Function in Hook

(remove-hook 'html-mode-hook 'xyz)

List All Hooks

How to Find Hook

Most major modes have a hook. If a mode's name is “xyz-mode”, its hook by convention is named “xyz-mode-hook”.

First, be sure you load the mode first. Some hook many not show when the mode isn't loaded or initialized.

To load a mode, just e.g. Alt+x js-mode

To find a mode's hook, just search variable with the name “-hook” in it, or search the name of the mode. [see Emacs: Show Variable Value, List Variables]

Note: A major mode may have more than 1 hook.

Show Value of a Hook

Emacs: Show Variable Value, List Variables

Emacs Lisp: Create a Hook

For emacs lisp programers: Emacs Lisp: Create a Hook

Major Mode and Minor Mode


Emacs Init

Init Basics

Keys

Font

Text Editing

Completion

File

Restore Things

Backup/AutoSave

Line

Appearance

Misc

Advanced Init Tips

packages