Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Configuration and Elisp

Emacs Key Bindings, Hooks and Advice

Bind your own keys with keymaps, use-package style :bind, attach functions to hooks, and change existing commands safely with advice-add.

Three mechanisms let you change how Emacs behaves without editing its source: keymaps decide what a key does, hooks run your code at defined moments, and advice wraps an existing function. Together they cover most customization. This lesson explains each, with real Elisp and small stand-ins that model how Emacs looks things up.

Keymaps and how keys are looked up

A keymap is a table from key sequences to commands. Emacs checks several keymaps in a fixed priority order when you press a key. Simplified, from highest to lowest priority:

  1. keymaps of minor modes that are active (for example flyspell-mode-map);
  2. the local map of the current major mode (for example org-mode-map);
  3. the global map.

The first map that defines the key wins. That is why C-c C-c does different things in Org, Magit and a plain buffer.

ELISP
(global-set-key (kbd "C-c d") #'my/insert-date)     ; everywhere
(keymap-global-set "C-c d" #'my/insert-date)        ; Emacs 29+ syntax
(define-key org-mode-map (kbd "C-c m") #'my/note)   ; only in Org
(keymap-set org-mode-map "C-c m" #'my/note)         ; Emacs 29+
(global-unset-key (kbd "C-z"))                      ; remove a binding

kbd turns a human description into the internal key form: C-x is Control, M-x is Meta (Alt), s- is Super, <f5> a function key, RET, TAB, SPC, ESC are special keys. Emacs 29 added keymap-set and friends, which take the same description strings directly (and check them for mistakes).

Reserved keys: the sequences C-c followed by a single letter (such as C-c d) are reserved for you; packages must not use them. Safe to bind freely. Use C-h k (describe-key) to see what a key does now, and C-h b to list bindings in the current buffer.

Prefix keys and define-prefix-command

Many keys are prefixes: C-x, C-c, M-g. You can create your own prefix map to group commands:

ELISP
(define-prefix-command 'my/map)
(global-set-key (kbd "C-c m") 'my/map)
(define-key my/map (kbd "d") #'my/insert-date)
(define-key my/map (kbd "l") #'my/duplicate-line)

Now C-c m d and C-c m l work, and which-key-mode (built in since Emacs 30; a package before that) pops up a cheat sheet after a short pause.

JS Stand-in: key lookup order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Hooks

A hook is a variable holding a list of functions that Emacs calls at a particular event. Most hooks are named after the mode or action: prog-mode-hook runs when any programming major mode starts, before-save-hook just before a buffer is written, after-init-hook when startup finishes, find-file-hook after visiting a file.

ELISP
(add-hook 'prog-mode-hook #'display-line-numbers-mode)
(add-hook 'before-save-hook #'delete-trailing-whitespace)
(add-hook 'text-mode-hook (lambda () (auto-fill-mode 1)))
(remove-hook 'before-save-hook #'delete-trailing-whitespace)

Hook functions take no arguments (for normal hooks). Some are abnormal hooks that pass arguments, such as after-change-functions. You can make a hook local to one buffer with (add-hook 'before-save-hook #'my/fn nil t); the t fourth argument means "buffer-local".

Prefer named functions over lambdas: you can remove or redefine them, and M-x describe-variable on the hook shows readable names. Mode hooks also run in a useful order: text-mode-hook first, then the derived mode's own (markdown-mode-hook), because many modes derive from text-mode or prog-mode.

JS Stand-in: add-hook and run-hooks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Advice: wrapping existing functions

Sometimes there is no hook where you need one. Advice lets you add code before, after or around any named function:

ELISP
(defun my/say-saving (&rest _)
  (message "Saving..."))
(advice-add 'save-buffer :before #'my/say-saving)

(defun my/loud-find-file (orig-fun &rest args)
  (message "Opening %S" args)
  (apply orig-fun args))
(advice-add 'find-file :around #'my/loud-find-file)

(advice-remove 'find-file #'my/loud-find-file)

Common combinators are :before, :after, :around (you receive the original function as the first argument), :filter-args, :filter-return and :override (replace entirely). Advice is powerful and global, so use it sparingly: hooks and options come first, advice last. When debugging, C-h f on the advised function lists active advice, and M-x advice-remove undoes it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which keymap has the highest priority when you press a key?

    Emacs checks minor-mode maps first, then the major mode's map, then the global map.
  2. 2. Which key sequences are reserved for users to bind freely?

    By convention packages avoid C-c plus a single letter, so those bindings belong to you.
  3. 3. What does (add-hook 'before-save-hook #'delete-trailing-whitespace) do?

    Functions on before-save-hook run before each save.
  4. 4. In :around advice, what is the first argument your function receives?

    An :around function is called with the original function first, followed by its arguments, and decides whether to call it.

Summary

  • Key lookup order: active minor modes, then the major mode map, then the global map.
  • Use keymap-set, keymap-global-set or define-key with kbd; C-c <letter> is yours.
  • Hooks are function lists; add-hook and remove-hook manage them, and a local hook is added with the fourth argument t.
  • advice-add wraps any function (:before, :after, :around, ...); use it last.
  • C-h k, C-h b, C-h v and C-h f show what is actually bound or advised.

Next: Package Management and use-package