1. 不一定非得扩展名/后缀名,前缀、中缀或者全名都可以作为判断依据,例如:
(add-to-list 'auto-mode-alist ("\\`Makefile\\'" . makefile-mode))
甚至路径也可以用来作为判断依据:
(add-to-list 'auto-mode-alist '("md/readme" . markdown-mode))
(add-to-list 'auto-mode-alist '("org/readme" . org-mode))
2. 在文件第一行指定模式:
// test_c -*- mode: c; -*-
3. 通过 file local variable (M-x add-file-local-variable
)指定模式:
;; Local Variables:
;; mode: c
;; End:
;; test_c ends here
4. 通过 dir local variable (M-x add-dir-local-variable
)指定模式。
这种方式稍复杂,最好对文件加载过程有一定了解,否则可能导致死循环,参考:请教怎样用 .dir-locals.el 来设置一个目录下的文件的 major mode 为 conf-mode? - #2,来自 cireu
5. magic-mode-alist
是 auto-mode-alist
之后的另一道防线。它有两种形式:
5.1 (regex . mode-function)
regex
匹配文件头部内容,例如 shebang 和二进制文件的魔法数字:
;; This regexp matches shebang expressions like `#!/usr/bin/env boot'
(add-to-list 'magic-mode-alist '("#!.*boot\\s-*$" . clojure-mode))
;; "Make `macho-mode' get called automatically for binaries.
(add-to-list 'magic-mode-alist '("\xFE\xED\xFA\xCE" . macho-mode))
5.2 (match-function . mode-function)
match-function
提供更高的自由度,可以做更多的事,例如检查文件内容特征:
(add-to-list 'magic-mode-alist (cons #'spacemacs//javascript-jsx-file-p 'rjsx-mode))
(defun spacemacs//javascript-jsx-file-p ()
"Enable rjsx mode by using magic-mode-alist."
(when buffer-file-name
(and (member (file-name-extension buffer-file-name) '("js" "jsx"))
(re-search-forward "\\(^\\s-*import React\\|\\( from \\|require(\\)[\"']react\\)"
magic-mode-regexp-match-limit t)
(save-excursion
(goto-char (match-beginning 1))
(let ((sexp (syntax-ppss)))
;; not inside string or comment
(not (or (nth 3 sexp)
(nth 4 sexp))))))))