Emacs Lisp: Create a Hook

By Xah Lee. Date: . Last updated: .

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-f-hook nil "Hook for function `my-f-hook'.")

then add

(run-hooks 'my-f-hook )

to the function definition body of my-f .

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


(defvar xah-html-browse-url-of-buffer-hook nil
 "Hook for `xah-html-browse-url-of-buffer'. Hook functions are called before switching to browser.")
(defun xah-html-browse-url-of-buffer ()
  "View current buffer in default browser, but save first.
Hook `xah-html-browse-url-of-buffer-hook' is run before saving and before opening in browser.
Version 2020-06-26 2021-06-26"
  (let (($url (buffer-file-name)))
    (run-hooks 'xah-html-browse-url-of-buffer-hook )
    (when (buffer-modified-p ) (save-buffer))
    (browse-url $url )))

Then, user might add:

(add-hook 'xah-html-browse-url-of-buffer-hook 'xah-clean-whitespace)
ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Elisp Write Major Mode


Package Name/Load

Syntax Table