Emacs: Cycle Fonts by Command 📜

By Xah Lee. Date: . Last updated: .

Here's commands that switch among font for current window. Especially useful for comparison of fonts.

put this in your Emacs Init File:

(defvar xah-font-list
  (cond
   ((eq system-type 'windows-nt)
    (vector
     ;; "Courier New"
     "Consolas"
     "Lucida Console"
     "Cascadia Mono"))
   ((eq system-type 'darwin) ; Mac
    (vector
     "Menlo"
     "Monaco"
     ;; "Courier New"
     ))
   ((eq system-type 'gnu/linux)
    (vector
     "DejaVu Sans Mono"
     "Inconsolata"
     "Liberation Mono")))
  "A vector of font names for `xah-cycle-font' to cycle from. Each is a string.
URL `http://xahlee.info/emacs/emacs/emacs_switching_fonts.html'")
(defun xah-cycle-font (&optional Skip-n)
  "Change font in current frame.
Each time this is called, font cycles thru fonts in the variable `xah-font-list' .

Press right arrow or left arrow to switch to next or prev font.

In lisp code, Skip-n is a integer.
If Skip-n is 1, cycle forward.
If Skip-n is -1, cycle backward.

URL `http://xahlee.info/emacs/emacs/emacs_switching_fonts.html'
Created: 2015-09-21
Version: 2025-08-07"
  (interactive "p")
  (let (xfontToUse xexist xstateBefore xstateAfter (xskip-n (or Skip-n 1)))
    ;; nstate is a integer. Possible values are valid index to the xah-font-list.
    (setq xstateBefore (if (get 'xah-cycle-font 'nstate) (get 'xah-cycle-font 'nstate) 0))
    (setq xstateAfter (% (+ xstateBefore (length xah-font-list) xskip-n) (length xah-font-list)))
    (setq xfontToUse (aref xah-font-list xstateAfter))
    (setq xexist (member xfontToUse (font-family-list)))
    (if xexist
        (progn
          (set-frame-font xfontToUse t)
          (message "Current font is: %s" xfontToUse))
      (message "font not exist: %s" xfontToUse))
    (put 'xah-cycle-font 'nstate xstateAfter))
  (set-transient-map
   (let ((xkmap (make-sparse-keymap)))
     (keymap-set xkmap "<left>" (lambda () (interactive) (xah-cycle-font -1)))
     (keymap-set xkmap "<right>" (lambda () (interactive) (xah-cycle-font 1)))
     xkmap)))

Emacs, font setup