tags:

views:

120

answers:

2

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?

+7  A: 

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'.

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

EDIT: the following should work if you put it in `kill-buffer-query-functions':

(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))

EDIT: To add it to the list, do:

(add-to-list 'kill-buffer-query-functions 'maybe-kill-buffer)
Denis Bueno
This works, except I have to remove the "buffer" argument.
James Sulak
Also, is there any way to make it exclude other buffers, such as *Open Recent*?
James Sulak
You could put the following inside the `and' after `buffer-modified-p': (not (equal (buffer-name) "*Open Recent*"))
Denis Bueno
+1  A: 
(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)
cjm