基于扩展的Emacs自动次要模式

Sea*_*red 15 emacs elisp dot-emacs

我在这个主题上发现了这个问题,但是有没有办法[在emacs中]基于扩展设置次要模式(或其列表)?例如,很容易发现可以像这样操纵主要模式

(add-to-list 'auto-mode-alist '("\\.notes\\'" . text-mode))
Run Code Online (Sandbox Code Playgroud)

而我理想的是能够做到的是

(add-to-list 'auto-minor-mode-alist '("\\.notes\\'" . auto-fill-mode))
Run Code Online (Sandbox Code Playgroud)

联系问题的接受答案提到钩子,特别是temp-buffer-setup-hook.要使用它,你必须像这样向钩子添加一个函数

(add-hook 'temp-buffer-setup-hook #'my-func-to-set-minor-mode)
Run Code Online (Sandbox Code Playgroud)

我的问题是双重的:

  1. 是否有更简单的方法来执行此操作,类似于主要模式?
  2. 如果没有,如何为钩子编写函数?
    1. 它需要根据正则表达式检查文件路径.
    2. 如果匹配,则激活所需模式(例如auto-fill-mode).

微弱的和错误的尝试解决方案:

;; Enables the given minor mode for the current buffer it it matches regex
;; my-pair is a cons cell (regular-expression . minor-mode)
(defun enable-minor-mode (my-pair)
  (if buffer-file-name ; If we are visiting a file,
      ;; and the filename matches our regular expression,
      (if (string-match (car my-pair) buffer-file-name) 
      (funcall (cdr my-pair))))) ; enable the minor mode

; used as
(add-hook 'temp-buffer-setup-hook
          (lambda ()
            (enable-minor-mode '("\\.notes\\'" . auto-fill-mode))))
Run Code Online (Sandbox Code Playgroud)

Tre*_*son 11

这段代码似乎给你想要的东西:

(defvar auto-minor-mode-alist ()
  "Alist of filename patterns vs correpsonding minor mode functions, see `auto-mode-alist'
All elements of this alist are checked, meaning you can enable multiple minor modes for the same regexp.")

(defun enable-minor-mode-based-on-extension ()
  "Check file name against `auto-minor-mode-alist' to enable minor modes
the checking happens for all pairs in auto-minor-mode-alist"
  (when buffer-file-name
    (let ((name (file-name-sans-versions buffer-file-name))
          (remote-id (file-remote-p buffer-file-name))
          (case-fold-search auto-mode-case-fold)
          (alist auto-minor-mode-alist))
      ;; Remove remote file name identification.
      (when (and (stringp remote-id)
                 (string-match-p (regexp-quote remote-id) name))
        (setq name (substring name (match-end 0))))
      (while (and alist (caar alist) (cdar alist))
        (if (string-match-p (caar alist) name)
            (funcall (cdar alist) 1))
        (setq alist (cdr alist))))))

(add-hook 'find-file-hook #'enable-minor-mode-based-on-extension)
Run Code Online (Sandbox Code Playgroud)

注意:比较完成后string-match-p,case-fold-search比较时的设置.


Rad*_*ugh 9

Trey Jackson的答案似乎是一个非常强大和可扩展的解决方案,但我一直在寻找更简单的东西.以下代码将hmmm-mode在编辑.hmmm文件时启用虚构:

(add-hook 'find-file-hook
          (lambda ()
            (when (string= (file-name-extension buffer-file-name) "hmmm")
              (hmmm-mode +1))))
Run Code Online (Sandbox Code Playgroud)