在使用 Emacs 的过程中,或多或少都会去自定义样式,比如 macOS 下的 ns_selection_bg_color[1],想法是挺好,跟随系统色调来调整 region 的背景色,但是晚上的颜色巨丑,严重影响使用体验,截图可参考这个帖子[2]。
白天的颜色
晚上的颜色
网上推荐做法一般如下:
(set-face-attribute
'region nil
:distant-foreground 'unspecified
:background "#BAD6FC")
;; 或
(custom-set-faces
'(region ((t (:background "#BAD6FC")))))
上面的方式相当于全局配置,在所有主题中都生效,我早期一直也是这么做的。
但是这样会导致一个问题,即在切换主题时,可能会与主题的配色冲突。之前我都是把相关代码注释掉,重启 Emacs 后再去加载主题,一直懒得去找更好的解决方式。
后来在使用 customize 界面时,无意间发现可以把当前样式的配置一键抽出来,定义为一个主题,使用自定义主题就解决了全局生效的问题,切换到其他主题前,disable 自定义主题即可,利用 advice 机制可以自动做这件事:
(defun my/disable-previous-theme (theme &optional _ _)
"disable other themes before loading new one"
(mapc 'disable-theme custom-enabled-themes))
(advice-add 'load-theme :before 'my/disable-previous-theme)
下面是我自定义的亮色主题(创建主题可以用 M-x customize-create-theme[3] 命令,比较直观):
(deftheme mylight
"Created 2021-09-12.")
(custom-theme-set-faces
'mylight
'(hl-line ((t (:background "gray90" :underline nil :foreground nil))))
'(region ((t (:background "#BAD6FC")))))
(provide-theme 'mylight)
尝试了 N 个主题后,发现 Emacs 默认的就很耐用。如果用的不是默认主题,那么在 custom-theme-set-faces 第二个参数指定,这样也可以让样式配置仅在其主题中生效。
• Notes on Deftheme[4]
[1]
ns_selection_bg_color: https://github.com/DarwinAwardWinner/dotemacs#dont-use-ns_selection_fg_color-and-ns_selection_bg_color
[2]
这个帖子: https://emacs-china.org/t/region-background/15271
[3]
M-x customize-create-theme: https://www.gnu.org/software/emacs/manual/html_node/emacs/Creating-Custom-Themes.html#Creating-Custom-Themes
[4]
Notes on Deftheme: https://emacsfodder.github.io/blog/notes-on-deftheme/