Elisp: How to Write a Toggle Command

By Xah Lee. Date: . Last updated: .

This page is a tutorial on how to write a command to toggle something.

Example: Command to Toggle Background Color

Here's a example to toggle background color.

(defun xah-toggle-background-color ()
  "Toggle background color between seashell and honeydew.
URL `http://xahlee.info/emacs/emacs/elisp_toggle_command.html'
Version 2015-12-17"
  ;; use a property “state”. Value is t or nil
  (if (get 'xah-toggle-background-color 'state)
        (set-background-color "seashell")
        (put 'xah-toggle-background-color 'state nil))
      (set-background-color "honeydew")
      (put 'xah-toggle-background-color 'state t))))

The gist to toggle, is to have a variable that we can set as current state.

But usually, we don't want to use a global variable.

The trick here, is to create a property for the function. In Emacs lisp, each symbol can have one or more properties. A property is basically a variable, but associated with the symbol only.

[see Elisp: Symbol Property List]

Here, we create a property named “state”. The value is t or nil.

Cycle Among States

You can create a command that cycle between many states.

Here's a example.

(defun xah-cycle-background-color (N)
  "Cycle background color among a preset list.

If `universal-argument' is called first, cycle n steps. Default is 1 step.

URL `http://xahlee.info/emacs/emacs/elisp_toggle_command.html'
Version: 2015-12-17"
  (interactive "p")
  ;; uses a property “state”. Value is a integer.
  (let* (
         (xvalues ["cornsilk" "pale green" "pale turquoise" "thistle" "seashell" "honeydew"])
          (if (get 'xah-cycle-background-color 'state)
              (get 'xah-cycle-background-color 'state)
         (xindex-after (% (+ xindex-before (length xvalues) N) (length xvalues)))
         (xnext-value (aref xvalues xindex-after)))

    (put 'xah-cycle-background-color 'state xindex-after)

    (set-background-color xnext-value)
    (message "background color changed to %s" xnext-value)))

Here, we create a property named “state”. The value is a integer.

In the function body, we have a variable that is the list of possible values. The property “state”, is used as index to this list.

Each time the command is called, we check current state, then, use modular arithmetic over the length of states list to get the next value (integer index). Then, we set the value, and update the state.

To create your own cycle something command, simply change the value list to what you want.