Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

(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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top