Elisp: Create a Hook

By Xah Lee. Date: . Last updated: .

Create a Hook for Major Mode

You can create a Hook to your major mode, so user can use add-hook to add functions to call when your mode is activated.

To create a hook, declare a variable like this:

(defvar my-mode-hook nil "Hook for function `my-mode-hook'.")

then add

(run-hooks 'my-mode-hook )

to the function definition body of my-mode .

when my-mode is called, it'll run hook.

💡 TIP: you can create a hook to any function, not just the mode command.

Example: Create a Hook for a Function

(defvar my-browse-url-of-buffer-hook nil
 "Hook for `my-browse-url-of-buffer'. Hook functions are called before switching to browser.")

(defun my-browse-url-of-buffer ()
  "View current buffer in default browser, but save first.
Hook `my-browse-url-of-buffer-hook' is run before saving and before opening in browser.
Version 2021-06-26"
  (let ((url (buffer-file-name)))
    (run-hooks 'my-browse-url-of-buffer-hook)
    (when (buffer-modified-p) (save-buffer))
    (browse-url url)))

Then, user might add:

(add-hook 'my-browse-url-of-buffer-hook 'my-clean-whitespace)

Emacs Hook

Emacs lisp, writing a major mode. Essentials