From 91189839ab886c5bae07c7deab6a2384f5a37771 Mon Sep 17 00:00:00 2001 From: JSDurand Date: Fri, 18 Nov 2022 13:53:16 +0800 Subject: basic: clear invisible buffers One day I found that my Emacs had accumulated a bunch of invisible buffers. So I want to make sure I have a convenient way to clean up invisible buffers easily, once the need arises. * basic.el (durand-invisible-buffer-unsafe-regex): A regular expression that matches some buffers that are not to be killed automatically. (durand-clear-invisible-buffers): Kill invisible buffers that are not important. (global-map): Bind the function to "C-c k". --- basic.el | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/basic.el b/basic.el index aa087f1..60d8dd2 100644 --- a/basic.el +++ b/basic.el @@ -199,6 +199,8 @@ This will maintain the frame's width and height as well." ;;; display-buffer-alist +(require 'rx) + (setq display-buffer-alist `((,(rx (seq bos "*Help*" eos)) (display-buffer-in-side-window) @@ -564,6 +566,41 @@ left. --- 2022-11-17 22:56:20.746698" (advice-add #'read-buffer-to-switch :override #'durand-read-buffer-to-switch) +;;; Clear invisible buffers + +(defvar durand-invisible-buffer-unsafe-regex + (rx-to-string '(or + "Minibuf" + "Echo Area" + "code-conversion-work" + "code-converting-work" + "address") + t) + "I do not want to kill some invisible buffers. +This variable is a regular expression that should match those +buffers that I do not want to kill automatically.") + +(defun durand-clear-invisible-buffers () + "Kill invisible buffers that are not known to be safe to kill." + (interactive) + (let ((count 0)) + (mapc + (lambda (buffer) + (let ((name (buffer-name buffer)) + (inhibit-changing-match-data t)) + (cond + ;; ignore non-invisible buffers + ((or (= (length name) 0) (not (= (aref name 0) 32)))) + ;; ignore some "potentially unsafe" buffers + ((string-match durand-invisible-buffer-unsafe-regex name)) + ;; ignore buffers that are associated with live processes + ((get-buffer-process buffer)) + ((setq count (1+ count)) (kill-buffer buffer))))) + (buffer-list)) + (message "Cleared %d invisible buffers" count))) + +(define-key global-map (vector 3 ?k) #'durand-clear-invisible-buffers) + ;;; Save close ;;;###autoload -- cgit v1.2.3-18-g5258