Emacs: Avoid Lambda in Hook

Buy Xah Emacs Tutorial. Master emacs benefits for life.
, ,

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.

Here's a hook definition, written in the way most people would write it:

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

However, it is better done like this:

(defun xah-xml-mode-keys ()
  "my keys for `xml-mode'."
  (local-set-key (kbd "<f8>") 'browse-url-of-buffer)
  (local-set-key (kbd "<tab>") 'html-next-content)
  (local-set-key (kbd "S-<tab>") 'html-previous-content)

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

Problems of Using Lambda in Hook

There are minor advantages in not using lambda in hook.

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

;; example of removing a hook. Can't be done if you used lambda in hook.
(remove-hook 'html-mode-hook 'xah-html-mode-keys)

You can lookup a hook's value by calling describe-variable. If you used lambda, it's harder to read.

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

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

Also, suppose you are using command-frequency-mode to know what commands you use the most. If you have lambda, the data will become unreadable with bunch of lambda code, instead of command names.

thanks to Steve Youngs for input.

Like it?
Buy Xah Emacs Tutorial
or share
blog comments powered by Disqus