Emacs: Avoid Lambda in Hook

By Xah Lee. Date: . Last updated: .

When you add function to a hook, it is best to avoid using lambda. Instead, define the function of what you want to do, then add that function name to the hook.

[see Emacs: What is Hook]

Here's a hook definition, written with lambda.

;; modify nxml-mode's shortcut keys
(add-hook 'nxml-mode-hook
          (lambda ()
            (local-set-key (kbd "<f8>") 'browse-url-of-buffer)))

However, it is better done like this:

(defun my-xml-mode-keys ()
  "my keys for `xml-mode'."
  (interactive)
  (local-set-key (kbd "<f8>") 'browse-url-of-buffer))

(add-hook 'nxml-mode-hook 'my-xml-mode-keys)

Problems of Using Lambda in Hook

  1. Lambda in hook is unreadable when reading value of a hook, such as in describe-variable or any keybinding help or log.
  2. Lambda in hook cannot be removed using remove-hook.

Following are details.

when you type some key followed by Ctrl+h, those bound to a lambda shows as question mark. Example:

<tab> m         xah-html-pre-source-code
<tab> p         xah-html-wrap-p-tag
<tab> r         ??
<tab> s         ??
<tab> u         xah-html-wrap-html-tag
<tab> w         ??

Also, you can lookup a hook's value by Alt+x describe-variable. If you used lambda, it's harder to read.

A hook is a list of functions. If you use function symbols, you can remove some of your hooked function by remove-hook.

;; removing a hook
(remove-hook 'html-mode-hook 'xah-html-mode-keys)

thanks to [Steve Youngs https://plus.google.com/117914896572210140511/posts] for input.

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