Protecting Emacs Buffers

A recent thread on Mastadon1 lead me to look at the built-in emacs-lock-mode package. This was added back in Emacs 24.1, but I already had implemented something similar and missed it.2

If you are not familiar with it, emacs-lock-mode allows you to lock a buffer in a couple ways:

  • Prevent the buffer from accidentally being killed.
  • Prevent Emacs from exiting while the buffer is locked.

My old buffer-protect package was written for the first case only. I occasionally would go in to ibuffer to clean up, and might accidentally mark and delete the scratch buffer or some other temporary buffer that had some useful text in it.

The built-in mode lets me drop this custom code and replace it with a little bit of configuration:

(use-package emacs-lock
  :config
  (with-current-buffer "*scratch*"
    (emacs-lock-mode 'kill)))

This locks the scratch buffer to keep it from being killed, but won’t block me from exiting Emacs. You can toggle the lock on any buffer with the command emacs-lock-mode. Use a prefix argument to choose the lock behavior, or customize the variable emacs-lock-default-locking-mode.

This lock mode is also nicely integrated with ibuffer. In my own buffer-protect code I’d had to advise some ibuffer functions to prevent them complaining if a protected buffer happened to be marked for deletion. With the built-in lock mode no such tweaking is needed:

  • Locked buffers are shown in the *IBuffer* list with an L annotation.
  • You can easily toggle the lock state on one or several buffers with L
  • If you happen to mark a locked buffer and try to delete it, ibuffer silently ignores the delete.

I don’t need emacs-lock-mode frequently enough to bind it to a key, but it’s nice to know it is there. And it is always nice to remove custom code from my configuration, particularly when the built-in equivalent is more tightly integrated with other tools like ibuffer.


  1. Thanks to @xenodium. Check out their blog on Emacs and other stuff. ↩︎

  2. For the last few releases, Mickey Petersen over at Mastering Emacs has been publishing an annotated version of the NEWS file with his comments and observations on what has changed. This is an excellent resource, highlighting new features you might have overlooked or implications of a change you might not think of. Check out his recent post on Emacs 29.1↩︎

Contents

@glucas on Mastodon