Subject: [PATCH] Add option to kill a shell buffer when the process ends

From: Philip Kaludercic <[email-masked]>
Date: Sun, 15 May 2022 08:13:49 +0000

Tags: patch

The below patch adds an option that has a *shell* buffer automatically
killed when a shell process terminates.  I find this useful, because it
helps to avoid re-activating old shell buffers in the wrong
`default-directory'.  Eshell has a "similar" behaviour (setting aside
that it doesn't have an inferior process), but term doesn't.  If this
patch is merged, perhaps something similar for term could be done too?`

In GNU Emacs 29.0.50 (build 12, x86_64-pc-linux-gnu, GTK+ Version 2.24.33, cairo version 1.16.0)
 of 2022-05-11 built on icterid
Repository revision: 474241f356c638bfd8d4eecb7138e3af76a8c036
Repository branch: master
Windowing system distributor 'The X.Org Foundation', version 11.0.12011000
System Description: Debian GNU/Linux 11 (bullseye)

Configured using:
 'configure --with-tree-sitter'

>From 21962d1e55db25c3e31a7efc722f91667bcd2319 Mon Sep 17 00:00:00 2001
From: Philip Kaludercic <[email-masked]>
Date: Sun, 15 May 2022 02:09:46 +0200
Subject: [PATCH] Add option to kill a shell buffer when the process ends

* shell.el (shell-kill-buffer-on-quit): Add new option.
(shell): Respect `shell-kill-buffer-on-quit'.
---
 lisp/shell.el | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)

diff --git a/lisp/shell.el b/lisp/shell.el
index 47887433d9..d7d0c487a0 100644
--- a/lisp/shell.el
+++ b/lisp/shell.el
@@ -331,6 +331,12 @@ shell-has-auto-cd
   :group 'shell-directories
   :version "28.1")
 
+(defcustom shell-kill-buffer-on-quit t
+  "Kill shell buffer after the process terminates."
+  :type 'boolean
+  :group 'shell
+  :version "29.1")
+
 (defvar shell-mode-map
   (let ((map (make-sparse-keymap)))
     (define-key map "\C-c\C-f" 'shell-forward-command)
@@ -818,6 +824,16 @@ shell
           (with-temp-buffer
             (insert-file-contents startfile)
             (buffer-string)))))))
+  (when shell-kill-buffer-on-quit
+    (let* ((buffer (current-buffer))
+           (sentinel (process-sentinel (get-buffer-process buffer))))
+      (set-process-sentinel
+       (get-buffer-process (current-buffer))
+       (lambda (proc event)
+         (unless (buffer-live-p proc)
+           (kill-buffer buffer))
+         (when sentinel
+           (funcall sentinel proc event))))))
   buffer)
 
 ;;; Directory tracking
-- 
2.30.2