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.
Asked
Active
Viewed 102 times
1

Gavin
- 183
- 8
-
1You 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 09 '21 at 16:58
-
@NickD updated. – Gavin Oct 09 '21 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 '21 at 06:25
2 Answers
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)

Drew
- 75,699
- 9
- 109
- 225
-
This works for current buffer, but not for arbitrary new buffers on `restart-emacs`. – Gavin Oct 09 '21 at 18:35
-
1You have to add it to your init file, so that it gets activated every time. – NickD Oct 09 '21 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)

aaa
- 426
- 3
- 9