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