Elisp: Create a Hook

By Xah Lee. Date: .

You can create a hook for the event when your function is called. [see Emacs: What is Hook] User can use add-hook to add functions to call when your function is called.

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.

Example

(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"
  (interactive)
  (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)

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


ELisp Write Major Mode

Basics

Package Name/Load

Syntax Table