* doc/misc/efaq-w32.texi (Tramp ssh): Remove deleted tramp methods.
[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
ba318903 3;; Copyright (C) 2012-2014 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
0d53f628
CY
70(defun advice--make-docstring (function)
71 "Build the raw docstring for FUNCTION, presumably advised."
231d8498
SM
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
1668ea90
SM
108(defun advice-eval-interactive-spec (spec)
109 "Evaluate the interactive spec SPEC."
110 (cond
111 ((stringp spec)
112 ;; There's no direct access to the C code (in call-interactively) that
113 ;; processes those specs, but that shouldn't stop us, should it?
114 ;; FIXME: Despite appearances, this is not faithful: SPEC and
115 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
116 ;; command-history (and maybe a few other details).
117 (call-interactively `(lambda (&rest args) (interactive ,spec) args)))
118 ;; ((functionp spec) (funcall spec))
119 (t (eval spec))))
120
231d8498 121(defun advice--make-interactive-form (function main)
231d8498
SM
122 ;; TODO: make it so that interactive spec can be a constant which
123 ;; dynamically checks the advice--car/cdr to do its job.
1668ea90 124 ;; For that, advice-eval-interactive-spec needs to be more faithful.
1668ea90 125 (let ((fspec (cadr (interactive-form function))))
47f01a8a 126 (when (eq 'function (car-safe fspec)) ;; Macroexpanded lambda?
1668ea90
SM
127 (setq fspec (nth 1 fspec)))
128 (if (functionp fspec)
129 `(funcall ',fspec
130 ',(cadr (interactive-form main)))
231d8498 131 (cadr (or (interactive-form function)
1668ea90 132 (interactive-form main))))))
231d8498
SM
133
134(defsubst advice--make-1 (byte-code stack-depth function main props)
135 "Build a function value that adds FUNCTION to MAIN."
136 (let ((adv-sig (gethash main advertised-signature-table))
137 (advice
138 (apply #'make-byte-code 128 byte-code
139 (vector #'apply function main props) stack-depth
0d53f628 140 nil
cb3a1380
SM
141 (and (or (commandp function) (commandp main))
142 (not (and (symbolp main) ;; Don't autoload too eagerly!
143 (autoloadp (symbol-function main))))
144 (list (advice--make-interactive-form
145 function main))))))
231d8498
SM
146 (when adv-sig (puthash advice adv-sig advertised-signature-table))
147 advice))
148
149(defun advice--make (where function main props)
150 "Build a function value that adds FUNCTION to MAIN at WHERE.
151WHERE is a symbol to select an entry in `advice--where-alist'."
cb3a1380
SM
152 (let ((fd (or (cdr (assq 'depth props)) 0))
153 (md (if (advice--p main)
154 (or (cdr (assq 'depth (advice--props main))) 0))))
155 (if (and md (> fd md))
156 ;; `function' should go deeper.
157 (let ((rest (advice--make where function (advice--cdr main) props)))
158 (advice--make-1 (aref main 1) (aref main 3)
159 (advice--car main) rest (advice--props main)))
160 (let ((desc (assq where advice--where-alist)))
161 (unless desc (error "Unknown add-function location `%S'" where))
162 (advice--make-1 (nth 1 desc) (nth 2 desc)
163 function main props)))))
231d8498 164
dabefae5 165(defun advice--member-p (function name definition)
231d8498
SM
166 (let ((found nil))
167 (while (and (not found) (advice--p definition))
168 (if (or (equal function (advice--car definition))
dabefae5
SM
169 (when name
170 (equal name (cdr (assq 'name (advice--props definition))))))
c67c0839 171 (setq found definition)
231d8498
SM
172 (setq definition (advice--cdr definition))))
173 found))
174
a731fc1b 175(defun advice--tweak (flist tweaker)
231d8498 176 (if (not (advice--p flist))
a731fc1b 177 (funcall tweaker nil flist nil)
231d8498 178 (let ((first (advice--car flist))
a731fc1b 179 (rest (advice--cdr flist))
231d8498 180 (props (advice--props flist)))
cb9c0a53
SM
181 (let ((val (funcall tweaker first rest props)))
182 (if val (car val)
a731fc1b
SM
183 (let ((nrest (advice--tweak rest tweaker)))
184 (if (eq rest nrest) flist
185 (advice--make-1 (aref flist 1) (aref flist 3)
cb9c0a53 186 first nrest props))))))))
a731fc1b
SM
187
188;;;###autoload
189(defun advice--remove-function (flist function)
190 (advice--tweak flist
191 (lambda (first rest props)
cb9c0a53
SM
192 (cond ((not first) rest)
193 ((or (equal function first)
a731fc1b 194 (equal function (cdr (assq 'name props))))
cb9c0a53 195 (list rest))))))
231d8498 196
1d44e9dc
SM
197(defvar advice--buffer-local-function-sample nil
198 "keeps an example of the special \"run the default value\" functions.
199These functions play the same role as t in buffer-local hooks, and to recognize
200them, we keep a sample here against which to compare. Each instance is
201different, but `function-equal' will hopefully ignore those differences.")
a61428c4
SM
202
203(defun advice--set-buffer-local (var val)
204 (if (function-equal val advice--buffer-local-function-sample)
205 (kill-local-variable var)
206 (set (make-local-variable var) val)))
207
208;;;###autoload
209(defun advice--buffer-local (var)
210 "Buffer-local value of VAR, presumed to contain a function."
211 (declare (gv-setter advice--set-buffer-local))
212 (if (local-variable-p var) (symbol-value var)
213 (setq advice--buffer-local-function-sample
1d44e9dc 214 ;; This function acts like the t special value in buffer-local hooks.
a61428c4
SM
215 (lambda (&rest args) (apply (default-value var) args)))))
216
231d8498
SM
217;;;###autoload
218(defmacro add-function (where place function &optional props)
219 ;; TODO:
a61428c4 220 ;; - maybe let `where' specify some kind of predicate and use it
231d8498 221 ;; to implement things like mode-local or eieio-defmethod.
a61428c4
SM
222 ;; Of course, that only makes sense if the predicates of all advices can
223 ;; be combined and made more efficient.
231d8498
SM
224 ;; :before is like a normal add-hook on a normal hook.
225 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
226 ;; :before-until is like add-hook on run-hook-with-args-until-success.
227 ;; Same with :after-* but for (add-hook ... 'append).
228 "Add a piece of advice on the function stored at PLACE.
229FUNCTION describes the code to add. WHERE describes where to add it.
230WHERE can be explained by showing the resulting new function, as the
231result of combining FUNCTION and the previous value of PLACE, which we
232call OLDFUN here:
233`:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
234`:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
235`:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
bcd7a0a4 236`:override' (lambda (&rest r) (apply FUNCTION r))
231d8498
SM
237`:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
238`:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
239`:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
240`:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
d36ed1c8
SM
241`:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
242`:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
231d8498
SM
243If FUNCTION was already added, do nothing.
244PROPS is an alist of additional properties, among which the following have
245a special meaning:
1668ea90 246- `name': a string or symbol. It can be used to refer to this piece of advice.
cb3a1380
SM
247- `depth': a number indicating a preference w.r.t ordering.
248 The default depth is 0. By convention, a depth of 100 means that
249 the advice should be innermost (i.e. at the end of the list),
250 whereas a depth of -100 means that the advice should be outermost.
1668ea90 251
36c0a301
SM
252If PLACE is a simple variable, only its global value will be affected.
253Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
a61428c4 254
1668ea90
SM
255If one of FUNCTION or OLDFUN is interactive, then the resulting function
256is also interactive. There are 3 cases:
257- FUNCTION is not interactive: the interactive spec of OLDFUN is used.
258- The interactive spec of FUNCTION is itself a function: it should take one
259 argument (the interactive spec of OLDFUN, which it can pass to
260 `advice-eval-interactive-spec') and return the list of arguments to use.
261- Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
231d8498 262 (declare (debug t)) ;;(indent 2)
a61428c4
SM
263 (cond ((eq 'local (car-safe place))
264 (setq place `(advice--buffer-local ,@(cdr place))))
265 ((symbolp place)
36c0a301 266 (setq place `(default-value ',place))))
231d8498
SM
267 `(advice--add-function ,where (gv-ref ,place) ,function ,props))
268
269;;;###autoload
270(defun advice--add-function (where ref function props)
c67c0839
SM
271 (let ((a (advice--member-p function (cdr (assq 'name props))
272 (gv-deref ref))))
273 (when a
274 ;; The advice is already present. Remove the old one, first.
275 (setf (gv-deref ref)
276 (advice--remove-function (gv-deref ref) (advice--car a))))
231d8498
SM
277 (setf (gv-deref ref)
278 (advice--make where function (gv-deref ref) props))))
279
bcd7a0a4 280;;;###autoload
231d8498
SM
281(defmacro remove-function (place function)
282 "Remove the FUNCTION piece of advice from PLACE.
283If FUNCTION was not added to PLACE, do nothing.
284Instead of FUNCTION being the actual function, it can also be the `name'
285of the piece of advice."
286 (declare (debug t))
a61428c4
SM
287 (cond ((eq 'local (car-safe place))
288 (setq place `(advice--buffer-local ,@(cdr place))))
289 ((symbolp place)
986545b5 290 (setq place `(default-value ',place))))
231d8498
SM
291 (gv-letplace (getter setter) place
292 (macroexp-let2 nil new `(advice--remove-function ,getter ,function)
293 `(unless (eq ,new ,getter) ,(funcall setter new)))))
294
1d44e9dc
SM
295(defun advice-function-mapc (f function-def)
296 "Apply F to every advice function in FUNCTION-DEF.
297F is called with two arguments: the function that was added, and the
298properties alist that was specified when it was added."
299 (while (advice--p function-def)
300 (funcall f (advice--car function-def) (advice--props function-def))
301 (setq function-def (advice--cdr function-def))))
302
303(defun advice-function-member-p (advice function-def)
304 "Return non-nil if ADVICE is already in FUNCTION-DEF.
305Instead of ADVICE being the actual function, it can also be the `name'
306of the piece of advice."
307 (advice--member-p advice advice function-def))
308
231d8498
SM
309;;;; Specific application of add-function to `symbol-function' for advice.
310
311(defun advice--subst-main (old new)
a731fc1b
SM
312 (advice--tweak old
313 (lambda (first _rest _props) (if (not first) new))))
231d8498 314
413d4689
SM
315(defun advice--normalize (symbol def)
316 (cond
317 ((special-form-p def)
318 ;; Not worth the trouble trying to handle this, I think.
1d44e9dc 319 (error "Advice impossible: %S is a special form" symbol))
671d5c16
SM
320 ((and (symbolp def) (macrop def))
321 (let ((newval `(macro . ,(lambda (&rest r) (macroexpand `(,def . ,r))))))
1d44e9dc 322 (put symbol 'advice--saved-rewrite (cons def (cdr newval)))
413d4689
SM
323 newval))
324 ;; `f' might be a pure (hence read-only) cons!
325 ((and (eq 'macro (car-safe def))
326 (not (ignore-errors (setcdr def (cdr def)) t)))
327 (cons 'macro (cdr def)))
328 (t def)))
329
330(defsubst advice--strip-macro (x)
331 (if (eq 'macro (car-safe x)) (cdr x) x))
332
1d44e9dc
SM
333(defun advice--symbol-function (symbol)
334 ;; The value conceptually stored in `symbol-function' is split into two
335 ;; parts:
336 ;; - the normal function definition.
337 ;; - the list of advice applied to it.
338 ;; `advice--symbol-function' is intended to return the second part (i.e. the
339 ;; list of advice, which includes a hole at the end which typically holds the
340 ;; first part, but this function doesn't care much which value is found
341 ;; there).
342 ;; In the "normal" state both parts are combined into a single value stored
343 ;; in the "function slot" of the symbol. But the way they are combined is
344 ;; different depending on whether the definition is a function or a macro.
345 ;; Also if the function definition is nil (i.e. unbound) or is an autoload,
346 ;; the second part is stashed away temporarily in the `advice--pending'
347 ;; symbol property.
348 (or (get symbol 'advice--pending)
349 (advice--strip-macro (symbol-function symbol))))
350
231d8498 351(defun advice--defalias-fset (fsetfun symbol newdef)
1d44e9dc 352 (unless fsetfun (setq fsetfun #'fset))
413d4689
SM
353 (when (get symbol 'advice--saved-rewrite)
354 (put symbol 'advice--saved-rewrite nil))
355 (setq newdef (advice--normalize symbol newdef))
671d5c16 356 (let ((oldadv (advice--symbol-function symbol)))
539f75f4
SM
357 (if (and newdef (not (autoloadp newdef)))
358 (let* ((snewdef (advice--strip-macro newdef))
359 (snewadv (advice--subst-main oldadv snewdef)))
360 (put symbol 'advice--pending nil)
1d44e9dc 361 (funcall fsetfun symbol
539f75f4
SM
362 (if (eq snewdef newdef) snewadv (cons 'macro snewadv))))
363 (unless (eq oldadv (get symbol 'advice--pending))
364 (put symbol 'advice--pending (advice--subst-main oldadv nil)))
1d44e9dc 365 (funcall fsetfun symbol newdef))))
231d8498
SM
366
367;;;###autoload
368(defun advice-add (symbol where function &optional props)
369 "Like `add-function' but for the function named SYMBOL.
370Contrary to `add-function', this will properly handle the cases where SYMBOL
371is defined as a macro, alias, command, ..."
372 ;; TODO:
373 ;; - record the advice location, to display in describe-function.
374 ;; - change all defadvice in lisp/**/*.el.
231d8498 375 ;; - obsolete advice.el.
539f75f4 376 (let* ((f (symbol-function symbol))
413d4689 377 (nf (advice--normalize symbol f)))
1d44e9dc 378 (unless (eq f nf) (fset symbol nf))
231d8498 379 (add-function where (cond
413d4689 380 ((eq (car-safe nf) 'macro) (cdr nf))
1668ea90
SM
381 ;; Reasons to delay installation of the advice:
382 ;; - If the function is not yet defined, installing
383 ;; the advice would affect `fboundp'ness.
384 ;; - If it's an autoloaded command,
385 ;; advice--make-interactive-form would end up
386 ;; loading the command eagerly.
387 ;; - `autoload' does nothing if the function is
388 ;; not an autoload or undefined.
389 ((or (not nf) (autoloadp nf))
231d8498
SM
390 (get symbol 'advice--pending))
391 (t (symbol-function symbol)))
392 function props)
0d53f628 393 (put symbol 'function-documentation `(advice--make-docstring ',symbol))
231d8498
SM
394 (add-function :around (get symbol 'defalias-fset-function)
395 #'advice--defalias-fset))
396 nil)
397
398;;;###autoload
399(defun advice-remove (symbol function)
400 "Like `remove-function' but for the function named SYMBOL.
539f75f4
SM
401Contrary to `remove-function', this also works when SYMBOL is a macro
402or an autoload and it preserves `fboundp'.
231d8498
SM
403Instead of the actual function to remove, FUNCTION can also be the `name'
404of the piece of advice."
539f75f4 405 (let ((f (symbol-function symbol)))
1d44e9dc
SM
406 (remove-function (cond ;This is `advice--symbol-function' but as a "place".
407 ((get symbol 'advice--pending)
408 (get symbol 'advice--pending))
409 ((eq (car-safe f) 'macro) (cdr f))
410 (t (symbol-function symbol)))
539f75f4 411 function)
671d5c16 412 (unless (advice--p (advice--symbol-function symbol))
539f75f4
SM
413 ;; Not advised any more.
414 (remove-function (get symbol 'defalias-fset-function)
415 #'advice--defalias-fset)
1d44e9dc
SM
416 (let ((asr (get symbol 'advice--saved-rewrite)))
417 (and asr (eq (cdr-safe (symbol-function symbol))
418 (cdr asr))
419 (fset symbol (car (get symbol 'advice--saved-rewrite)))))))
539f75f4
SM
420 nil)
421
1d44e9dc
SM
422(defun advice-mapc (fun symbol)
423 "Apply FUN to every advice function in SYMBOL.
539f75f4
SM
424FUN is called with a two arguments: the function that was added, and the
425properties alist that was specified when it was added."
1d44e9dc 426 (advice-function-mapc fun (advice--symbol-function symbol)))
231d8498
SM
427
428;;;###autoload
1d44e9dc
SM
429(defun advice-member-p (advice symbol)
430 "Return non-nil if ADVICE has been added to SYMBOL.
413d4689 431Instead of ADVICE being the actual function, it can also be the `name'
231d8498 432of the piece of advice."
1d44e9dc 433 (advice-function-member-p advice (advice--symbol-function symbol)))
231d8498 434
23ba2705
SM
435;; When code is advised, called-interactively-p needs to be taught to skip
436;; the advising frames.
437;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
438;; done from the advised function if the deepest advice is an around advice!
439;; In other cases (calls from an advice or calls from the advised function when
440;; the deepest advice is not an around advice), it should hopefully get
441;; it right.
442(add-hook 'called-interactively-p-functions
443 #'advice--called-interactively-skip)
444(defun advice--called-interactively-skip (origi frame1 frame2)
445 (let* ((i origi)
446 (get-next-frame
447 (lambda ()
448 (setq frame1 frame2)
7ced0d04 449 (setq frame2 (backtrace-frame i #'called-interactively-p))
23ba2705
SM
450 ;; (message "Advice Frame %d = %S" i frame2)
451 (setq i (1+ i)))))
452 (when (and (eq (nth 1 frame2) 'apply)
453 (progn
454 (funcall get-next-frame)
455 (advice--p (indirect-function (nth 1 frame2)))))
456 (funcall get-next-frame)
457 ;; If we now have the symbol, this was the head advice and
458 ;; we're done.
459 (while (advice--p (nth 1 frame1))
460 ;; This was an inner advice called from some earlier advice.
461 ;; The stack frames look different depending on the particular
462 ;; kind of the earlier advice.
463 (let ((inneradvice (nth 1 frame1)))
464 (if (and (eq (nth 1 frame2) 'apply)
465 (progn
466 (funcall get-next-frame)
467 (advice--p (indirect-function
468 (nth 1 frame2)))))
469 ;; The earlier advice was something like a before/after
470 ;; advice where the "next" code is called directly by the
471 ;; advice--p object.
472 (funcall get-next-frame)
473 ;; It's apparently an around advice, where the "next" is
474 ;; called by the body of the advice in any way it sees fit,
475 ;; so we need to skip the frames of that body.
476 (while
477 (progn
478 (funcall get-next-frame)
479 (not (and (eq (nth 1 frame2) 'apply)
480 (eq (nth 3 frame2) inneradvice)))))
481 (funcall get-next-frame)
482 (funcall get-next-frame))))
483 (- i origi 1))))
484
231d8498
SM
485
486(provide 'nadvice)
487;;; nadvice.el ends here