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.
2 Answers
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)
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)
C-x C-f foo
, get a new bufferfoo
, modify it e.g. by typing something, then you doC-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 withC-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?