1

What's the best way to prompt for confirmation before killing any modified buffer, including new buffers created by evil-buffer-new, which creates a buffer without an associated filename. Modified file buffers already have confirmation, but modified new buffers without an associated filename don't. I'd like to ask for confirmation on these buffers too, whether the kill is by kill-this-buffer, restart-emacs or any other means.

3
  • 1
    You mean you do C-x C-f foo, get a new buffer foo, modify it e.g. by typing something, then you do C-x k and you don't get asked whether to "kill anyway"? When I do the above, I do get asked the question (also if I try to kill emacs with C-x C-c). If you are doing something different, please edit the question and specify exactly what you are doing. In particular, how do you create your non-file new buffer?
    – NickD
    Oct 9 at 16:58
  • @NickD updated.
    – Gavin
    Oct 9 at 18:29
  • Buffers are a data type in Emacs. They are created and killed behind the scenes very frequently. Running a command might potentially create and kill dozens of buffers that you wouldn't normally be aware of at all. You don't want to be prompted whenever any buffer is killed -- you need to make your requirement more specific than that.
    – phils
    Oct 10 at 6:25
0

Use kill-buffer-hook. But you probably don't want to force confirmation when a temporary buffer ( *...) gets killed.

Add this or similar to your init file:

(defun foo ()
  (unless (or (string-match-p "^ [*]" (buffer-name))
          (y-or-n-p
           (format "Are you sure you want to kill buffer `%s'? "
               (current-buffer))))
    (error "OK, buffer `%s' not killed" (current-buffer))))

(add-hook 'kill-buffer-hook 'foo)
2
  • This works for current buffer, but not for arbitrary new buffers on restart-emacs.
    – Gavin
    Oct 9 at 18:35
  • 1
    You have to add it to your init file, so that it gets activated every time.
    – NickD
    Oct 9 at 19:40
0

Instead of erroring out from the hook, you apparently can use the variable kill-buffer-query-functions, which seems to be made specially for that.

(defun my/confirm-closing-buffer ()
  (or (string-match-p "^ [*]" (buffer-name))
      (y-or-n-p (format "Are you sure you want to kill buffer `%s'? " (buffer-name)))))

(add-to-list 'kill-buffer-query-functions #'my/confirm-closing-buffer t)

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.