ProtectingBuffers

Emacs Lock

Emacs Lock (‘emacs-lock-mode’) is a minor mode for marking buffers as protected. Several levels of protection are provided:

The default locking behavior can be customized via ‘emacs-lock-default-locking-mode’.

Emacs Lock is included in Emacs 24.

To protect the scratch buffer against accidental kill you can use the following code in .emacs or in init.el :

	(with-current-buffer "*scratch*"
	  (emacs-lock-mode 'kill))

And to unprotect :

	(with-current-buffer "*scratch*"
	  (emacs-lock-mode -1))

Protecting Buffers in XEmacs

To protect important buffers from accidental killing, use the following forms in XEmacs:

    (setq permanent-buffers-alist 
          '(("*scratch*" (lisp-interaction-mode))))
    (permanent-buffers-mode t)

Protecting Buffers in GNU Emacs

For GNU Emacs you can use protbuf.el [1] by NoahFriedman like so:

    (require 'protbuf)
    (protect-buffer-from-kill-mode nil (get-buffer "*scratch*"))

For another way to auto-protect buffers with certain names, see ProtBufByName, an add-on for ProtBuf.

Killing Protected Buffers

In case you need a function to kill a buffer protected by protbuf.el, here is one:

(defun kill-protected-buffer (&optional buffer-or-name)
  "Kill a buffer, overriding the protection granted by protbuf.el"
  (interactive (list (get-buffer (read-buffer "Kill buffer: " (current-buffer) 'existing))))
  (message "Killing buffer %s, overriding protections." 
           (buffer-name buffer-or-name))
  (protect-buffer-from-kill-mode nil buffer-or-name)
  ;; Also disable by-name protection
  (let ((protect-buffer-names) (protect-buffer-matches)
        (protect-process-buffer-names) (protect-process-buffer-matches))
    (kill-buffer buffer-or-name)))

This function also works with protbuf-by-name.el.

keep-buffers

github

  * Simpler and more robust than above.
  * Protect buffers by regexp.
  * Protected buffers can be buried when killed or have their contents erased prior to burial.  Erasure can be undone. 

It’s like 10 lines of real code.


CategoryBufferSwitching