Subject: bug#41868: [PATCH] Add project-clean-up command

From: "Philip K." <[email-masked]>
Date: Mon, 15 Jun 2020 12:00:56 +0200

Hi,

I wanted to propose a command for project.el to kill all opened buffers
in a project, called when one finishes working on some specific
code-base. I gave it the name "project-clean-up", but maybe it should be
renamed? I have been using it in my local emacs branch for about a week,
and have found it to be useful.

One issue I ran into is that a buffer might be falsely associated with a
project, such as *Help*. That's why I added an user option
project-dont-clean-regexps to contain a list of regular expression of
what buffer names to spare. The reason I couldn't just stick to checking
the value of buffer-file-name is that Dired, VC, etc. buffers don't get
recognized. There might be a better way to do this, but I'm not sure if
it's worth the effort.

And it might be worth considering to add a prompt, to ask the user if
they actually want to kill all the buffers.

-- 
	Philip K.

>From d7d4127cc561b3f2d1650d19a3fb58895a4cabd1 Mon Sep 17 00:00:00 2001
From: Philip K <[email-masked]>
Date: Fri, 12 Jun 2020 23:37:51 +0200
Subject: [PATCH] Add project-clean-up command

---
 lisp/progmodes/project.el | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)

diff --git a/lisp/progmodes/project.el b/lisp/progmodes/project.el
index f3df44fa7b..9e55f3594c 100644
--- a/lisp/progmodes/project.el
+++ b/lisp/progmodes/project.el
@@ -744,6 +744,35 @@ project-compile
          (default-directory (project-root pr)))
     (compile command comint)))
 
+(defcustom project-dont-clean-regexps
+  '("\\*Help\\*")
+  "List of regular expressions to be ignored by `project-clean-up'."
+  :type '(repeat regexp))
+
+(defun project--list-buffers (pr)
+  "Return a list of all buffers in project PR."
+  (let ((root (project-root pr))
+        bufs)
+    (dolist (buf (buffer-list))
+      (when-let* ((path (or (buffer-file-name buf)
+                            (buffer-local-value 'default-directory buf)))
+                  (true (file-truename path)))
+        (when (file-in-directory-p true root)
+          (push buf bufs))))
+    bufs))
+
+;;;###autoload
+(defun project-clean-up ()
+  "Kill all opened buffers in a project."
+  (interactive)
+  (let* ((pr (project-current t)))
+    (dolist (buf (project--list-buffers pr))
+      (let ((match (mapcar (lambda (re)
+                             (and (string-match-p re (buffer-name buf)) t))
+                           project-dont-clean-regexps)))
+        (unless (memq t match)
+          (kill-buffer buf))))))
+
 
 ;;; Project list
 
-- 
2.20.1