Emacs auto-minor-mode based on extension

前端 未结 2 1757
悲哀的现实
悲哀的现实 2021-02-07 05:13

I found this question somewhat on the topic, but is there a way [in emacs] to set a minor mode (or a list thereof) based on extension? For example, it\'s pretty easy to

相关标签:
2条回答
  • 2021-02-07 05:26

    This code seems to give what you want:

    (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)
    

    Note: the comparison is done with string-match-p which follows the case-fold-search settings during comparison.

    0 讨论(0)
  • 2021-02-07 05:26

    The answer by Trey Jackson seems to be a very robust and extensible solution, but I was looking for something simpler. The following code will enable the fictional hmmm-mode when editing .hmmm files:

    (add-hook 'find-file-hook
              (lambda ()
                (when (string= (file-name-extension buffer-file-name) "hmmm")
                  (hmmm-mode +1))))
    
    0 讨论(0)
提交回复
热议问题