Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a warning before killing a temporary buffer in Emacs?

Tags:

emacs

More than once I've lost work by accidentally killing a temporary buffer in Emacs. Can I set up Emacs to give me a warning when I kill a buffer not associated with a file?

like image 906
James Sulak Avatar asked Sep 17 '08 19:09

James Sulak


2 Answers

Make a function that will ask you whether you're sure when the buffer has been edited and is not associated with a file. Then add that function to the list kill-buffer-query-functions.

Looking at the documentation for Buffer File Name you understand:

  • a buffer is not visiting a file if and only if the variable buffer-file-name is nil

Use that insight to write the function:

(defun maybe-kill-buffer ()
  (if (and (not buffer-file-name)
           (buffer-modified-p))
      ;; buffer is not visiting a file
      (y-or-n-p "This buffer is not visiting a file but has been edited.  Kill it anyway? ")
    t))

And then add the function to the hook like so:

(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer)
like image 104
EfForEffort Avatar answered Nov 04 '22 18:11

EfForEffort


(defun maybe-kill-buffer ()
  (if (and (not buffer-file-name)
           (buffer-modified-p))
      ;; buffer is not visiting a file
      (y-or-n-p (format "Buffer %s has been edited.  Kill it anyway? "
                        (buffer-name)))
    t))

(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer)
like image 34
cjm Avatar answered Nov 04 '22 17:11

cjm