Mark buffers in region in ibuffer

2015-12-01 • 1 min read • Tags: Comp Emacs Funprog

EDIT: emacs-25 is patched accordingly.

Using desktop-save-mode in emacs, I usually end up with tens and tens of open buffers after a long period, 100+ this time.

When cleaning up a bit, I want to select a region of buffers, and then mark them for deletion. Unfortunately, and although there is a vast variety of methods for selecting buffers in ibuffer, there is no such shortcut.

So here is my first attempt:

(defun ibuffer-mark-region (start end)
  "Mark buffers in region"
  (interactive "r")
  (ibuffer-assert-ibuffer-mode)
  (if (use-region-p)
      (progn
        (goto-char start)
        (while (< (point) end)
          (ibuffer-mark-forward 1)))
    (ibuffer-mark-forward 1)))
(define-key ibuffer-mode-map (kbd "m") 'ibuffer-mark-region)

In a second attempt, I also added the ability to delete (kill) buffers selected in the region:

(defun ibuffer-mark-region (start end)
  "Mark buffers in region"
  (interactive "r")
  (ibuffer-mark-region-with-char start end ibuffer-marked-char))

(defun ibuffer-mark-region-for-delete (start end)
  "Mark buffers in region for deletion"
  (interactive "r")
  (ibuffer-mark-region-with-char start end ibuffer-deletion-char))

(defun ibuffer-mark-region-with-char (start end mark-char)
  (if (use-region-p)
      (progn
        (goto-char start)
        (while (< (point)  end)
          (ibuffer-mark-interactive 1 mark-char 1)))
    (ibuffer-mark-interactive 1 mark-char 1)))

(define-key ibuffer-mode-map (kbd "m") 'ibuffer-mark-region)
(define-key ibuffer-mode-map (kbd "d") 'ibuffer-mark-region-for-delete)