1

I'm using the following to create a new buffer "untitled" with the keyboard map C-n. This works fine for a new buffer but additional buffers of the same name where <num> gets applied seem to inherit the Fundamental major mode rather than Text. Why is this?

(setq major-mode 'text-mode)

(defun new-buffer-by-name (arg)
   "Creates a new buffer by name"
   (generate-new-buffer arg)
   (set-buffer-major-mode (get-buffer arg))
   (switch-to-buffer arg))

(global-set-key (kbd "C-n")
   (lambda () (interactive)
      (new-buffer-by-name "untitled")))
1

Looking at C-h v major-mode, you'll see:

Automatically becomes buffer-local when set.

To set the default value (and not only a buffer-local value), use (setq-default major-mode 'text-mode) instead.

Moreover, you create a new buffer with generate-new-buffer but don't actually run set-buffer-major-mode on it.

Lastly, I suggest to make new-buffer-by-name itself an interactive function.

The code then becomes :

(setq-default major-mode 'text-mode)

(defun new-buffer-by-name (bufname)
  "Creates a new buffer by name"
  (interactive (list "untitled"))
  (let ((newbuf (generate-new-buffer bufname)))
    (set-buffer-major-mode newbuf)
    (switch-to-buffer newbuf)))

(global-set-key (kbd "C-n") #'new-buffer-by-name)
  • This doesn't work when creating additional buffers of the same where <num> is appended. – Zhro Aug 5 '15 at 10:37
  • @Zhro I edited the answer accordingly. – YoungFrog Aug 5 '15 at 10:59
  • Of course.. I'm setting the major mode for "untitled" instead of the new buffer! D: – Zhro Aug 5 '15 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.