Since I’m using MacOS again for the work, and obviously, I still use Emacs, I wanted to have a functionality which would detect which system theme is being used and load the correct one during Emacs startup.

Previously, I have hacked together just a simple script which depended on GTK theme. Basically, If command returns string Adwaita, load light theme, if it returns Adwaita-dark, load dark theme.

Later I learned that this might not be the good approach at all, even more so since GNOME developed concept of having Dark and Light theme.

Without further ado, this is what I cobbled together:

(defun system-dark-mode-enabled-p ()
  "Check if dark mode is currently enabled."
  (pcase system-type
    ('darwin
     ;; Have to use osascript here as defaults returns inconsistent results
     ;; - AppleInterfaceStyleSwitchesAutomatically == 1 ;; exists only if the theme is set to auto
     ;; - AppleInterfaceStyle == Dark ;; exists only if the theme is set to dark
     ;; How to determine if theme is light or dark when Automatic Theme switching is in place?
     ;; Luckily, osascript can provide that detail
     (if (string= (shell-command-to-string "printf %s \"$( osascript -e \'tell application \"System Events\" to tell appearance preferences to return dark mode\' )\"") "true") t))
    ('gnu/linux
     ;; prefer-dark and default are possible options
     (if (string= (shell-command-to-string "gsettings get org.gnome.desktop.interface color-scheme") "\'prefer-dark\'\n") t))))

This function basically returns t if dark mode is enabled, and nil if not. And with this, I just need to use that variable while loading the theme:

(defun tomica/load-theme ()
  "Load dark/light variant depending on the system theme"
  (interactive)
  ;; Load files before loading the theme
  (modus-themes-load-themes)
  (if (system-dark-mode-enabled-p)
      (modus-themes-load-vivendi)
    (modus-themes-load-operandi)))

What I’d still like to develop here is support for KDE on Linux. But perhaps some other day.

Also, as you can see, I am using great themes provided by Protasilaos Stavrou called modus-themes. If you haven’t already, I recommend you to check them out!