LoginSignup
6
3

More than 5 years have passed since last update.

emacsのauto-mode-alistが動かない!?

Posted at

何が起こったか

perl を書こうと思って、.emacs.d/init.el に以下のような設定をしました。

.emacs.d/init.el
(add-to-list 'auto-mode-alist '("\\.pl\\'" . cperl-mode))

(defun hookfunc-cperl-mode ()
  (flycheck-mode))

(add-hook 'cperl-mode-hook 'hookfunc-cperl-mode)

find-file(C-xC-f)で、新しいファイルを開くと、ちゃんとcperl-modeになったのですが、再度エディットしようと思い、ファイルを開くと…  あら? 普通のperl-modeになってしまいました。

調査開始w

bufferの エディットモードはlisp/files.el(自分の環境では/usr/local/share/emacs/25.2/lisp)で定義されています。

ソースが長いので、コメントを見てみます。

files.el
(defun set-auto-mode (&optional keep-mode-if-same)
  "Select major mode appropriate for current buffer.

To find the right major mode, this function checks for a -*- mode tag
checks for a `mode:' entry in the Local Variables section of the file,
checks if it uses an interpreter listed in `interpreter-mode-alist',
matches the buffer beginning against `magic-mode-alist',
compares the filename against the entries in `auto-mode-alist',
then matches the buffer beginning against `magic-fallback-mode-alist'.

1. -*-のタグ(# -- mode:cperl --)
2. interpreter-mode-alist(shebangをチェックしてモードを決める)
3. magic-mode-alist(正規表現が最初の行にマッチするかでモードを決める)
4. auto-mode-alist(ファイル名がマッチするかで、モードを決める)
5. magic-fallback-mode-alist(上記にマッチしない場合、最後にもう一回最初の行をチェック)

の順番で確認してメジャーモードを決めているようです。

最初にファイルを作る場合は、4.でめでたくcperl-modeを認識したのですが、ファイルを一度作ったあとにもう一度開いたときには2.でメジャーモードが判定されたため、perl-modeになってしまったようです。

どうしたか

今回の原因は、上記の2.でメジャーモードが判定されるのが原因なので、

.emacs.d/init.el
(add-to-list 'auto-mode-alist '("\\.pl\\'" . cperl-mode))
(add-to-list 'interpreter-mode-alist '("perl" . cperl-mode))
(defun hookfunc-cperl-mode ()
  (flycheck-mode))

のようにしました。 これでめでたく既存のファイルもcperl-modeになりました。

その後

色々書いてきましたが、今は下記の通りで落ち着いています。

.emacs.d/init.el
(defun hookfunc-perl-mode ()
  (cperl-mode)
  (flycheck-mode))
(add-hook 'perl-mode-hook 'hookfunc-perl-mode)

なんだかなーな、感じですが、これが一番ラクですw

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3