* lisp/emacs-lisp/nadvice.el (advice--member-p): Return the advice if found.
[bpt/emacs.git] / lisp / emacs-lisp / nadvice.el
CommitLineData
231d8498
SM
1;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
2
09b8afb6 3;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
231d8498
SM
4
5;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6;; Keywords: extensions, lisp, tools
7;; Package: emacs
8
9;; This program is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation, either version 3 of the License, or
12;; (at your option) any later version.
13
14;; This program is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
18
19;; You should have received a copy of the GNU General Public License
20;; along with this program. If not, see <http://www.gnu.org/licenses/>.
21
22;;; Commentary:
23
24;; This package lets you add behavior (which we call "piece of advice") to
25;; existing functions, like the old `advice.el' package, but with much fewer
8725b746 26;; bells and whistles. It comes in 2 parts:
231d8498
SM
27;;
28;; - The first part lets you add/remove functions, similarly to
29;; add/remove-hook, from any "place" (i.e. as accepted by `setf') that
30;; holds a function.
31;; This part provides mainly 2 macros: `add-function' and `remove-function'.
32;;
a77b8d5e 33;; - The second part provides `advice-add' and `advice-remove' which are
231d8498
SM
34;; refined version of the previous macros specially tailored for the case
35;; where the place that we want to modify is a `symbol-function'.
36
37;;; Code:
38
39;;;; Lightweight advice/hook
40(defvar advice--where-alist
41 '((:around "\300\301\302\003#\207" 5)
42 (:before "\300\301\002\"\210\300\302\002\"\207" 4)
43 (:after "\300\302\002\"\300\301\003\"\210\207" 5)
bcd7a0a4 44 (:override "\300\301\ 2\"\207" 4)
231d8498
SM
45 (:after-until "\300\302\002\"\206\013\000\300\301\002\"\207" 4)
46 (:after-while "\300\302\002\"\205\013\000\300\301\002\"\207" 4)
47 (:before-until "\300\301\002\"\206\013\000\300\302\002\"\207" 4)
d36ed1c8
SM
48 (:before-while "\300\301\002\"\205\013\000\300\302\002\"\207" 4)
49 (:filter-args "\300\302\301\ 3!\"\207" 5)
50 (:filter-return "\301\300\302\ 3\"!\207" 5))
231d8498
SM
51 "List of descriptions of how to add a function.
52Each element has the form (WHERE BYTECODE STACK) where:
53 WHERE is a keyword indicating where the function is added.
54 BYTECODE is the corresponding byte-code that will be used.
55 STACK is the amount of stack space needed by the byte-code.")
56
57(defvar advice--bytecodes (mapcar #'cadr advice--where-alist))
58
59(defun advice--p (object)
60 (and (byte-code-function-p object)
61 (eq 128 (aref object 0))
62 (memq (length object) '(5 6))
63 (memq (aref object 1) advice--bytecodes)
64 (eq #'apply (aref (aref object 2) 0))))
65
66(defsubst advice--car (f) (aref (aref f 2) 1))
67(defsubst advice--cdr (f) (aref (aref f 2) 2))
68(defsubst advice--props (f) (aref (aref f 2) 3))
69
70(defun advice--make-docstring (_string function)
71 "Build the raw doc-string of SYMBOL, presumably advised."
72 (let ((flist (indirect-function function))
73 (docstring nil))
74 (if (eq 'macro (car-safe flist)) (setq flist (cdr flist)))
75 (while (advice--p flist)
76 (let ((bytecode (aref flist 1))
77 (where nil))
78 (dolist (elem advice--where-alist)
79 (if (eq bytecode (cadr elem)) (setq where (car elem))))
80 (setq docstring
81 (concat
82 docstring
83 (propertize (format "%s advice: " where)
84 'face 'warning)
85 (let ((fun (advice--car flist)))
86 (if (symbolp fun) (format "`%S'" fun)
87 (let* ((name (cdr (assq 'name (advice--props flist))))
88 (doc (documentation fun t))
89 (usage (help-split-fundoc doc function)))
90 (if usage (setq doc (cdr usage)))
91 (if name
92 (if doc
93 (format "%s\n%s" name doc)
94 (format "%s" name))
95 (or doc "No documentation")))))
96 "\n")))
97 (setq flist (advice--cdr flist)))
98 (if docstring (setq docstring (concat docstring "\n")))
99 (let* ((origdoc (unless (eq function flist) ;Avoid inf-loops.
100 (documentation flist t)))
101 (usage (help-split-fundoc origdoc function)))
102 (setq usage (if (null usage)
103 (let ((arglist (help-function-arglist flist)))
104 (format "%S" (help-make-usage function arglist)))
105 (setq origdoc (cdr usage)) (car usage)))
106 (help-add-fundoc-usage (concat docstring origdoc) usage))))
107
108(defvar advice--docstring
109 ;; Can't eval-when-compile nor use defconst because it then gets pure-copied,
110 ;; which drops the text-properties.
111 ;;(eval-when-compile
112 (propertize "Advised function"
113 'dynamic-docstring-function #'advice--make-docstring)) ;; )
114
1668ea90
SM
115(defun advice-eval-interactive-spec (spec)
116 "Evaluate the interactive spec SPEC."
117 (cond
118 ((stringp spec)
119 ;; There's no direct access to the C code (in call-interactively) that
120 ;; processes those specs, but that shouldn't stop us, should it?
121 ;; FIXME: Despite appearances, this is not faithful: SPEC and
122 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
123 ;; command-history (and maybe a few other details).
124 (call-interactively `(lambda (&rest args) (interactive ,spec) args)))
125 ;; ((functionp spec) (funcall spec))
126 (t (eval spec))))
127
231d8498 128(defun advice--make-interactive-form (function main)
231d8498
SM
129 ;; TODO: make it so that interactive spec can be a constant which
130 ;; dynamically checks the advice--car/cdr to do its job.
1668ea90
SM
131 ;; For that, advice-eval-interactive-spec needs to be more faithful.
132 ;; FIXME: The calls to interactive-form below load autoloaded functions
133 ;; too eagerly.
134 (let ((fspec (cadr (interactive-form function))))
47f01a8a 135 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
1668ea90
SM
136 (setq fspec (nth 1 fspec)))
137 (if (functionp fspec)
138 `(funcall ',fspec
139 ',(cadr (interactive-form main)))
231d8498 140 (cadr (or (interactive-form function)
1668ea90 141 (interactive-form main))))))
231d8498
SM
142
143(defsubst advice--make-1 (byte-code stack-depth function main props)
144 "Build a function value that adds FUNCTION to MAIN."
145 (let ((adv-sig (gethash main advertised-signature-table))
146 (advice
147 (apply #'make-byte-code 128 byte-code
148 (vector #'apply function main props) stack-depth
149 advice--docstring
150 (when (or (commandp function) (commandp main))
151 (list (advice--make-interactive-form
152 function main))))))
153 (when adv-sig (puthash advice adv-sig advertised-signature-table))
154 advice))
155
156(defun advice--make (where function main props)
157 "Build a function value that adds FUNCTION to MAIN at WHERE.
158WHERE is a symbol to select an entry in `advice--where-alist'."
159 (let ((desc (assq where advice--where-alist)))
160 (unless desc (error "Unknown add-function location `%S'" where))
161 (advice--make-1 (nth 1 desc) (nth 2 desc)
162 function main props)))
163
dabefae5 164(defun advice--member-p (function name definition)
231d8498
SM
165 (let ((found nil))
166 (while (and (not found) (advice--p definition))
167 (if (or (equal function (advice--car definition))
dabefae5
SM
168 (when name
169 (equal name (cdr (assq 'name (advice--props definition))))))
c67c0839 170 (setq found definition)
231d8498
SM
171 (setq definition (advice--cdr definition))))
172 found))
173
a731fc1b 174(defun advice--tweak (flist tweaker)
231d8498 175 (if (not (advice--p flist))
a731fc1b 176 (funcall tweaker nil flist nil)
231d8498 177 (let ((first (advice--car flist))
a731fc1b 178 (rest (advice--cdr flist))
231d8498 179 (props (advice--props flist)))
cb9c0a53
SM
180 (let ((val (funcall tweaker first rest props)))
181 (if val (car val)
a731fc1b
SM
182 (let ((nrest (advice--tweak rest tweaker)))
183 (if (eq rest nrest) flist
184 (advice--make-1 (aref flist 1) (aref flist 3)
cb9c0a53 185 first nrest props))))))))
a731fc1b
SM
186
187;;;###autoload
188(defun advice--remove-function (flist function)
189 (advice--tweak flist
190 (lambda (first rest props)
cb9c0a53
SM
191 (cond ((not first) rest)
192 ((or (equal function first)
a731fc1b 193 (equal function (cdr (assq 'name props))))
cb9c0a53 194 (list rest))))))
231d8498 195
a61428c4
SM
196(defvar advice--buffer-local-function-sample nil)
197
198(defun advice--set-buffer-local (var val)
199 (if (function-equal val advice--buffer-local-function-sample)
200 (kill-local-variable var)
201 (set (make-local-variable var) val)))
202
203;;;###autoload
204(defun advice--buffer-local (var)
205 "Buffer-local value of VAR, presumed to contain a function."
206 (declare (gv-setter advice--set-buffer-local))
207 (if (local-variable-p var) (symbol-value var)
208 (setq advice--buffer-local-function-sample
209 (lambda (&rest args) (apply (default-value var) args)))))
210
231d8498
SM
211;;;###autoload
212(defmacro add-function (where place function &optional props)
213 ;; TODO:
231d8498
SM
214 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
215 ;; and tracing want to stay first.
a61428c4 216 ;; - maybe let `where' specify some kind of predicate and use it
231d8498 217 ;; to implement things like mode-local or eieio-defmethod.
a61428c4
SM
218 ;; Of course, that only makes sense if the predicates of all advices can
219 ;; be combined and made more efficient.
231d8498
SM
220 ;; :before is like a normal add-hook on a normal hook.
221 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
222 ;; :before-until is like add-hook on run-hook-with-args-until-success.
223 ;; Same with :after-* but for (add-hook ... 'append).
224 "Add a piece of advice on the function stored at PLACE.
225FUNCTION describes the code to add. WHERE describes where to add it.
226WHERE can be explained by showing the resulting new function, as the
227result of combining FUNCTION and the previous value of PLACE, which we
228call OLDFUN here:
229`:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
230`:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
231`:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
bcd7a0a4 232`:override' (lambda (&rest r) (apply FUNCTION r))
231d8498
SM
233`:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
234`:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
235`:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
236`:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
d36ed1c8
SM
237`:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
238`:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
231d8498
SM
239If FUNCTION was already added, do nothing.
240PROPS is an alist of additional properties, among which the following have
241a special meaning:
1668ea90
SM
242- `name': a string or symbol. It can be used to refer to this piece of advice.
243
36c0a301
SM
244If PLACE is a simple variable, only its global value will be affected.
245Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
a61428c4 246
1668ea90
SM
247If one of FUNCTION or OLDFUN is interactive, then the resulting function
248is also interactive. There are 3 cases:
249- FUNCTION is not interactive: the interactive spec of OLDFUN is used.
250- The interactive spec of FUNCTION is itself a function: it should take one
251 argument (the interactive spec of OLDFUN, which it can pass to
252 `advice-eval-interactive-spec') and return the list of arguments to use.
253- Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
231d8498 254 (declare (debug t)) ;;(indent 2)
a61428c4
SM
255 (cond ((eq 'local (car-safe place))
256 (setq place `(advice--buffer-local ,@(cdr place))))
257 ((symbolp place)
36c0a301 258 (setq place `(default-value ',place))))
231d8498
SM
259 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
260
261;;;###autoload
262(defun advice--add-function (where ref function props)
c67c0839
SM
263 (let ((a (advice--member-p function (cdr (assq 'name props))
264 (gv-deref ref))))
265 (when a
266 ;; The advice is already present. Remove the old one, first.
267 (setf (gv-deref ref)
268 (advice--remove-function (gv-deref ref) (advice--car a))))
231d8498
SM
269 (setf (gv-deref ref)
270 (advice--make where function (gv-deref ref) props))))
271
bcd7a0a4 272;;;###autoload
231d8498
SM
273(defmacro remove-function (place function)
274 "Remove the FUNCTION piece of advice from PLACE.
275If FUNCTION was not added to PLACE, do nothing.
276Instead of FUNCTION being the actual function, it can also be the `name'
277of the piece of advice."
278 (declare (debug t))
a61428c4
SM
279 (cond ((eq 'local (car-safe place))
280 (setq place `(advice--buffer-local ,@(cdr place))))
281 ((symbolp place)
282 (error "Use (default-value '%S) or (local '%S)" place place)))
231d8498
SM
283 (gv-letplace (getter setter) place
284 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
285 `(unless (eq ,new ,getter) ,(funcall setter new)))))
286
287;;;; Specific application of add-function to `symbol-function' for advice.
288
289(defun advice--subst-main (old new)
a731fc1b
SM
290 (advice--tweak old
291 (lambda (first _rest _props) (if (not first) new))))
231d8498 292
413d4689
SM
293(defun advice--normalize (symbol def)
294 (cond
295 ((special-form-p def)
296 ;; Not worth the trouble trying to handle this, I think.
a77b8d5e 297 (error "advice-add failure: %S is a special form" symbol))
413d4689
SM
298 ((and (symbolp def)
299 (eq 'macro (car-safe (ignore-errors (indirect-function def)))))
300 (let ((newval (cons 'macro (cdr (indirect-function def)))))
301 (put symbol 'advice--saved-rewrite (cons def newval))
302 newval))
303 ;; `f' might be a pure (hence read-only) cons!
304 ((and (eq 'macro (car-safe def))
305 (not (ignore-errors (setcdr def (cdr def)) t)))
306 (cons 'macro (cdr def)))
307 (t def)))
308
309(defsubst advice--strip-macro (x)
310 (if (eq 'macro (car-safe x)) (cdr x) x))
311
231d8498 312(defun advice--defalias-fset (fsetfun symbol newdef)
413d4689
SM
313 (when (get symbol 'advice--saved-rewrite)
314 (put symbol 'advice--saved-rewrite nil))
315 (setq newdef (advice--normalize symbol newdef))
316 (let* ((olddef (advice--strip-macro
317 (if (fboundp symbol) (symbol-function symbol))))
231d8498
SM
318 (oldadv
319 (cond
413d4689
SM
320 ((null (get symbol 'advice--pending))
321 (or olddef
322 (progn
323 (message "Delayed advice activation failed for %s: no data"
324 symbol)
325 nil)))
326 ((or (not olddef) (autoloadp olddef))
327 (prog1 (get symbol 'advice--pending)
328 (put symbol 'advice--pending nil)))
231d8498
SM
329 (t (message "Dropping left-over advice--pending for %s" symbol)
330 (put symbol 'advice--pending nil)
331 olddef))))
413d4689
SM
332 (let* ((snewdef (advice--strip-macro newdef))
333 (snewadv (advice--subst-main oldadv snewdef)))
334 (funcall (or fsetfun #'fset) symbol
335 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))))
231d8498
SM
336
337
338;;;###autoload
339(defun advice-add (symbol where function &optional props)
340 "Like `add-function' but for the function named SYMBOL.
341Contrary to `add-function', this will properly handle the cases where SYMBOL
342is defined as a macro, alias, command, ..."
343 ;; TODO:
344 ;; - record the advice location, to display in describe-function.
345 ;; - change all defadvice in lisp/**/*.el.
346 ;; - rewrite advice.el on top of this.
347 ;; - obsolete advice.el.
413d4689
SM
348 (let* ((f (and (fboundp symbol) (symbol-function symbol)))
349 (nf (advice--normalize symbol f)))
350 (unless (eq f nf) ;; Most importantly, if nf == nil!
351 (fset symbol nf))
231d8498 352 (add-function where (cond
413d4689 353 ((eq (car-safe nf) 'macro) (cdr nf))
1668ea90
SM
354 ;; Reasons to delay installation of the advice:
355 ;; - If the function is not yet defined, installing
356 ;; the advice would affect `fboundp'ness.
357 ;; - If it's an autoloaded command,
358 ;; advice--make-interactive-form would end up
359 ;; loading the command eagerly.
360 ;; - `autoload' does nothing if the function is
361 ;; not an autoload or undefined.
362 ((or (not nf) (autoloadp nf))
231d8498
SM
363 (get symbol 'advice--pending))
364 (t (symbol-function symbol)))
365 function props)
366 (add-function :around (get symbol 'defalias-fset-function)
367 #'advice--defalias-fset))
368 nil)
369
370;;;###autoload
371(defun advice-remove (symbol function)
372 "Like `remove-function' but for the function named SYMBOL.
373Contrary to `remove-function', this will work also when SYMBOL is a macro
374and it will not signal an error if SYMBOL is not `fboundp'.
375Instead of the actual function to remove, FUNCTION can also be the `name'
376of the piece of advice."
377 (when (fboundp symbol)
378 (let ((f (symbol-function symbol)))
379 ;; Can't use the `if' place here, because the body is too large,
380 ;; resulting in use of code that only works with lexical-scoping.
381 (remove-function (if (eq (car-safe f) 'macro)
382 (cdr f)
383 (symbol-function symbol))
384 function)
385 (unless (advice--p
386 (if (eq (car-safe f) 'macro) (cdr f) (symbol-function symbol)))
413d4689 387 ;; Not advised any more.
231d8498
SM
388 (remove-function (get symbol 'defalias-fset-function)
389 #'advice--defalias-fset)
390 (if (eq (symbol-function symbol)
391 (cdr (get symbol 'advice--saved-rewrite)))
392 (fset symbol (car (get symbol 'advice--saved-rewrite))))))
393 nil))
394
395;; (defun advice-mapc (fun symbol)
396;; "Apply FUN to every function added as advice to SYMBOL.
397;; FUN is called with a two arguments: the function that was added, and the
398;; properties alist that was specified when it was added."
399;; (let ((def (or (get symbol 'advice--pending)
400;; (if (fboundp symbol) (symbol-function symbol)))))
401;; (while (advice--p def)
402;; (funcall fun (advice--car def) (advice--props def))
403;; (setq def (advice--cdr def)))))
404
405;;;###autoload
413d4689
SM
406(defun advice-member-p (advice function-name)
407 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
408Instead of ADVICE being the actual function, it can also be the `name'
231d8498 409of the piece of advice."
dabefae5 410 (advice--member-p advice advice
413d4689
SM
411 (or (get function-name 'advice--pending)
412 (advice--strip-macro
413 (if (fboundp function-name)
414 (symbol-function function-name))))))
231d8498 415
23ba2705
SM
416;; When code is advised, called-interactively-p needs to be taught to skip
417;; the advising frames.
418;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
419;; done from the advised function if the deepest advice is an around advice!
420;; In other cases (calls from an advice or calls from the advised function when
421;; the deepest advice is not an around advice), it should hopefully get
422;; it right.
423(add-hook 'called-interactively-p-functions
424 #'advice--called-interactively-skip)
425(defun advice--called-interactively-skip (origi frame1 frame2)
426 (let* ((i origi)
427 (get-next-frame
428 (lambda ()
429 (setq frame1 frame2)
430 (setq frame2 (internal--called-interactively-p--get-frame i))
431 ;; (message "Advice Frame %d = %S" i frame2)
432 (setq i (1+ i)))))
433 (when (and (eq (nth 1 frame2) 'apply)
434 (progn
435 (funcall get-next-frame)
436 (advice--p (indirect-function (nth 1 frame2)))))
437 (funcall get-next-frame)
438 ;; If we now have the symbol, this was the head advice and
439 ;; we're done.
440 (while (advice--p (nth 1 frame1))
441 ;; This was an inner advice called from some earlier advice.
442 ;; The stack frames look different depending on the particular
443 ;; kind of the earlier advice.
444 (let ((inneradvice (nth 1 frame1)))
445 (if (and (eq (nth 1 frame2) 'apply)
446 (progn
447 (funcall get-next-frame)
448 (advice--p (indirect-function
449 (nth 1 frame2)))))
450 ;; The earlier advice was something like a before/after
451 ;; advice where the "next" code is called directly by the
452 ;; advice--p object.
453 (funcall get-next-frame)
454 ;; It's apparently an around advice, where the "next" is
455 ;; called by the body of the advice in any way it sees fit,
456 ;; so we need to skip the frames of that body.
457 (while
458 (progn
459 (funcall get-next-frame)
460 (not (and (eq (nth 1 frame2) 'apply)
461 (eq (nth 3 frame2) inneradvice)))))
462 (funcall get-next-frame)
463 (funcall get-next-frame))))
464 (- i origi 1))))
465
231d8498
SM
466
467(provide 'nadvice)
468;;; nadvice.el ends here