How to create new buffer with major-mode like auto-mode-alist do for file?

Like, C-x b a.el <RET> create buffer named a.el but with emacs-lisp-mode instead of fundamental-mode.

I have tried to search, without luck.


Unfortunately, auto-mode-alist only works for filename but not buffer.

auto-mode-alist is a variable defined in ‘files.el’.

Documentation:

Alist of filename patterns vs corresponding major mode functions.


And there is not something like create-buffer-*-hook could be used.

Please help :slight_smile:


Currently, the workaround is used find-file but without saving them, but you have to bother to avoid filename conflict and accident saving them, and when exit, ask you whether want to save file.

Quick and dirty hack:

(define-advice switch-to-buffer (:around (fn &rest args) set-mode-for-new-buf)
  (let ((bufs (buffer-list))
        (buf (apply fn args)))
    (unless (memq buf bufs)
      (funcall (or (assoc-default (buffer-name) auto-mode-alist #'string-match)
                   #'ignore)))))
1 个赞