Elisp: How to Write a Toggle Command

By Xah Lee. Date: . Last updated: .

The gist to toggle something is to have a variable that indicates the current state.

we can use Symbol Property List to store the current state.

Here's a example to toggle background color.

(defun my-toggle-background-color ()
  "Toggle background color between seashell and honeydew."
  (interactive)
  (if (get real-this-command 'xstatus)
      (progn
        (set-background-color "seashell")
        (put real-this-command 'xstatus nil))
    (progn
      (set-background-color "honeydew")
      (put real-this-command 'xstatus t))))