Wai Hon's Blog

Ignore "save-buffer" Unless Visiting a File

2022-04-09 #emacs

I have a habit of hitting the save shortcut (C-x C-s) occasionally. However, if the buffer does not have a visited file (like treemacs, vterm, scratch, help, etc), Emacs asks me where to save the file and I need to cancel with triple ESC.

For example, hitting C-x C-s within the *scratch* buffer.

This is annoying. To fix it, I remap save-buffer to the function below1 which does nothing for non-file-visiting buffer.

(defun my/save-buffer (&optional arg)
  "Like `save-buffer', but does nothing if buffer is not visiting a file."
  (interactive "p")
  (unless (or (buffer-file-name)                       ; regular buffer
              (buffer-file-name (buffer-base-buffer))) ; indirect buffer
    (user-error "Use 'M-x save-buffer' explicitly to save this buffer with no visited file"))
  (save-buffer arg))

(global-set-key [remap save-buffer] #'my/save-buffer)

Now, I get the message below and do not need to cancel the save operation.

Update: My friend AhLeung has an alternative using save-all-buffers:

(defun my/save-all-buffers ()
  "Save all motified file-visiting buffers without asking."
  (save-some-buffers t))

(global-set-key [remap save-buffer] #'my/save-all-buffers)

  1. This elisp is updated with the suggestion from Phil-Hudson. Thanks! ↩︎