Emacs根据major-mode切换主题和minor-mode

Emacs根据major-mode切换主题和minor-mode

Table of Contents

1. 背景

近些年我的所有Coding和记录工作都在emacs上进行,当我在Coding时,我更喜欢使用护眼的暗色主题;而当我写一些笔记或文章时,我更希望使用一些更类似于纸张的浅色主题。同时,在写作时,我习惯于使用Writeroom Mode,较宽的侧边距使我更专注于文字本身。曾经我需要在自己处于某种工作状态时手动进行切换。

得益于Emacs27之后引入的关于窗口变化的一系列hook,我们可以自定义buffer切换时的动作了。这里使用的是window-buffer-change-functions这个hook,它会在buffer被切换时触发。

2. 实例

(add-hook 'window-buffer-change-functions
          (lambda (window)
            (if (member major-mode (list 'org-mode 'markdown-mode))
                (writing)
              (not-writing))))

(defun writing ()
  (unless (bound-and-true-p writeroom-mode)
    (progn
      (disable-theme 'doom-monokai-pro)
      (load-theme 'doom-acario-light t)
      (writeroom--enable))))

(defun not-writing ()
  (disable-theme 'doom-acario-light)
  (enable-theme 'doom-monokai-pro)
  (writeroom--disable))

3. 效果

  • org-mode:
    emacs-switch-org.png
  • elisp-mode:

    emacs-switch-el.png