基于扩展的Emacs自动辅助模式 [英] Emacs auto-minor-mode based on extension
问题描述
我发现这个问题有些主题,但是有没有一种方式(在emacs中)根据扩展设置一个次要模式(或其列表)?例如,很容易发现,主要模式可以像这样操纵
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 find out that major modes can be manipulated like so
(setq auto-mode-alist
(cons '("\\.notes$" . text-mode)
auto-mode-alist))
我最理想的做法是
(setq auto-minor-mode-alist
(cons '("\\.notes$" . auto-fill-mode)
auto-minor-mode-alist))
链接问题的接受答案提到了钩子,特别是 temp-buffer-setup-hook
/ A>。要使用这个,你必须像这样添加一个函数给钩子。
The accept answer of the linked question mentions hooks, specifically temp-buffer-setup-hook
. To use this, you have to add a function to the hook like so
(add-hook 'temp-buffer-setup-hook 'my-func-to-set-minor-mode)
我的问题是双重的:
- 与主要模式类似,是否有更简单的方法?
- 如果没有,一个写钩子的功能怎么样?
- Is there an easier way to do this, similar to major modes?
- If not, how would one write the function for the hook?
- 需要根据正则表达式检查文件路径。
- 如果匹配,请激活所需的模式例如
自动填充模式
)。
- It needs to check the file path against a regular expression.
- If it matches, activate the desired mode (e.g.
auto-fill-mode
).
解决方案的费用低廉:
Feeble and buggy attempt at a solution:
; 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))))
推荐答案
这段代码似乎给了你想要的:
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 buffer-file-name)
(remote-id (file-remote-p buffer-file-name))
(alist auto-minor-mode-alist))
;; Remove backup-suffixes from file name.
(setq name (file-name-sans-versions name))
;; 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 (caar alist) name)
(funcall (cdar alist) 1))
(setq alist (cdr alist))))))
(add-hook 'find-file-hook 'enable-minor-mode-based-on-extension)
注意:比较是用 string-match-p
在比较期间跟随 case-fold-search
设置。
Note: the comparison is done with string-match-p
which follows the case-fold-search
settings during comparison.
这篇关于基于扩展的Emacs自动辅助模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!