Published on

Switch theme in emacs

  1. Show available themes to select
  2. Disable the current theme
  3. Load the selected theme
(defun switch-theme ()
  "Interactively select and load an Emacs theme."
  (interactive)
  (let* ((available-themes (custom-available-themes))
         (current-theme (car custom-enabled-themes))
         (chosen-theme (intern (completing-read "Select theme: " available-themes nil t)))
         (disable-themes (delq chosen-theme custom-enabled-themes)))
    ;; Disable the current theme(s)
    (mapc 'disable-theme custom-enabled-themes)
    (setq custom-enabled-themes nil)
    
    ;; Load the chosen theme
    (load-theme chosen-theme t)
    
    (message "Theme '%s' loaded. Disabled themes: %s" chosen-theme (mapconcat 'symbol-name disable-themes ", "))))

Here's how the function works:

  1. available-themes: It retrieves a list of available themes.
  2. current-theme: It captures the currently enabled theme.
  3. chosen-theme: It allows to select a theme from the available themes using completing-read.
  4. disable-themes: It stores the list of themes that need to be disabled (the current theme plus any other currently enabled themes).
  5. mapc: It disables the themes listed in disable-themes.
  6. setq custom-enabled-themes nil: This clears the list of enabled themes.
  7. load-theme: It loads the chosen theme.
  8. A message is displayed indicating which theme was loaded and which themes were disabled.

(switch-theme), will prompt to select a theme from the available themes, disable the current theme(s), and load the selected theme.