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 'ruby-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

List of Emacs 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,

Alt+x describe-variable, then try to type a name you guessed, press Tab for completion.

Or

  1. Alt+x apropos-variable
  2. Type “-hook”, press Enter.

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

Show Value of a Hook

Alt+x describe-variable, then type the hook name, to see its current value.

Elisp: Create a Hook

For emacs lisp programers: Elisp: Create a Hook

Major Mode and Minor Mode

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


Emacs Init

Init Basics

packages

text editing

file

appearance

misc