Matthias David

Emacser, Indépendant, Technicien, Developpeur

Theme Dark/Light automatique

Publié le 19 janv. 2022 par Matthias David.

Fortement inspiré par le code de Luca Cambiaghi que vous trouverez içi.

Voici un bout de code qui permet de changer automatiquement de thème (Light/Dark), suivant les heures de lever et de coucher du soleil selon la région.

Il faut au préalable renseigner les variables suivantes:

Code

(require 'solar)

(defun md/load-dark-theme ()
  (setq doom-theme dark-theme)
  (load-theme 'doom-verde))

(defun md/load-light-theme ()
  (setq doom-theme light-theme)
  (load-theme 'doom-one-light))

;; --- Sunset-sunrise
(defun frac-to-time (f)
  "Convert fractional time F to (HH MM)."
  (let ((l (cl-floor f)))
       (list (cl-first l)
             (floor (* 60 (cl-second l))))))

(defun md/diary-sunrise ()
  "Get clean sunrise time string from Emacs' `sunset-sunrise'`."
  (frac-to-time (cl-first (cl-first (solar-sunrise-sunset (calendar-current-date))))))

(defun md/diary-sunset ()
  "Get clean sunset time string from Emacs' `sunset-sunrise'`."
  (frac-to-time (cl-first (cl-second (solar-sunrise-sunset (calendar-current-date))))))

(defun md/encode-time (time)
  "Encode TIME into a valid format for `run-at-time'."
  (let ((hour (car time))
        (min (-last-item time)))
    (format "%s:%s" hour min)))


(defun md/change-theme-with-timers ()
  (message "Changement auto du theme")
  (run-at-time "00:00" (* 60 60 24) 'md/load-dark-theme)
  (run-at-time (md/encode-time (md/diary-sunrise)) (* 60 60 24) 'md/load-light-theme)
  (run-at-time (md/encode-time (md/diary-sunset)) (* 60 60 24) 'md/load-dark-theme))

(defconst light-theme 'doom-one-light)
(defconst dark-theme  'doom-verde)

(defun md/toggle-theme ()
  "Toggle between light and dark themes."
  (interactive)
  (cond ((eq doom-theme dark-theme)
         (message "Changement pour le theme light: %s" light-theme)
         (setq doom-theme light-theme)
         (load-theme light-theme))
        ((eq doom-theme light-theme)
         (message "Changement pour le theme dark: %s" dark-theme)
         (setq doom-theme dark-theme)
         (load-theme dark-theme))
        (t (message "Toggling theme is not possible. Theme is not currently light-theme (%s) or dark-theme (%s)." light-theme dark-theme))))

(add-hook 'emacs-startup-hook 'md/change-theme-with-timers)