Loading and unloading GNU Emacs themes
Every time you call load-theme
in GNU Emacs, there is a chance that previous theme changed something that new theme does not. Also, sometimes themes change linum
(line numbers) settings and if you use linum
you don't want that. Here is part of my GNU Emacs configuration and how I deal with those problems.
Enter advice-add
In Emacs lisp you can create are advising functions that can run before or after some other functions. Actually, there are other possibilities except before or after, but those are out of scope of this article.
Here is complete code, including line number formatting. Comments are present to explain code.
;; enable linum-mode (line number mode)
(global-linum-mode 1)
;; Create function for line number format
;; Basic idea is to align line number to the right and to make
;; height of linum dependent of total line numbers.
(defun linum-format-func (line)
"Format LINE for 'linum-mode'."
(let ((w (length (number-to-string (count-lines (point-min) (point-max))))))
(propertize (format (format "%%%dd%c" w ?\x2007) line) 'face 'linum)))
;; Set last function as linum formatter
(setq linum-format 'linum-format-func)
;; before loading new theme
(defun load-theme--disable-old-theme(theme &rest args)
"Disable current theme before loading new one."
(mapcar #'disable-theme custom-enabled-themes))
(advice-add 'load-theme :before #'load-theme--disable-old-theme)
;; After loading new theme
(defun load-theme--restore-line-numbering(theme &rest args)
"Set linum-format again after loading any theme."
(setq linum-format 'linum-format-func))
(advice-add 'load-theme :after #'load-theme--restore-line-numbering)
Old defadvice
There are few examples on the Internet of doing this in Emacs with defadvice
. That is old version of advice-add
and it's deprecated. There is one chapter in Emacs manual that explains how to port old defadvice
code to add-advice
. At the moment of writing of this article, defadvice
is still working in GNU Emacs.