1;;; loadhist.el --- lisp functions for working with feature groups  -*- lexical-binding: t -*-
2
3;; Copyright (C) 1995, 1998, 2000-2021 Free Software Foundation, Inc.
4
5;; Author: Eric S. Raymond <esr@snark.thyrsus.com>
6;; Maintainer: emacs-devel@gnu.org
7;; Keywords: internal
8
9;; This file is part of GNU Emacs.
10
11;; GNU Emacs is free software: you can redistribute it and/or modify
12;; it under the terms of the GNU General Public License as published by
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
15
16;; GNU Emacs is distributed in the hope that it will be useful,
17;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19;; GNU General Public License for more details.
20
21;; You should have received a copy of the GNU General Public License
22;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23
24;;; Commentary:
25
26;; These functions exploit the load-history system variable.
27;; Entry points include `unload-feature', `symbol-file', and
28;; `feature-file', documented in the Emacs Lisp manual.
29
30;;; Code:
31
32(eval-when-compile (require 'cl-lib))
33
34(defun feature-symbols (feature)
35  "Return the file and list of definitions associated with FEATURE.
36The value is actually the element of `load-history'
37for the file that did (provide FEATURE)."
38  (catch 'foundit
39    (let ((element (cons 'provide feature)))
40      (dolist (x load-history nil)
41	(when (member element (cdr x))
42	  (throw 'foundit x))))))
43
44(defun feature-file (feature)
45  "Return the file name from which a given FEATURE was loaded.
46Actually, return the load argument, if any; this is sometimes the name of a
47Lisp file without an extension.  If the feature came from an `eval-buffer' on
48a buffer with no associated file, or an `eval-region', return nil."
49  (if (not (featurep feature))
50      (error "%S is not a currently loaded feature" feature)
51    (car (feature-symbols feature))))
52
53(defun file-loadhist-lookup (file)
54  "Return the `load-history' element for FILE.
55FILE can be a file name, or a library name.
56A library name is equivalent to the file name that `load-library' would load."
57  ;; First look for FILE as given.
58  (let ((symbols (assoc file load-history)))
59    ;; Try converting a library name to an absolute file name.
60    (and (null symbols)
61	 (let ((absname
62		(locate-file file load-path (get-load-suffixes))))
63	   (and absname (not (equal absname file))
64		(setq symbols (cdr (assoc absname load-history))))))
65    symbols))
66
67(defun file-provides (file)
68  "Return the list of features provided by FILE as it was loaded.
69FILE can be a file name, or a library name.
70A library name is equivalent to the file name that `load-library' would load."
71  (let (provides)
72    (dolist (x (file-loadhist-lookup file) provides)
73      (when (eq (car-safe x) 'provide)
74	(push (cdr x) provides)))))
75
76(defun file-requires (file)
77  "Return the list of features required by FILE as it was loaded.
78FILE can be a file name, or a library name.
79A library name is equivalent to the file name that `load-library' would load."
80  (let (requires)
81    (dolist (x (file-loadhist-lookup file) requires)
82      (when (eq (car-safe x) 'require)
83	(push (cdr x) requires)))))
84
85(defun file-dependents (file)
86  "Return the list of loaded libraries that depend on FILE.
87This can include FILE itself.
88FILE can be a file name, or a library name.
89A library name is equivalent to the file name that `load-library' would load."
90  (let ((provides (file-provides file))
91	(dependents nil))
92    (dolist (x load-history dependents)
93      (when (and (stringp (car x))
94                 (seq-intersection provides (file-requires (car x)) #'eq))
95	(push (car x) dependents)))))
96
97(defun read-feature (prompt &optional loaded-p)
98  "Read feature name from the minibuffer, prompting with string PROMPT.
99If optional second arg LOADED-P is non-nil, the feature must be loaded
100from a file."
101  (intern (completing-read
102           prompt
103           (mapcar #'symbol-name
104                   (if loaded-p
105                       (delq nil
106                             (mapcar
107                              (lambda (x) (and (feature-file x) x))
108                              features))
109                     features)))))
110
111(defvaralias 'loadhist-hook-functions 'unload-feature-special-hooks)
112(defvar unload-feature-special-hooks
113  '(after-change-functions after-insert-file-functions
114    after-make-frame-functions auto-coding-functions
115    auto-fill-function before-change-functions
116    blink-paren-function buffer-access-fontify-functions
117    choose-completion-string-functions
118    comint-output-filter-functions command-line-functions
119    comment-indent-function compilation-finish-functions
120    delete-frame-functions disabled-command-function
121    fill-nobreak-predicate find-directory-functions
122    find-file-not-found-functions
123    font-lock-fontify-buffer-function
124    font-lock-fontify-region-function
125    font-lock-mark-block-function
126    font-lock-syntactic-face-function
127    font-lock-unfontify-buffer-function
128    font-lock-unfontify-region-function
129    kill-buffer-query-functions kill-emacs-query-functions
130    lisp-indent-function mouse-position-function
131    redisplay-end-trigger-functions suspend-tty-functions
132    temp-buffer-show-function window-scroll-functions
133    window-size-change-functions write-contents-functions
134    write-file-functions write-region-annotate-functions)
135  "A list of special hooks from Info node `(elisp)Standard Hooks'.
136
137These are symbols with hooklike values whose names don't end in
138`-hook' or `-hooks', from which `unload-feature' should try to remove
139pertinent symbols.")
140
141(defvar unload-function-defs-list nil
142  "List of definitions in the Lisp library being unloaded.
143
144This is meant to be used by `FEATURE-unload-function'; see the
145documentation of `unload-feature' for details.")
146
147(defun unload--set-major-mode ()
148  (save-current-buffer
149    (dolist (buffer (buffer-list))
150      (set-buffer buffer)
151      (let ((proposed major-mode))
152        ;; Look for a predecessor mode not defined in the feature we're processing
153        (while (and proposed (rassq proposed unload-function-defs-list))
154          (setq proposed (get proposed 'derived-mode-parent)))
155        (unless (eq proposed major-mode)
156          ;; Two cases: either proposed is nil, and we want to switch to fundamental
157          ;; mode, or proposed is not nil and not major-mode, and so we use it.
158          (funcall (or proposed 'fundamental-mode)))))))
159
160(cl-defgeneric loadhist-unload-element (x)
161  "Unload an element from the `load-history'."
162  (message "Unexpected element %S in load-history" x))
163
164;; In `load-history', the definition of a previously autoloaded
165;; function is represented by 2 entries: (t . SYMBOL) comes before
166;; (defun . SYMBOL) and says we should restore SYMBOL's autoload when
167;; we undefine it.
168;; So we use this auxiliary variable to keep track of the last (t . SYMBOL)
169;; that occurred.
170(defvar loadhist--restore-autoload nil
171  "If non-nil, is a symbol for which to try to restore a previous autoload.")
172
173(cl-defmethod loadhist-unload-element ((x (head t)))
174  (setq loadhist--restore-autoload (cdr x)))
175
176(defun loadhist--unload-function (x)
177  (let ((fun (cdr x)))
178    (when (fboundp fun)
179      (when (fboundp 'ad-unadvise)
180	(ad-unadvise fun))
181      (let ((aload (get fun 'autoload)))
182	(defalias fun
183          (if (and aload (eq fun loadhist--restore-autoload))
184	      (cons 'autoload aload)
185            nil)))))
186  (setq loadhist--restore-autoload nil))
187
188(cl-defmethod loadhist-unload-element ((x (head defun)))
189  (loadhist--unload-function x))
190(cl-defmethod loadhist-unload-element ((x (head autoload)))
191  (loadhist--unload-function x))
192
193(cl-defmethod loadhist-unload-element ((_ (head require))) nil)
194(cl-defmethod loadhist-unload-element ((_ (head defface))) nil)
195
196(cl-defmethod loadhist-unload-element ((x (head provide)))
197  ;; Remove any feature names that this file provided.
198  (setq features (delq (cdr x) features)))
199
200(cl-defmethod loadhist-unload-element ((x symbol))
201  ;; Kill local values as much as possible.
202  (dolist (buf (buffer-list))
203    (with-current-buffer buf
204      (if (and (boundp x) (timerp (symbol-value x)))
205	  (cancel-timer (symbol-value x)))
206      (kill-local-variable x)))
207  (if (and (boundp x) (timerp (symbol-value x)))
208      (cancel-timer (symbol-value x)))
209  ;; Get rid of the default binding if we can.
210  (unless (local-variable-if-set-p x)
211    (makunbound x)))
212
213(cl-defmethod loadhist-unload-element ((x (head define-type)))
214  (let* ((name (cdr x)))
215    ;; Remove the struct.
216    (setf (cl--find-class name) nil)))
217
218(cl-defmethod loadhist-unload-element ((x (head define-symbol-props)))
219  (pcase-dolist (`(,symbol . ,props) (cdr x))
220    (dolist (prop props)
221      (put symbol prop nil))))
222
223;;;###autoload
224(defun unload-feature (feature &optional force)
225  "Unload the library that provided FEATURE.
226If the feature is required by any other loaded code, and prefix arg FORCE
227is nil, raise an error.
228
229Standard unloading activities include restoring old autoloads for
230functions defined by the library, removing such functions from
231hooks and `auto-mode-alist', undoing their ELP profiling,
232unproviding any features provided by the library, and canceling
233timers held in variables defined by the library.
234
235If a function `FEATURE-unload-function' is defined, this function
236calls it with no arguments, before doing anything else.  That function
237can do whatever is appropriate to undo the loading of the library.  If
238`FEATURE-unload-function' returns non-nil, that suppresses the
239standard unloading of the library.  Otherwise the standard unloading
240proceeds.
241
242`FEATURE-unload-function' has access to the package's list of
243definitions in the variable `unload-function-defs-list' and could
244remove symbols from it in the event that the package has done
245something strange, such as redefining an Emacs function."
246  (interactive
247   (list
248    (read-feature "Unload feature: " t)
249    current-prefix-arg))
250  (unless (featurep feature)
251    (error "%s is not a currently loaded feature" (symbol-name feature)))
252  (unless force
253    (let* ((file (feature-file feature))
254	   (dependents (delete file (copy-sequence (file-dependents file)))))
255      (when dependents
256	(error "Loaded libraries %s depend on %s"
257	       (prin1-to-string dependents) file))))
258  (let* ((unload-function-defs-list (feature-symbols feature))
259         (file (pop unload-function-defs-list))
260	 (name (symbol-name feature))
261         (unload-hook (intern-soft (concat name "-unload-hook")))
262	 (unload-func (intern-soft (concat name "-unload-function"))))
263    ;; If FEATURE-unload-function is defined and returns non-nil,
264    ;; don't try to do anything more; otherwise proceed normally.
265    (unless (and (fboundp unload-func)
266		 (funcall unload-func))
267      ;; Try to avoid losing badly when hooks installed in critical
268      ;; places go away.  (Some packages install things on
269      ;; `kill-buffer-hook', `activate-menubar-hook' and the like.)
270      (if unload-hook
271	  ;; First off, provide a clean way for package FOO to arrange
272	  ;; this by adding hooks on the variable `FOO-unload-hook'.
273	  ;; This is obsolete; FEATURE-unload-function should be used now.
274	  (run-hooks unload-hook)
275	;; Otherwise, do our best.  Look through the obarray for symbols
276	;; which seem to be hook variables or special hook functions and
277	;; remove anything from them which matches the feature-symbols
278	;; about to get zapped.  Obviously this won't get anonymous
279	;; functions which the package might just have installed, and
280	;; there might be other important state, but this tactic
281	;; normally works.
282        (let ((removables (cl-loop for def in unload-function-defs-list
283                                   when (and (eq (car-safe def) 'defun)
284                                             (not (get (cdr def) 'autoload)))
285                                   collect (cdr def))))
286          (mapatoms
287	   (lambda (x)
288	     (when (and (boundp x)
289		        (or (and (consp (symbol-value x)) ; Random hooks.
290			         (string-match "-hooks?\\'" (symbol-name x)))
291                            ;; Known abnormal hooks etc.
292			    (memq x unload-feature-special-hooks)))
293	       (dolist (func removables)
294	         (remove-hook x func)))))
295          (save-current-buffer
296            (dolist (buffer (buffer-list))
297              (pcase-dolist (`(,sym . ,val) (buffer-local-variables buffer))
298                (when (or (and (consp val)
299                               (string-match "-hooks?\\'" (symbol-name sym)))
300                          (memq sym unload-feature-special-hooks))
301                  (set-buffer buffer)
302                  (dolist (func removables)
303                    (remove-hook sym func t))))))
304          ;; Remove any feature-symbols from auto-mode-alist as well.
305          (dolist (func removables)
306            (setq auto-mode-alist
307                  (rassq-delete-all func auto-mode-alist)))))
308
309      ;; Change major mode in all buffers using one defined in the feature being unloaded.
310      (unload--set-major-mode)
311
312      (mapc #'loadhist-unload-element unload-function-defs-list)
313      ;; Delete the load-history element for this file.
314      (setq load-history (delq (assoc file load-history) load-history))))
315  ;; Don't return load-history, it is not useful.
316  nil)
317
318;; Obsolete.
319
320(defsubst file-set-intersect (p q)
321  "Return the set intersection of two lists."
322  (declare (obsolete seq-intersection "28.1"))
323  (nreverse (seq-intersection p q #'eq)))
324
325(provide 'loadhist)
326
327;;; loadhist.el ends here
328