1 ;;; nadvice.el --- Light-weight advice primitives for Elisp functions -*- lexical-binding: t -*-
3 ;; Copyright (C) 2012-2013 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: extensions, lisp, tools
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/>.
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
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'.
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 (:after-until
"\300\302\002\"\206\013\000\300\301\002\"\207" 4)
45 (:after-while
"\300\302\002\"\205\013\000\300\301\002\"\207" 4)
46 (:before-until
"\300\301\002\"\206\013\000\300\302\002\"\207" 4)
47 (:before-while
"\300\301\002\"\205\013\000\300\302\002\"\207" 4)
48 (:filter-args
"\300\302\301\ 3!\"\207" 5)
49 (:filter-return
"\301\300\302\ 3\"!\207" 5))
50 "List of descriptions of how to add a function.
51 Each element has the form (WHERE BYTECODE STACK) where:
52 WHERE is a keyword indicating where the function is added.
53 BYTECODE is the corresponding byte-code that will be used.
54 STACK is the amount of stack space needed by the byte-code.")
56 (defvar advice--bytecodes
(mapcar #'cadr advice--where-alist
))
58 (defun advice--p (object)
59 (and (byte-code-function-p object
)
60 (eq 128 (aref object
0))
61 (memq (length object
) '(5 6))
62 (memq (aref object
1) advice--bytecodes
)
63 (eq #'apply
(aref (aref object
2) 0))))
65 (defsubst advice--car
(f) (aref (aref f
2) 1))
66 (defsubst advice--cdr
(f) (aref (aref f
2) 2))
67 (defsubst advice--props
(f) (aref (aref f
2) 3))
69 (defun advice--make-docstring (_string function
)
70 "Build the raw doc-string of SYMBOL, presumably advised."
71 (let ((flist (indirect-function function
))
73 (if (eq 'macro
(car-safe flist
)) (setq flist
(cdr flist
)))
74 (while (advice--p flist
)
75 (let ((bytecode (aref flist
1))
77 (dolist (elem advice--where-alist
)
78 (if (eq bytecode
(cadr elem
)) (setq where
(car elem
))))
82 (propertize (format "%s advice: " where
)
84 (let ((fun (advice--car flist
)))
85 (if (symbolp fun
) (format "`%S'" fun
)
86 (let* ((name (cdr (assq 'name
(advice--props flist
))))
87 (doc (documentation fun t
))
88 (usage (help-split-fundoc doc function
)))
89 (if usage
(setq doc
(cdr usage
)))
92 (format "%s\n%s" name doc
)
94 (or doc
"No documentation")))))
96 (setq flist
(advice--cdr flist
)))
97 (if docstring
(setq docstring
(concat docstring
"\n")))
98 (let* ((origdoc (unless (eq function flist
) ;Avoid inf-loops.
99 (documentation flist t
)))
100 (usage (help-split-fundoc origdoc function
)))
101 (setq usage
(if (null usage
)
102 (let ((arglist (help-function-arglist flist
)))
103 (format "%S" (help-make-usage function arglist
)))
104 (setq origdoc
(cdr usage
)) (car usage
)))
105 (help-add-fundoc-usage (concat docstring origdoc
) usage
))))
107 (defvar advice--docstring
108 ;; Can't eval-when-compile nor use defconst because it then gets pure-copied,
109 ;; which drops the text-properties.
111 (propertize "Advised function"
112 'dynamic-docstring-function
#'advice--make-docstring
)) ;; )
114 (defun advice-eval-interactive-spec (spec)
115 "Evaluate the interactive spec SPEC."
118 ;; There's no direct access to the C code (in call-interactively) that
119 ;; processes those specs, but that shouldn't stop us, should it?
120 ;; FIXME: Despite appearances, this is not faithful: SPEC and
121 ;; (advice-eval-interactive-spec SPEC) will behave subtly differently w.r.t
122 ;; command-history (and maybe a few other details).
123 (call-interactively `(lambda (&rest args
) (interactive ,spec
) args
)))
124 ;; ((functionp spec) (funcall spec))
127 (defun advice--make-interactive-form (function main
)
128 ;; TODO: make it so that interactive spec can be a constant which
129 ;; dynamically checks the advice--car/cdr to do its job.
130 ;; For that, advice-eval-interactive-spec needs to be more faithful.
131 ;; FIXME: The calls to interactive-form below load autoloaded functions
133 (let ((fspec (cadr (interactive-form function
))))
134 (when (eq 'function
(car-safe fspec
)) ;; Macroexpanded lambda?
135 (setq fspec
(nth 1 fspec
)))
136 (if (functionp fspec
)
138 ',(cadr (interactive-form main
)))
139 (cadr (or (interactive-form function
)
140 (interactive-form main
))))))
142 (defsubst advice--make-1
(byte-code stack-depth function main props
)
143 "Build a function value that adds FUNCTION to MAIN."
144 (let ((adv-sig (gethash main advertised-signature-table
))
146 (apply #'make-byte-code
128 byte-code
147 (vector #'apply function main props
) stack-depth
149 (when (or (commandp function
) (commandp main
))
150 (list (advice--make-interactive-form
152 (when adv-sig
(puthash advice adv-sig advertised-signature-table
))
155 (defun advice--make (where function main props
)
156 "Build a function value that adds FUNCTION to MAIN at WHERE.
157 WHERE is a symbol to select an entry in `advice--where-alist'."
158 (let ((desc (assq where advice--where-alist
)))
159 (unless desc
(error "Unknown add-function location `%S'" where
))
160 (advice--make-1 (nth 1 desc
) (nth 2 desc
)
161 function main props
)))
163 (defun advice--member-p (function name definition
)
165 (while (and (not found
) (advice--p definition
))
166 (if (or (equal function
(advice--car definition
))
168 (equal name
(cdr (assq 'name
(advice--props definition
))))))
170 (setq definition
(advice--cdr definition
))))
173 (defun advice--tweak (flist tweaker
)
174 (if (not (advice--p flist
))
175 (funcall tweaker nil flist nil
)
176 (let ((first (advice--car flist
))
177 (rest (advice--cdr flist
))
178 (props (advice--props flist
)))
179 (let ((val (funcall tweaker first rest props
)))
181 (let ((nrest (advice--tweak rest tweaker
)))
182 (if (eq rest nrest
) flist
183 (advice--make-1 (aref flist
1) (aref flist
3)
184 first nrest props
))))))))
187 (defun advice--remove-function (flist function
)
189 (lambda (first rest props
)
190 (cond ((not first
) rest
)
191 ((or (equal function first
)
192 (equal function
(cdr (assq 'name props
))))
195 (defvar advice--buffer-local-function-sample nil
)
197 (defun advice--set-buffer-local (var val
)
198 (if (function-equal val advice--buffer-local-function-sample
)
199 (kill-local-variable var
)
200 (set (make-local-variable var
) val
)))
203 (defun advice--buffer-local (var)
204 "Buffer-local value of VAR, presumed to contain a function."
205 (declare (gv-setter advice--set-buffer-local
))
206 (if (local-variable-p var
) (symbol-value var
)
207 (setq advice--buffer-local-function-sample
208 (lambda (&rest args
) (apply (default-value var
) args
)))))
211 (defmacro add-function
(where place function
&optional props
)
213 ;; - provide some kind of control over ordering. E.g. debug-on-entry, ELP
214 ;; and tracing want to stay first.
215 ;; - maybe let `where' specify some kind of predicate and use it
216 ;; to implement things like mode-local or eieio-defmethod.
217 ;; Of course, that only makes sense if the predicates of all advices can
218 ;; be combined and made more efficient.
219 ;; :before is like a normal add-hook on a normal hook.
220 ;; :before-while is like add-hook on run-hook-with-args-until-failure.
221 ;; :before-until is like add-hook on run-hook-with-args-until-success.
222 ;; Same with :after-* but for (add-hook ... 'append).
223 "Add a piece of advice on the function stored at PLACE.
224 FUNCTION describes the code to add. WHERE describes where to add it.
225 WHERE can be explained by showing the resulting new function, as the
226 result of combining FUNCTION and the previous value of PLACE, which we
228 `:before' (lambda (&rest r) (apply FUNCTION r) (apply OLDFUN r))
229 `:after' (lambda (&rest r) (prog1 (apply OLDFUN r) (apply FUNCTION r)))
230 `:around' (lambda (&rest r) (apply FUNCTION OLDFUN r))
231 `:before-while' (lambda (&rest r) (and (apply FUNCTION r) (apply OLDFUN r)))
232 `:before-until' (lambda (&rest r) (or (apply FUNCTION r) (apply OLDFUN r)))
233 `:after-while' (lambda (&rest r) (and (apply OLDFUN r) (apply FUNCTION r)))
234 `:after-until' (lambda (&rest r) (or (apply OLDFUN r) (apply FUNCTION r)))
235 `:filter-args' (lambda (&rest r) (apply OLDFUN (funcall FUNCTION r)))
236 `:filter-return'(lambda (&rest r) (funcall FUNCTION (apply OLDFUN r)))
237 If FUNCTION was already added, do nothing.
238 PROPS is an alist of additional properties, among which the following have
240 - `name': a string or symbol. It can be used to refer to this piece of advice.
242 If PLACE is a simple variable, only its global value will be affected.
243 Use (local 'VAR) if you want to apply FUNCTION to VAR buffer-locally.
245 If one of FUNCTION or OLDFUN is interactive, then the resulting function
246 is also interactive. There are 3 cases:
247 - FUNCTION is not interactive: the interactive spec of OLDFUN is used.
248 - The interactive spec of FUNCTION is itself a function: it should take one
249 argument (the interactive spec of OLDFUN, which it can pass to
250 `advice-eval-interactive-spec') and return the list of arguments to use.
251 - Else, use the interactive spec of FUNCTION and ignore the one of OLDFUN."
252 (declare (debug t
)) ;;(indent 2)
253 (cond ((eq 'local
(car-safe place
))
254 (setq place
`(advice--buffer-local ,@(cdr place
))))
256 (setq place
`(default-value ',place
))))
257 `(advice--add-function ,where
(gv-ref ,place
) ,function
,props
))
260 (defun advice--add-function (where ref function props
)
261 (unless (advice--member-p function
(cdr (assq 'name props
))
264 (advice--make where function
(gv-deref ref
) props
))))
266 (defmacro remove-function
(place function
)
267 "Remove the FUNCTION piece of advice from PLACE.
268 If FUNCTION was not added to PLACE, do nothing.
269 Instead of FUNCTION being the actual function, it can also be the `name'
270 of the piece of advice."
272 (cond ((eq 'local
(car-safe place
))
273 (setq place
`(advice--buffer-local ,@(cdr place
))))
275 (error "Use (default-value '%S) or (local '%S)" place place
)))
276 (gv-letplace (getter setter
) place
277 (macroexp-let2 nil new
`(advice--remove-function ,getter
,function
)
278 `(unless (eq ,new
,getter
) ,(funcall setter new
)))))
280 ;;;; Specific application of add-function to `symbol-function' for advice.
282 (defun advice--subst-main (old new
)
284 (lambda (first _rest _props
) (if (not first
) new
))))
286 (defun advice--normalize (symbol def
)
288 ((special-form-p def
)
289 ;; Not worth the trouble trying to handle this, I think.
290 (error "advice-add failure: %S is a special form" symbol
))
292 (eq 'macro
(car-safe (ignore-errors (indirect-function def
)))))
293 (let ((newval (cons 'macro
(cdr (indirect-function def
)))))
294 (put symbol
'advice--saved-rewrite
(cons def newval
))
296 ;; `f' might be a pure (hence read-only) cons!
297 ((and (eq 'macro
(car-safe def
))
298 (not (ignore-errors (setcdr def
(cdr def
)) t
)))
299 (cons 'macro
(cdr def
)))
302 (defsubst advice--strip-macro
(x)
303 (if (eq 'macro
(car-safe x
)) (cdr x
) x
))
305 (defun advice--defalias-fset (fsetfun symbol newdef
)
306 (when (get symbol
'advice--saved-rewrite
)
307 (put symbol
'advice--saved-rewrite nil
))
308 (setq newdef
(advice--normalize symbol newdef
))
309 (let* ((olddef (advice--strip-macro
310 (if (fboundp symbol
) (symbol-function symbol
))))
313 ((null (get symbol
'advice--pending
))
316 (message "Delayed advice activation failed for %s: no data"
319 ((or (not olddef
) (autoloadp olddef
))
320 (prog1 (get symbol
'advice--pending
)
321 (put symbol
'advice--pending nil
)))
322 (t (message "Dropping left-over advice--pending for %s" symbol
)
323 (put symbol
'advice--pending nil
)
325 (let* ((snewdef (advice--strip-macro newdef
))
326 (snewadv (advice--subst-main oldadv snewdef
)))
327 (funcall (or fsetfun
#'fset
) symbol
328 (if (eq snewdef newdef
) snewadv
(cons 'macro snewadv
))))))
332 (defun advice-add (symbol where function
&optional props
)
333 "Like `add-function' but for the function named SYMBOL.
334 Contrary to `add-function', this will properly handle the cases where SYMBOL
335 is defined as a macro, alias, command, ..."
337 ;; - record the advice location, to display in describe-function.
338 ;; - change all defadvice in lisp/**/*.el.
339 ;; - rewrite advice.el on top of this.
340 ;; - obsolete advice.el.
341 (let* ((f (and (fboundp symbol
) (symbol-function symbol
)))
342 (nf (advice--normalize symbol f
)))
343 (unless (eq f nf
) ;; Most importantly, if nf == nil!
345 (add-function where
(cond
346 ((eq (car-safe nf
) 'macro
) (cdr nf
))
347 ;; Reasons to delay installation of the advice:
348 ;; - If the function is not yet defined, installing
349 ;; the advice would affect `fboundp'ness.
350 ;; - If it's an autoloaded command,
351 ;; advice--make-interactive-form would end up
352 ;; loading the command eagerly.
353 ;; - `autoload' does nothing if the function is
354 ;; not an autoload or undefined.
355 ((or (not nf
) (autoloadp nf
))
356 (get symbol
'advice--pending
))
357 (t (symbol-function symbol
)))
359 (add-function :around
(get symbol
'defalias-fset-function
)
360 #'advice--defalias-fset
))
364 (defun advice-remove (symbol function
)
365 "Like `remove-function' but for the function named SYMBOL.
366 Contrary to `remove-function', this will work also when SYMBOL is a macro
367 and it will not signal an error if SYMBOL is not `fboundp'.
368 Instead of the actual function to remove, FUNCTION can also be the `name'
369 of the piece of advice."
370 (when (fboundp symbol
)
371 (let ((f (symbol-function symbol
)))
372 ;; Can't use the `if' place here, because the body is too large,
373 ;; resulting in use of code that only works with lexical-scoping.
374 (remove-function (if (eq (car-safe f
) 'macro
)
376 (symbol-function symbol
))
379 (if (eq (car-safe f
) 'macro
) (cdr f
) (symbol-function symbol
)))
380 ;; Not advised any more.
381 (remove-function (get symbol
'defalias-fset-function
)
382 #'advice--defalias-fset
)
383 (if (eq (symbol-function symbol
)
384 (cdr (get symbol
'advice--saved-rewrite
)))
385 (fset symbol
(car (get symbol
'advice--saved-rewrite
))))))
388 ;; (defun advice-mapc (fun symbol)
389 ;; "Apply FUN to every function added as advice to SYMBOL.
390 ;; FUN is called with a two arguments: the function that was added, and the
391 ;; properties alist that was specified when it was added."
392 ;; (let ((def (or (get symbol 'advice--pending)
393 ;; (if (fboundp symbol) (symbol-function symbol)))))
394 ;; (while (advice--p def)
395 ;; (funcall fun (advice--car def) (advice--props def))
396 ;; (setq def (advice--cdr def)))))
399 (defun advice-member-p (advice function-name
)
400 "Return non-nil if ADVICE has been added to FUNCTION-NAME.
401 Instead of ADVICE being the actual function, it can also be the `name'
402 of the piece of advice."
403 (advice--member-p advice advice
404 (or (get function-name
'advice--pending
)
406 (if (fboundp function-name
)
407 (symbol-function function-name
))))))
409 ;; When code is advised, called-interactively-p needs to be taught to skip
410 ;; the advising frames.
411 ;; FIXME: This Major Ugly Hack won't handle calls to called-interactively-p
412 ;; done from the advised function if the deepest advice is an around advice!
413 ;; In other cases (calls from an advice or calls from the advised function when
414 ;; the deepest advice is not an around advice), it should hopefully get
416 (add-hook 'called-interactively-p-functions
417 #'advice--called-interactively-skip
)
418 (defun advice--called-interactively-skip (origi frame1 frame2
)
423 (setq frame2
(internal--called-interactively-p--get-frame i
))
424 ;; (message "Advice Frame %d = %S" i frame2)
426 (when (and (eq (nth 1 frame2
) 'apply
)
428 (funcall get-next-frame
)
429 (advice--p (indirect-function (nth 1 frame2
)))))
430 (funcall get-next-frame
)
431 ;; If we now have the symbol, this was the head advice and
433 (while (advice--p (nth 1 frame1
))
434 ;; This was an inner advice called from some earlier advice.
435 ;; The stack frames look different depending on the particular
436 ;; kind of the earlier advice.
437 (let ((inneradvice (nth 1 frame1
)))
438 (if (and (eq (nth 1 frame2
) 'apply
)
440 (funcall get-next-frame
)
441 (advice--p (indirect-function
443 ;; The earlier advice was something like a before/after
444 ;; advice where the "next" code is called directly by the
446 (funcall get-next-frame
)
447 ;; It's apparently an around advice, where the "next" is
448 ;; called by the body of the advice in any way it sees fit,
449 ;; so we need to skip the frames of that body.
452 (funcall get-next-frame
)
453 (not (and (eq (nth 1 frame2
) 'apply
)
454 (eq (nth 3 frame2
) inneradvice
)))))
455 (funcall get-next-frame
)
456 (funcall get-next-frame
))))
461 ;;; nadvice.el ends here