[gnu.emacs.bug] kill-buffer-hooks

mcgrath%paris.Berkeley.EDU@GINGER.BERKELEY.EDU (Roland McGrath) (11/27/89)

The following file implements kill-buffer-hooks, which get run when you kill a
buffer with kill-buffer.  I implemented this in the primitive for version 19,
but it just now occurred to me to do it in Lisp for version 18.

I use this kill-buffer hook always:

(defun save-if-necessary ()
  "Save the buffer if necessary and the user wants to."
  (let ((name (buffer-file-name)))
    (and name (buffer-modified-p)
	 (if (y-or-n-p (format "Save file %s? " name))
	     (save-buffer)
	   (set-buffer-modified-p nil)
	   (message "")			; Get rid of the question.
	   ))))

I also use a buffer-local kill-buffer hook installed by my gnus-Startup-hook to
run gnus-Group-exit when I kill the *Newsgroups* buffer, and one installed by
my mh-folder-mode-hook to kill the show-+FOLDER buffer when I kill the +FOLDER
buffer (since I don't like old buffers cluttering up my life).

This approach is more general than the modified enhanced kill-buffer recently
posted, and it has the advantage that it will be standard in version 19.

;;; Run hook functions when killing buffers.
;;;
;;; Copyright (C) 1989 Roland McGrath
;;;
;;; This program is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 1, or (at your option)
;;; any later version.
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; A copy of the GNU General Public License can be obtained from this
;;; program's author (send electronic mail to roland@ai.mit.edu) or from
;;; the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
;;; 02139, USA.
;;;
;;; Send bug reports to roland@ai.mit.edu.

;; To use this, just load it and set kill-buffer-hooks as desired.
;; You cannot autoload this file.

(defvar kill-buffer-hooks nil "\
*Hooks to run when a buffer is killed.
May be a function or a list of functions.  If it is a list,
each element is called in order.  Functions are called with
no arguments, with the buffer to be killed current.")

;; Rename the kill-buffer subr to basic-kill-buffer.
(let ((func (symbol-function 'kill-buffer)))
  (and (subrp func)
       (fset 'basic-kill-buffer func)))

(defun kill-buffer (buffer)
  (interactive "bKill buffer: ")
  (set-buffer buffer)
  (run-hooks 'kill-buffer-hooks)
  (basic-kill-buffer buffer))

(provide 'kill-buffer-hooks)