1 ;;; advice.el --- An overloading mechanism for Emacs Lisp functions
3 ;; Copyright (C) 1993-1994, 2000-2012 Free Software Foundation, Inc.
5 ;; Author: Hans Chalupsky <hans@cs.buffalo.edu>
7 ;; Created: 12 Dec 1992
8 ;; Keywords: extensions, lisp, tools
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;; advice|Hans Chalupsky|hans@cs.buffalo.edu|
28 ;; Overloading mechanism for Emacs Lisp functions|
29 ;; 1994/08/05 03:42:04|2.14|~/packages/advice.el.Z|
34 ;; NOTE: This documentation is slightly out of date. In particular, all the
35 ;; references to Emacs-18 are obsolete now, because it is not any longer
36 ;; supported by this version of Advice.
38 ;; Advice is documented in the Emacs Lisp Manual.
42 ;; This package implements a full-fledged Lisp-style advice mechanism
43 ;; for Emacs Lisp. Advice is a clean and efficient way to modify the
44 ;; behavior of Emacs Lisp functions without having to keep personal
45 ;; modified copies of such functions around. A great number of such
46 ;; modifications can be achieved by treating the original function as a
47 ;; black box and specifying a different execution environment for it
48 ;; with a piece of advice. Think of a piece of advice as a kind of fancy
49 ;; hook that you can attach to any function/macro/subr.
53 ;; - Clean definition of multiple, named before/around/after advices
54 ;; for functions, macros, subrs and special forms
55 ;; - Full control over the arguments an advised function will receive,
56 ;; the binding environment in which it will be executed, as well as the
57 ;; value it will return.
58 ;; - Allows re/definition of interactive behavior for functions and subrs
59 ;; - Every piece of advice can have its documentation string which will be
60 ;; combined with the original documentation of the advised function at
61 ;; call-time of `documentation' for proper command-key substitution.
62 ;; - The execution of every piece of advice can be protected against error
63 ;; and non-local exits in preceding code or advices.
64 ;; - Simple argument access either by name, or, more portable but as
65 ;; efficient, via access macros
66 ;; - Allows the specification of a different argument list for the advised
67 ;; version of a function.
68 ;; - Advised functions can be byte-compiled either at file-compile time
69 ;; (see preactivation) or activation time.
70 ;; - Separation of advice definition and activation
71 ;; - Forward advice is possible, that is
72 ;; as yet undefined or autoload functions can be advised without having to
73 ;; preload the file in which they are defined.
74 ;; - Forward redefinition is possible because around advice can be used to
75 ;; completely redefine a function.
76 ;; - A caching mechanism for advised definition provides for cheap deactivation
77 ;; and reactivation of advised functions.
78 ;; - Preactivation allows efficient construction and compilation of advised
79 ;; definitions at file compile time without giving up the flexibility of
80 ;; the advice mechanism.
81 ;; - En/disablement mechanism allows the use of different "views" of advised
82 ;; functions depending on what pieces of advice are currently en/disabled
83 ;; - Provides manipulation mechanisms for sets of advised functions via
84 ;; regular expressions that match advice names
86 ;; @ How to get Advice for Emacs-18:
87 ;; =================================
88 ;; `advice18.el', a version of Advice that also works in Emacs-18 is available
89 ;; either via anonymous ftp from `ftp.cs.buffalo.edu (128.205.32.9)' with
90 ;; pathname `/pub/Emacs/advice18.el', or from one of the Emacs Lisp archive
91 ;; sites, or send email to <hans@cs.buffalo.edu> and I'll mail it to you.
93 ;; @ Overview, or how to read this file:
94 ;; =====================================
95 ;; NOTE: This documentation is slightly out of date. In particular, all the
96 ;; references to Emacs-18 are obsolete now, because it is not any longer
97 ;; supported by this version of Advice. An up-to-date version will soon be
98 ;; available as an info file (thanks to the kind help of Jack Vinson and
99 ;; David M. Smith). Until then you can use `outline-mode' to help you read
100 ;; this documentation (set `outline-regexp' to `";; @+"').
102 ;; The four major sections of this file are:
104 ;; @ This initial information ...installation, customization etc.
105 ;; @ Advice documentation: ...general documentation
106 ;; @ Foo games: An advice tutorial ...teaches about Advice by example
107 ;; @ Advice implementation: ...actual code, yeah!!
109 ;; The latter three are actual headings which you can search for
110 ;; directly in case `outline-mode' doesn't work for you.
114 ;; - This version of Advice only works for Emacs 19.26 and later. It uses
115 ;; new versions of the built-in functions `fset/defalias' which are not
116 ;; yet available in Lucid Emacs, hence, it won't work there.
117 ;; - Advised functions/macros/subrs will only exhibit their advised behavior
118 ;; when they are invoked via their function cell. This means that advice will
119 ;; not work for the following:
120 ;; + advised subrs that are called directly from other subrs or C-code
121 ;; + advised subrs that got replaced with their byte-code during
122 ;; byte-compilation (e.g., car)
123 ;; + advised macros which were expanded during byte-compilation before
124 ;; their advice was activated.
128 ;; This package is an extension and generalization of packages such as
129 ;; insert-hooks.el written by Noah S. Friedman, and advise.el written by
130 ;; Raul J. Acevedo. Some ideas used in here come from these packages,
131 ;; others come from the various Lisp advice mechanisms I've come across
132 ;; so far, and a few are simply mine.
134 ;; @ Comments, suggestions, bug reports:
135 ;; =====================================
136 ;; If you find any bugs, have suggestions for new advice features, find the
137 ;; documentation wrong, confusing, incomplete, or otherwise unsatisfactory,
138 ;; have any questions about Advice, or have otherwise enlightening
139 ;; comments feel free to send me email at <hans@cs.buffalo.edu>.
141 ;; @ Safety Rules and Emergency Exits:
142 ;; ===================================
143 ;; Before we begin: CAUTION!!
144 ;; Advice provides you with a lot of rope to hang yourself on very
145 ;; easily accessible trees, so, here are a few important things you
146 ;; should know: Once Advice has been started with `ad-start-advice'
147 ;; (which happens automatically when you load this file), it
148 ;; generates an advised definition of the `documentation' function, and
149 ;; it will enable automatic advice activation when functions get defined.
150 ;; All of this can be undone at any time with `M-x ad-stop-advice'.
152 ;; If you experience any strange behavior/errors etc. that you attribute to
153 ;; Advice or to some ill-advised function do one of the following:
155 ;; - M-x ad-deactivate FUNCTION (if you have a definite suspicion what
156 ;; function gives you problems)
157 ;; - M-x ad-deactivate-all (if you don't have a clue what's going wrong)
158 ;; - M-x ad-stop-advice (if you think the problem is related to the
159 ;; advised functions used by Advice itself)
160 ;; - M-x ad-recover-normality (for real emergencies)
161 ;; - If none of the above solves your Advice-related problem go to another
162 ;; terminal, kill your Emacs process and send me some hate mail.
164 ;; The first three measures have restarts, i.e., once you've figured out
165 ;; the problem you can reactivate advised functions with either `ad-activate',
166 ;; `ad-activate-all', or `ad-start-advice'. `ad-recover-normality' unadvises
167 ;; everything so you won't be able to reactivate any advised functions, you'll
168 ;; have to stick with their standard incarnations for the rest of the session.
170 ;; IMPORTANT: With Advice loaded always do `M-x ad-deactivate-all' before
171 ;; you byte-compile a file, because advised special forms and macros can lead
172 ;; to unwanted compilation results. When you are done compiling use
173 ;; `M-x ad-activate-all' to go back to the advised state of all your
174 ;; advised functions.
176 ;; RELAX: Advice is pretty safe even if you are oblivious to the above.
177 ;; I use it extensively and haven't run into any serious trouble in a long
178 ;; time. Just wanted you to be warned.
183 ;; Look at the documentation of `ad-redefinition-action' for possible values
184 ;; of this variable. Its default value is `warn' which will print a warning
185 ;; message when an already defined advised function gets redefined with a
186 ;; new original definition and de/activated.
188 ;; Look at the documentation of `ad-default-compilation-action' for possible
189 ;; values of this variable. Its default value is `maybe' which will compile
190 ;; advised definitions during activation in case the byte-compiler is already
191 ;; loaded. Otherwise, it will leave them uncompiled.
195 ;; Before I go on explaining how advice works, here are four simple examples
196 ;; how this package can be used. The first three are very useful, the last one
199 ;;(defadvice switch-to-buffer (before existing-buffers-only activate)
200 ;; "When called interactively switch to existing buffers only, unless
201 ;;when called with a prefix argument."
203 ;; (list (read-buffer "Switch to buffer: " (other-buffer)
204 ;; (null current-prefix-arg)))))
206 ;;(defadvice switch-to-buffer (around confirm-non-existing-buffers activate)
207 ;; "Switch to non-existing buffers only upon confirmation."
208 ;; (interactive "BSwitch to buffer: ")
209 ;; (if (or (get-buffer (ad-get-arg 0))
210 ;; (y-or-n-p (format "`%s' does not exist, create? " (ad-get-arg 0))))
213 ;;(defadvice find-file (before existing-files-only activate)
214 ;; "Find existing files only"
215 ;; (interactive "fFind file: "))
217 ;;(defadvice car (around interactive activate)
218 ;; "Make `car' an interactive function."
219 ;; (interactive "xCar of list: ")
221 ;; (if (called-interactively-p 'interactive)
222 ;; (message "%s" ad-return-value)))
225 ;; @ Advice documentation:
226 ;; =======================
227 ;; Below is general documentation of the various features of advice. For more
228 ;; concrete examples check the corresponding sections in the tutorial part.
232 ;; - Emacs, Emacs-19: Emacs as released by the GNU Project
233 ;; - Lemacs: Lucid's version of Emacs with major version 19
234 ;; - v18: Any Emacs with major version 18 or built as an extension to that
236 ;; - v19: Any Emacs with major version 19
237 ;; - jwz: Jamie Zawinski - former keeper of Lemacs and creator of the optimizing
238 ;; byte-compiler used in v19s.
239 ;; - Advice: The name of this package.
240 ;; - advices: Short for "pieces of advice".
242 ;; @@ Defining a piece of advice with `defadvice':
243 ;; ===============================================
244 ;; The main means of defining a piece of advice is the macro `defadvice',
245 ;; there is no interactive way of specifying a piece of advice. A call to
246 ;; `defadvice' has the following syntax which is similar to the syntax of
249 ;; (defadvice <function> (<class> <name> [<position>] [<arglist>] {<flags>}*)
250 ;; [ [<documentation-string>] [<interactive-form>] ]
253 ;; <function> is the name of the function/macro/subr to be advised.
255 ;; <class> is the class of the advice which has to be one of `before',
256 ;; `around', `after', `activation' or `deactivation' (the last two allow
257 ;; definition of special act/deactivation hooks).
259 ;; <name> is the name of the advice which has to be a non-nil symbol.
260 ;; Names uniquely identify a piece of advice in a certain advice class,
261 ;; hence, advices can be redefined by defining an advice with the same class
262 ;; and name. Advice names are global symbols, hence, the same name space
263 ;; conventions used for function names should be applied.
265 ;; An optional <position> specifies where in the current list of advices of
266 ;; the specified <class> this new advice will be placed. <position> has to
267 ;; be either `first', `last' or a number that specifies a zero-based
268 ;; position (`first' is equivalent to 0). If no position is specified
269 ;; `first' will be used as a default. If this call to `defadvice' redefines
270 ;; an already existing advice (see above) then the position argument will
271 ;; be ignored and the position of the already existing advice will be used.
273 ;; An optional <arglist> which has to be a list can be used to define the
274 ;; argument list of the advised function. This argument list should of
275 ;; course be compatible with the argument list of the original function,
276 ;; otherwise functions that call the advised function with the original
277 ;; argument list in mind will break. If more than one advice specify an
278 ;; argument list then the first one (the one with the smallest position)
279 ;; found in the list of before/around/after advices will be used.
281 ;; <flags> is a list of symbols that specify further information about the
282 ;; advice. All flags can be specified with unambiguous initial substrings.
283 ;; `activate': Specifies that the advice information of the advised
284 ;; function should be activated right after this advice has been
285 ;; defined. In forward advices `activate' will be ignored.
286 ;; `protect': Specifies that this advice should be protected against
287 ;; non-local exits and errors in preceding code/advices.
288 ;; `compile': Specifies that the advised function should be byte-compiled.
289 ;; This flag will be ignored unless `activate' is also specified.
290 ;; `disable': Specifies that the defined advice should be disabled, hence,
291 ;; it will not be used in an activation until somebody enables it.
292 ;; `preactivate': Specifies that the advised function should get preactivated
293 ;; at macro-expansion/compile time of this `defadvice'. This
294 ;; generates a compiled advised definition according to the
295 ;; current advice state which will be used during activation
296 ;; if appropriate. Only use this if the `defadvice' gets
297 ;; actually compiled (with a v18 byte-compiler put the `defadvice'
298 ;; into the body of a `defun' to accomplish proper compilation).
300 ;; An optional <documentation-string> can be supplied to document the advice.
301 ;; On call of the `documentation' function it will be combined with the
302 ;; documentation strings of the original function and other advices.
304 ;; An optional <interactive-form> form can be supplied to change/add
305 ;; interactive behavior of the original function. If more than one advice
306 ;; has an `(interactive ...)' specification then the first one (the one
307 ;; with the smallest position) found in the list of before/around/after
308 ;; advices will be used.
310 ;; A possibly empty list of <body-forms> specifies the body of the advice in
311 ;; an implicit progn. The body of an advice can access/change arguments,
312 ;; the return value, the binding environment, and can have all sorts of
313 ;; other side effects.
315 ;; @@ Assembling advised definitions:
316 ;; ==================================
317 ;; Suppose a function/macro/subr/special-form has N pieces of before advice,
318 ;; M pieces of around advice and K pieces of after advice. Assuming none of
319 ;; the advices is protected, its advised definition will look like this
320 ;; (body-form indices correspond to the position of the respective advice in
321 ;; that advice class):
323 ;; ([macro] lambda <arglist>
324 ;; [ [<advised-docstring>] [(interactive ...)] ]
325 ;; (let (ad-return-value)
326 ;; {<before-0-body-form>}*
328 ;; {<before-N-1-body-form>}*
329 ;; {<around-0-body-form>}*
330 ;; {<around-1-body-form>}*
332 ;; {<around-M-1-body-form>}*
333 ;; (setq ad-return-value
334 ;; <apply original definition to <arglist>>)
335 ;; {<other-around-M-1-body-form>}*
337 ;; {<other-around-1-body-form>}*
338 ;; {<other-around-0-body-form>}*
339 ;; {<after-0-body-form>}*
341 ;; {<after-K-1-body-form>}*
344 ;; Macros and special forms will be redefined as macros, hence the optional
345 ;; [macro] in the beginning of the definition.
347 ;; <arglist> is either the argument list of the original function or the
348 ;; first argument list defined in the list of before/around/after advices.
349 ;; The values of <arglist> variables can be accessed/changed in the body of
350 ;; an advice by simply referring to them by their original name, however,
351 ;; more portable argument access macros are also provided (see below).
353 ;; <advised-docstring> is an optional, special documentation string which will
354 ;; be expanded into a proper documentation string upon call of `documentation'.
356 ;; (interactive ...) is an optional interactive form either taken from the
357 ;; original function or from a before/around/after advice. For advised
358 ;; interactive subrs that do not have an interactive form specified in any
359 ;; advice we have to use (interactive) and then call the subr interactively
360 ;; if the advised function was called interactively, because the
361 ;; interactive specification of subrs is not accessible. This is the only
362 ;; case where changing the values of arguments will not have an affect
363 ;; because they will be reset by the interactive specification of the subr.
364 ;; If this is a problem one can always specify an interactive form in a
365 ;; before/around/after advice to gain control over argument values that
366 ;; were supplied interactively.
368 ;; Then the body forms of the various advices in the various classes of advice
369 ;; are assembled in order. The forms of around advice L are normally part of
370 ;; one of the forms of around advice L-1. An around advice can specify where
371 ;; the forms of the wrapped or surrounded forms should go with the special
372 ;; keyword `ad-do-it', which will be substituted with a `progn' containing the
373 ;; forms of the surrounded code.
375 ;; The innermost part of the around advice onion is
376 ;; <apply original definition to <arglist>>
377 ;; whose form depends on the type of the original function. The variable
378 ;; `ad-return-value' will be set to its result. This variable is visible to
379 ;; all pieces of advice which can access and modify it before it gets returned.
381 ;; The semantic structure of advised functions that contain protected pieces
382 ;; of advice is the same. The only difference is that `unwind-protect' forms
383 ;; make sure that the protected advice gets executed even if some previous
384 ;; piece of advice had an error or a non-local exit. If any around advice is
385 ;; protected then the whole around advice onion will be protected.
387 ;; @@ Argument access in advised functions:
388 ;; ========================================
389 ;; As already mentioned, the simplest way to access the arguments of an
390 ;; advised function in the body of an advice is to refer to them by name. To
391 ;; do that, the advice programmer needs to know either the names of the
392 ;; argument variables of the original function, or the names used in the
393 ;; argument list redefinition given in a piece of advice. While this simple
394 ;; method might be sufficient in many cases, it has the disadvantage that it
395 ;; is not very portable because it hardcodes the argument names into the
396 ;; advice. If the definition of the original function changes the advice
397 ;; might break even though the code might still be correct. Situations like
398 ;; that arise, for example, if one advises a subr like `eval-region' which
399 ;; gets redefined in a non-advice style into a function by the edebug
400 ;; package. If the advice assumes `eval-region' to be a subr it might break
401 ;; once edebug is loaded. Similar situations arise when one wants to use the
402 ;; same piece of advice across different versions of Emacs. Some subrs in a
403 ;; v18 Emacs are functions in v19 and vice versa, but for the most part the
404 ;; semantics remain the same, hence, the same piece of advice might be usable
405 ;; in both Emacs versions.
407 ;; As a solution to that advice provides argument list access macros that get
408 ;; translated into the proper access forms at activation time, i.e., when the
409 ;; advised definition gets constructed. Access macros access actual arguments
410 ;; by position regardless of how these actual argument get distributed onto
411 ;; the argument variables of a function. The rational behind this is that in
412 ;; Emacs Lisp the semantics of an argument is strictly determined by its
413 ;; position (there are no keyword arguments).
415 ;; Suppose the function `foo' is defined as
417 ;; (defun foo (x y &optional z &rest r) ....)
419 ;; and is then called with
421 ;; (foo 0 1 2 3 4 5 6)
423 ;; which means that X=0, Y=1, Z=2 and R=(3 4 5 6). The assumption is that
424 ;; the semantics of an actual argument is determined by its position. It is
425 ;; this semantics that has to be known by the advice programmer. Then s/he
426 ;; can access these arguments in a piece of advice with some of the
427 ;; following macros (the arrows indicate what value they will return):
429 ;; (ad-get-arg 0) -> 0
430 ;; (ad-get-arg 1) -> 1
431 ;; (ad-get-arg 2) -> 2
432 ;; (ad-get-arg 3) -> 3
433 ;; (ad-get-args 2) -> (2 3 4 5 6)
434 ;; (ad-get-args 4) -> (4 5 6)
436 ;; `(ad-get-arg <position>)' will return the actual argument that was supplied
437 ;; at <position>, `(ad-get-args <position>)' will return the list of actual
438 ;; arguments supplied starting at <position>. Note that these macros can be
439 ;; used without any knowledge about the form of the actual argument list of
440 ;; the original function.
442 ;; Similarly, `(ad-set-arg <position> <value-form>)' can be used to set the
443 ;; value of the actual argument at <position> to <value-form>. For example,
445 ;; (ad-set-arg 5 "five")
447 ;; will have the effect that R=(3 4 "five" 6) once the original function is
448 ;; called. `(ad-set-args <position> <value-list-form>)' can be used to set
449 ;; the list of actual arguments starting at <position> to <value-list-form>.
452 ;; (ad-set-args 0 '(5 4 3 2 1 0))
454 ;; will have the effect that X=5, Y=4, Z=3 and R=(2 1 0) once the original
455 ;; function is called.
457 ;; All these access macros are text macros rather than real Lisp macros. When
458 ;; the advised definition gets constructed they get replaced with actual access
459 ;; forms depending on the argument list of the advised function, i.e., after
460 ;; that argument access is in most cases as efficient as using the argument
461 ;; variable names directly.
463 ;; @@@ Accessing argument bindings of arbitrary functions:
464 ;; =======================================================
465 ;; Some functions (such as `trace-function' defined in trace.el) need a
466 ;; method of accessing the names and bindings of the arguments of an
467 ;; arbitrary advised function. To do that within an advice one can use the
468 ;; special keyword `ad-arg-bindings' which is a text macro that will be
469 ;; substituted with a form that will evaluate to a list of binding
470 ;; specifications, one for every argument variable. These binding
471 ;; specifications can then be examined in the body of the advice. For
472 ;; example, somewhere in an advice we could do this:
474 ;; (let* ((bindings ad-arg-bindings)
475 ;; (firstarg (car bindings))
476 ;; (secondarg (car (cdr bindings))))
477 ;; ;; Print info about first argument
478 ;; (print (format "%s=%s (%s)"
479 ;; (ad-arg-binding-field firstarg 'name)
480 ;; (ad-arg-binding-field firstarg 'value)
481 ;; (ad-arg-binding-field firstarg 'type)))
484 ;; The `type' of an argument is either `required', `optional' or `rest'.
485 ;; Wherever `ad-arg-bindings' appears a form will be inserted that evaluates
486 ;; to the list of bindings, hence, in order to avoid multiple unnecessary
487 ;; evaluations one should always bind it to some variable.
489 ;; @@@ Argument list mapping:
490 ;; ==========================
491 ;; Because `defadvice' allows the specification of the argument list
492 ;; of the advised function we need a mapping mechanism that maps this
493 ;; argument list onto that of the original function. Hence SYM and
494 ;; NEWDEF have to be properly mapped onto the &rest variable when the
495 ;; original definition is called. Advice automatically takes care of
496 ;; that mapping, hence, the advice programmer can specify an argument
497 ;; list without having to know about the exact structure of the
498 ;; original argument list as long as the new argument list takes a
499 ;; compatible number/magnitude of actual arguments.
501 ;; @@ Activation and deactivation:
502 ;; ===============================
503 ;; The definition of an advised function does not change until all its advice
504 ;; gets actually activated. Activation can either happen with the `activate'
505 ;; flag specified in the `defadvice', with an explicit call or interactive
506 ;; invocation of `ad-activate', or if forward advice is enabled (i.e., the
507 ;; value of `ad-activate-on-definition' is t) at the time an already advised
508 ;; function gets defined.
510 ;; When a function gets first activated its original definition gets saved,
511 ;; all defined and enabled pieces of advice will get combined with the
512 ;; original definition, the resulting definition might get compiled depending
513 ;; on some conditions described below, and then the function will get
514 ;; redefined with the advised definition. This also means that undefined
515 ;; functions cannot get activated even though they might be already advised.
517 ;; The advised definition will get compiled either if `ad-activate' was called
518 ;; interactively with a prefix argument, or called explicitly with its second
519 ;; argument as t, or, if `ad-default-compilation-action' justifies it according
520 ;; to the current system state. If the advised definition was
521 ;; constructed during "preactivation" (see below) then that definition will
522 ;; be already compiled because it was constructed during byte-compilation of
523 ;; the file that contained the `defadvice' with the `preactivate' flag.
525 ;; `ad-deactivate' can be used to back-define an advised function to its
526 ;; original definition. It can be called interactively or directly. Because
527 ;; `ad-activate' caches the advised definition the function can be
528 ;; reactivated via `ad-activate' with only minor overhead (it is checked
529 ;; whether the current advice state is consistent with the cached
530 ;; definition, see the section on caching below).
532 ;; `ad-activate-regexp' and `ad-deactivate-regexp' can be used to de/activate
533 ;; all currently advised function that have a piece of advice with a name that
534 ;; contains a match for a regular expression. These functions can be used to
535 ;; de/activate sets of functions depending on certain advice naming
538 ;; Finally, `ad-activate-all' and `ad-deactivate-all' can be used to
539 ;; de/activate all currently advised functions. These are useful to
540 ;; (temporarily) return to an un/advised state.
542 ;; @@@ Reasons for the separation of advice definition and activation:
543 ;; ===================================================================
544 ;; As already mentioned, advising happens in two stages:
546 ;; 1) definition of various pieces of advice
547 ;; 2) activation of all advice currently defined and enabled
549 ;; The advantage of this is that various pieces of advice can be defined
550 ;; before they get combined into an advised definition which avoids
551 ;; unnecessary constructions of intermediate advised definitions. The more
552 ;; important advantage is that it allows the implementation of forward advice.
553 ;; Advice information for a certain function accumulates as the value of the
554 ;; `advice-info' property of the function symbol. This accumulation is
555 ;; completely independent of the fact that that function might not yet be
556 ;; defined. The special forms `defun' and `defmacro' have been advised to
557 ;; check whether the function/macro they defined had advice information
558 ;; associated with it. If so and forward advice is enabled, the original
559 ;; definition will be saved, and then the advice will be activated. When a
560 ;; file is loaded in a v18 Emacs the functions/macros it defines are also
561 ;; defined with calls to `defun/defmacro'. Hence, we can forward advise
562 ;; functions/macros which will be defined later during a load/autoload of some
563 ;; file (for compiled files generated by jwz's byte-compiler in a v19 Emacs
564 ;; this is slightly more complicated but the basic idea is the same).
566 ;; @@ Enabling/disabling pieces or sets of advice:
567 ;; ===============================================
568 ;; A major motivation for the development of this advice package was to bring
569 ;; a little bit more structure into the function overloading chaos in Emacs
570 ;; Lisp. Many packages achieve some of their functionality by adding a little
571 ;; bit (or a lot) to the standard functionality of some Emacs Lisp function.
572 ;; ange-ftp is a very popular package that achieves its magic by overloading
573 ;; most Emacs Lisp functions that deal with files. A popular function that's
574 ;; overloaded by many packages is `expand-file-name'. The situation that one
575 ;; function is multiply overloaded can arise easily.
577 ;; Once in a while it would be desirable to be able to disable some/all
578 ;; overloads of a particular package while keeping all the rest. Ideally -
579 ;; at least in my opinion - these overloads would all be done with advice,
580 ;; I know I am dreaming right now... In that ideal case the enable/disable
581 ;; mechanism of advice could be used to achieve just that.
583 ;; Every piece of advice is associated with an enablement flag. When the
584 ;; advised definition of a particular function gets constructed (e.g., during
585 ;; activation) only the currently enabled pieces of advice will be considered.
586 ;; This mechanism allows one to have different "views" of an advised function
587 ;; dependent on what pieces of advice are currently enabled.
589 ;; Another motivation for this mechanism is that it allows one to define a
590 ;; piece of advice for some function yet keep it dormant until a certain
591 ;; condition is met. Until then activation of the function will not make use
592 ;; of that piece of advice. Once the condition is met the advice can be
593 ;; enabled and a reactivation of the function will add its functionality as
594 ;; part of the new advised definition. For example, the advices of `defun'
595 ;; etc. used by advice itself will stay disabled until `ad-start-advice' is
596 ;; called and some variables have the proper values. Hence, if somebody
597 ;; else advised these functions too and activates them the advices defined
598 ;; by advice will get used only if they are intended to be used.
600 ;; The main interface to this mechanism are the interactive functions
601 ;; `ad-enable-advice' and `ad-disable-advice'. For example, the following
602 ;; would disable a particular advice of the function `foo':
604 ;; (ad-disable-advice 'foo 'before 'my-advice)
606 ;; This call by itself only changes the flag, to get the proper effect in
607 ;; the advised definition too one has to activate `foo' with
609 ;; (ad-activate 'foo)
611 ;; or interactively. To disable whole sets of advices one can use a regular
612 ;; expression mechanism. For example, let us assume that ange-ftp actually
613 ;; used advice to overload all its functions, and that it used the
614 ;; "ange-ftp-" prefix for all its advice names, then we could temporarily
615 ;; disable all its advices with
617 ;; (ad-disable-regexp "^ange-ftp-")
619 ;; and the following call would put that actually into effect:
621 ;; (ad-activate-regexp "^ange-ftp-")
623 ;; A safer way would have been to use
625 ;; (ad-update-regexp "^ange-ftp-")
627 ;; instead which would have only reactivated currently actively advised
628 ;; functions, but not functions that were currently inactive. All these
629 ;; functions can also be called interactively.
631 ;; A certain piece of advice is considered a match if its name contains a
632 ;; match for the regular expression. To enable ange-ftp again we would use
633 ;; `ad-enable-regexp' and then activate or update again.
635 ;; @@ Forward advice, automatic advice activation:
636 ;; ===============================================
637 ;; Because most Emacs Lisp packages are loaded on demand via an autoload
638 ;; mechanism it is essential to be able to "forward advise" functions.
639 ;; Otherwise, proper advice definition and activation would make it necessary
640 ;; to preload every file that defines a certain function before it can be
641 ;; advised, which would partly defeat the purpose of the advice mechanism.
643 ;; In the following, "forward advice" always implies its automatic activation
644 ;; once a function gets defined, and not just the accumulation of advice
645 ;; information for a possibly undefined function.
647 ;; Advice implements forward advice mainly via the following: 1) Separation
648 ;; of advice definition and activation that makes it possible to accumulate
649 ;; advice information without having the original function already defined,
650 ;; 2) special versions of the built-in functions `fset/defalias' which check
651 ;; for advice information whenever they define a function. If advice
652 ;; information was found then the advice will immediately get activated when
653 ;; the function gets defined.
655 ;; Automatic advice activation means, that whenever a function gets defined
656 ;; with either `defun', `defmacro', `fset' or by loading a byte-compiled
657 ;; file, and the function has some advice-info stored with it then that
658 ;; advice will get activated right away.
660 ;; @@@ Enabling automatic advice activation:
661 ;; =========================================
662 ;; Automatic advice activation is enabled by default. It can be disabled with
663 ;; `M-x ad-stop-advice' and enabled again with `M-x ad-start-advice'.
665 ;; @@ Caching of advised definitions:
666 ;; ==================================
667 ;; After an advised definition got constructed it gets cached as part of the
668 ;; advised function's advice-info so it can be reused, for example, after an
669 ;; intermediate deactivation. Because the advice-info of a function might
670 ;; change between the time of caching and reuse a cached definition gets
671 ;; a cache-id associated with it so it can be verified whether the cached
672 ;; definition is still valid (the main application of this is preactivation
675 ;; When an advised function gets activated and a verifiable cached definition
676 ;; is available, then that definition will be used instead of creating a new
677 ;; advised definition from scratch. If you want to make sure that a new
678 ;; definition gets constructed then you should use `ad-clear-cache' before you
679 ;; activate the advised function.
683 ;; Constructing an advised definition is moderately expensive. In a situation
684 ;; where one package defines a lot of advised functions it might be
685 ;; prohibitively expensive to do all the advised definition construction at
686 ;; runtime. Preactivation is a mechanism that allows compile-time construction
687 ;; of compiled advised definitions that can be activated cheaply during
688 ;; runtime. Preactivation uses the caching mechanism to do that. Here's how it
691 ;; When the byte-compiler compiles a `defadvice' that has the `preactivate'
692 ;; flag specified, it uses the current original definition of the advised
693 ;; function plus the advice specified in this `defadvice' (even if it is
694 ;; specified as disabled) and all other currently enabled pieces of advice to
695 ;; construct an advised definition and an identifying cache-id and makes them
696 ;; part of the `defadvice' expansion which will then be compiled by the
697 ;; byte-compiler (to ensure that in a v18 emacs you have to put the
698 ;; `defadvice' inside a `defun' to get it compiled and then you have to call
699 ;; that compiled `defun' in order to actually execute the `defadvice'). When
700 ;; the file with the compiled, preactivating `defadvice' gets loaded the
701 ;; precompiled advised definition will be cached on the advised function's
702 ;; advice-info. When it gets activated (can be immediately on execution of the
703 ;; `defadvice' or any time later) the cache-id gets checked against the
704 ;; current state of advice and if it is verified the precompiled definition
705 ;; will be used directly (the verification is pretty cheap). If it couldn't get
706 ;; verified a new advised definition for that function will be built from
707 ;; scratch, hence, the efficiency added by the preactivation mechanism does
708 ;; not at all impair the flexibility of the advice mechanism.
710 ;; MORAL: In order get all the efficiency out of preactivation the advice
711 ;; state of an advised function at the time the file with the
712 ;; preactivating `defadvice' gets byte-compiled should be exactly
713 ;; the same as it will be when the advice of that function gets
714 ;; actually activated. If it is not there is a high chance that the
715 ;; cache-id will not match and hence a new advised definition will
716 ;; have to be constructed at runtime.
718 ;; Preactivation and forward advice do not contradict each other. It is
719 ;; perfectly ok to load a file with a preactivating `defadvice' before the
720 ;; original definition of the advised function is available. The constructed
721 ;; advised definition will be used once the original function gets defined and
722 ;; its advice gets activated. The only constraint is that at the time the
723 ;; file with the preactivating `defadvice' got compiled the original function
724 ;; definition was available.
726 ;; TIPS: Here are some indications that a preactivation did not work the way
727 ;; you intended it to work:
728 ;; - Activation of the advised function takes longer than usual/expected
729 ;; - The byte-compiler gets loaded while an advised function gets
731 ;; - `byte-compile' is part of the `features' variable even though you
732 ;; did not use the byte-compiler
733 ;; Right now advice does not provide an elegant way to find out whether
734 ;; and why a preactivation failed. What you can do is to trace the
735 ;; function `ad-cache-id-verification-code' (with the function
736 ;; `trace-function-background' defined in my trace.el package) before
737 ;; any of your advised functions get activated. After they got
738 ;; activated check whether all calls to `ad-cache-id-verification-code'
739 ;; returned `verified' as a result. Other values indicate why the
740 ;; verification failed which should give you enough information to
741 ;; fix your preactivation/compile/load/activation sequence.
743 ;; IMPORTANT: There is one case (that I am aware of) that can make
744 ;; preactivation fail, i.e., a preconstructed advised definition that does
745 ;; NOT match the current state of advice gets used nevertheless. That case
746 ;; arises if one package defines a certain piece of advice which gets used
747 ;; during preactivation, and another package incompatibly redefines that
748 ;; very advice (i.e., same function/class/name), and it is the second advice
749 ;; that is available when the preconstructed definition gets activated, and
750 ;; that was the only definition of that advice so far (`ad-add-advice'
751 ;; catches advice redefinitions and clears the cache in such a case).
752 ;; Catching that would make the cache verification too expensive.
754 ;; MORAL-II: Redefining somebody else's advice is BAAAAD (to speak with
755 ;; George Walker Bush), and why would you redefine your own advice anyway?
756 ;; Advice is a mechanism to facilitate function redefinition, not advice
757 ;; redefinition (wait until I write Meta-Advice :-). If you really have
758 ;; to undo somebody else's advice try to write a "neutralizing" advice.
760 ;; @@ Advising macros and special forms and other dangerous things:
761 ;; ================================================================
762 ;; Look at the corresponding tutorial sections for more information on
763 ;; these topics. Here it suffices to point out that the special treatment
764 ;; of macros and special forms by the byte-compiler can lead to problems
765 ;; when they get advised. Macros can create problems because they get
766 ;; expanded at compile time, hence, they might not have all the necessary
767 ;; runtime support and such advice cannot be de/activated or changed as
768 ;; it is possible for functions. Special forms create problems because they
769 ;; have to be advised "into" macros, i.e., an advised special form is a
770 ;; implemented as a macro, hence, in most cases the byte-compiler will
771 ;; not recognize it as a special form anymore which can lead to very strange
774 ;; MORAL: - Only advise macros or special forms when you are absolutely sure
775 ;; what you are doing.
776 ;; - As a safety measure, always do `ad-deactivate-all' before you
777 ;; byte-compile a file to make sure that even if some inconsiderate
778 ;; person advised some special forms you'll get proper compilation
779 ;; results. After compilation do `ad-activate-all' to get back to
780 ;; the previous state.
782 ;; @@ Adding a piece of advice with `ad-add-advice':
783 ;; =================================================
784 ;; The non-interactive function `ad-add-advice' can be used to add a piece of
785 ;; advice to some function without using `defadvice'. This is useful if advice
786 ;; has to be added somewhere by a function (also look at `ad-make-advice').
788 ;; @@ Activation/deactivation advices, file load hooks:
789 ;; ====================================================
790 ;; There are two special classes of advice called `activation' and
791 ;; `deactivation'. The body forms of these advices are not included into the
792 ;; advised definition of a function, rather they are assembled into a hook
793 ;; form which will be evaluated whenever the advice-info of the advised
794 ;; function gets activated or deactivated. One application of this mechanism
795 ;; is to define file load hooks for files that do not provide such hooks
796 ;; (v19s already come with a general file-load-hook mechanism, v18s don't).
797 ;; For example, suppose you want to print a message whenever `file-x' gets
798 ;; loaded, and suppose the last function defined in `file-x' is
799 ;; `file-x-last-fn'. Then we can define the following advice:
801 ;; (defadvice file-x-last-fn (activation file-x-load-hook)
802 ;; "Executed whenever file-x is loaded"
803 ;; (if load-in-progress (message "Loaded file-x")))
805 ;; This will constitute a forward advice for function `file-x-last-fn' which
806 ;; will get activated when `file-x' is loaded (only if forward advice is
807 ;; enabled of course). Because there are no "real" pieces of advice
808 ;; available for it, its definition will not be changed, but the activation
809 ;; advice will be run during its activation which is equivalent to having a
810 ;; file load hook for `file-x'.
812 ;; @@ Summary of main advice concepts:
813 ;; ===================================
815 ;; A piece of advice gets defined with `defadvice' and added to the
816 ;; `advice-info' property of a function.
818 ;; Every piece of advice has an enablement flag associated with it. Only
819 ;; enabled advices are considered during construction of an advised
822 ;; Redefine an advised function with its advised definition. Constructs
823 ;; an advised definition from scratch if no verifiable cached advised
824 ;; definition is available and caches it.
826 ;; Back-define an advised function to its original definition.
828 ;; Reactivate an advised function but only if its advice is currently
829 ;; active. This can be used to bring all currently advised function up
830 ;; to date with the current state of advice without also activating
831 ;; currently inactive functions.
833 ;; Is the saving of an advised definition and an identifying cache-id so
834 ;; it can be reused, for example, for activation after deactivation.
836 ;; Is the construction of an advised definition according to the current
837 ;; state of advice during byte-compilation of a file with a preactivating
838 ;; `defadvice'. That advised definition can then rather cheaply be used
839 ;; during activation without having to construct an advised definition
840 ;; from scratch at runtime.
842 ;; @@ Summary of interactive advice manipulation functions:
843 ;; ========================================================
844 ;; The following interactive functions can be used to manipulate the state
845 ;; of advised functions (all of them support completion on function names,
846 ;; advice classes and advice names):
848 ;; - ad-activate to activate the advice of a FUNCTION
849 ;; - ad-deactivate to deactivate the advice of a FUNCTION
850 ;; - ad-update to activate the advice of a FUNCTION unless it was not
851 ;; yet activated or is currently inactive.
852 ;; - ad-unadvise deactivates a FUNCTION and removes all of its advice
853 ;; information, hence, it cannot be activated again
854 ;; - ad-recover tries to redefine a FUNCTION to its original definition and
855 ;; discards all advice information (a low-level `ad-unadvise').
856 ;; Use only in emergencies.
858 ;; - ad-remove-advice removes a particular piece of advice of a FUNCTION.
859 ;; You still have to do call `ad-activate' or `ad-update' to
860 ;; activate the new state of advice.
861 ;; - ad-enable-advice enables a particular piece of advice of a FUNCTION.
862 ;; - ad-disable-advice disables a particular piece of advice of a FUNCTION.
863 ;; - ad-enable-regexp maps over all currently advised functions and enables
864 ;; every advice whose name contains a match for a regular
866 ;; - ad-disable-regexp disables matching advices.
868 ;; - ad-activate-regexp activates all advised function with a matching advice
869 ;; - ad-deactivate-regexp deactivates all advised function with matching advice
870 ;; - ad-update-regexp updates all advised function with a matching advice
871 ;; - ad-activate-all activates all advised functions
872 ;; - ad-deactivate-all deactivates all advised functions
873 ;; - ad-update-all updates all advised functions
874 ;; - ad-unadvise-all unadvises all advised functions
875 ;; - ad-recover-all recovers all advised functions
877 ;; - ad-compile byte-compiles a function/macro if it is compilable.
879 ;; @@ Summary of forms with special meanings when used within an advice:
880 ;; =====================================================================
881 ;; ad-return-value name of the return value variable (get/settable)
882 ;; (ad-get-arg <pos>), (ad-get-args <pos>),
883 ;; (ad-set-arg <pos> <value>), (ad-set-args <pos> <value-list>)
884 ;; argument access text macros to get/set the values of
885 ;; actual arguments at a certain position
886 ;; ad-arg-bindings text macro that returns the actual names, values
887 ;; and types of the arguments as a list of bindings. The
888 ;; order of the bindings corresponds to the order of the
889 ;; arguments. The individual fields of every binding (name,
890 ;; value and type) can be accessed with the function
891 ;; `ad-arg-binding-field' (see example above).
892 ;; ad-do-it text macro that identifies the place where the original
893 ;; or wrapped definition should go in an around advice
896 ;; @ Foo games: An advice tutorial
897 ;; ===============================
898 ;; The following tutorial was created in Emacs 18.59. Left-justified
899 ;; s-expressions are input forms followed by one or more result forms.
900 ;; First we have to start the advice magic:
905 ;; We start by defining an innocent looking function `foo' that simply
906 ;; adds 1 to its argument X:
916 ;; @@ Defining a simple piece of advice:
917 ;; =====================================
918 ;; Now let's define the first piece of advice for `foo'. To do that we
919 ;; use the macro `defadvice' which takes a function name, a list of advice
920 ;; specifiers and a list of body forms as arguments. The first element of
921 ;; the advice specifiers is the class of the advice, the second is its name,
922 ;; the third its position and the rest are some flags. The class of our
923 ;; first advice is `before', its name is `fg-add2', its position among the
924 ;; currently defined before advices (none so far) is `first', and the advice
925 ;; will be `activate'ed immediately. Advice names are global symbols, hence,
926 ;; the name space conventions used for function names should be applied. All
927 ;; advice names in this tutorial will be prefixed with `fg' for `Foo Games'
928 ;; (because everybody has the right to be inconsistent all the function names
929 ;; used in this tutorial do NOT follow this convention).
931 ;; In the body of an advice we can refer to the argument variables of the
932 ;; original function by name. Here we add 1 to X so the effect of calling
933 ;; `foo' will be to actually add 2. All of the advice definitions below only
934 ;; have one body form for simplicity, but there is no restriction to that
935 ;; extent. Every piece of advice can have a documentation string which will
936 ;; be combined with the documentation of the original function.
938 ;; (defadvice foo (before fg-add2 first activate)
946 ;; @@ Specifying the position of an advice:
947 ;; ========================================
948 ;; Now we define the second before advice which will cancel the effect of
949 ;; the previous advice. This time we specify the position as 0 which is
950 ;; equivalent to `first'. A number can be used to specify the zero-based
951 ;; position of an advice among the list of advices in the same class. This
952 ;; time we already have one before advice hence the position specification
953 ;; actually has an effect. So, after the following definition the position
954 ;; of the previous advice will be 1 even though we specified it with `first'
955 ;; above, the reason for this is that the position argument is relative to
956 ;; the currently defined pieces of advice which by now has changed.
958 ;; (defadvice foo (before fg-cancel-add2 0 activate)
959 ;; "Again only add 1 to X."
966 ;; @@ Redefining a piece of advice:
967 ;; ================================
968 ;; Now we define an advice with the same class and same name but with a
969 ;; different position. Defining an advice in a class in which an advice with
970 ;; that name already exists is interpreted as a redefinition of that
971 ;; particular advice, in which case the position argument will be ignored
972 ;; and the previous position of the redefined piece of advice is used.
973 ;; Advice flags can be specified with non-ambiguous initial substrings, hence,
974 ;; from now on we'll use `act' instead of the verbose `activate'.
976 ;; (defadvice foo (before fg-cancel-add2 last act)
977 ;; "Again only add 1 to X."
981 ;; @@ Assembly of advised documentation:
982 ;; =====================================
983 ;; The documentation strings of the various pieces of advice are assembled
984 ;; in order which shows that advice `fg-cancel-add2' is still the first
985 ;; `before' advice even though we specified position `last' above:
987 ;; (documentation 'foo)
990 ;; This function is advised with the following advice(s):
992 ;; fg-cancel-add2 (before):
993 ;; Again only add 1 to X.
998 ;; @@ Advising interactive behavior:
999 ;; =================================
1000 ;; We can make a function interactive (or change its interactive behavior)
1001 ;; by specifying an interactive form in one of the before or around
1002 ;; advices (there could also be body forms in this advice). The particular
1003 ;; definition always assigns 5 as an argument to X which gives us 6 as a
1004 ;; result when we call foo interactively:
1006 ;; (defadvice foo (before fg-inter last act)
1007 ;; "Use 5 as argument when called interactively."
1008 ;; (interactive (list 5)))
1011 ;; (call-interactively 'foo)
1014 ;; If more than one advice have an interactive declaration, then the one of
1015 ;; the advice with the smallest position will be used (before advices go
1016 ;; before around and after advices), hence, the declaration below does
1017 ;; not have any effect:
1019 ;; (defadvice foo (before fg-inter2 last act)
1020 ;; (interactive (list 6)))
1023 ;; (call-interactively 'foo)
1026 ;; Let's have a look at what the definition of `foo' looks like now
1027 ;; (indentation added by hand for legibility):
1029 ;; (symbol-function 'foo)
1032 ;; (interactive (list 5))
1033 ;; (let (ad-return-value)
1036 ;; (setq ad-return-value (ad-Orig-foo x))
1037 ;; ad-return-value))
1039 ;; @@ Around advices:
1040 ;; ==================
1041 ;; Now we'll try some `around' advices. An around advice is a wrapper around
1042 ;; the original definition. It can shadow or establish bindings for the
1043 ;; original definition, and it can look at and manipulate the value returned
1044 ;; by the original function. The position of the special keyword `ad-do-it'
1045 ;; specifies where the code of the original function will be executed. The
1046 ;; keyword can appear multiple times which will result in multiple calls of
1047 ;; the original function in the resulting advised code. Note, that if we don't
1048 ;; specify a position argument (i.e., `first', `last' or a number), then
1049 ;; `first' (or 0) is the default):
1051 ;; (defadvice foo (around fg-times-2 act)
1052 ;; "First double X."
1053 ;; (let ((x (* x 2)))
1060 ;; Around advices are assembled like onion skins where the around advice
1061 ;; with position 0 is the outermost skin and the advice at the last position
1062 ;; is the innermost skin which is directly wrapped around the call of the
1063 ;; original definition of the function. Hence, after the next `defadvice' we
1064 ;; will first multiply X by 2 then add 1 and then call the original
1065 ;; definition (i.e., add 1 again):
1067 ;; (defadvice foo (around fg-add-1 last act)
1069 ;; (let ((x (1+ x)))
1076 ;; Again, let's see what the definition of `foo' looks like so far:
1078 ;; (symbol-function 'foo)
1081 ;; (interactive (list 5))
1082 ;; (let (ad-return-value)
1085 ;; (let ((x (* x 2)))
1086 ;; (let ((x (1+ x)))
1087 ;; (setq ad-return-value (ad-Orig-foo x))))
1088 ;; ad-return-value))
1090 ;; @@ Controlling advice activation:
1091 ;; =================================
1092 ;; In every `defadvice' so far we have used the flag `activate' to activate
1093 ;; the advice immediately after its definition, and that's what we want in
1094 ;; most cases. However, if we define multiple pieces of advice for a single
1095 ;; function then activating every advice immediately is inefficient. A
1096 ;; better way to do this is to only activate the last defined advice.
1099 ;; (defadvice foo (after fg-times-x)
1100 ;; "Multiply the result with X."
1101 ;; (setq ad-return-value (* ad-return-value x)))
1104 ;; This still yields the same result as before:
1108 ;; Now we define another advice and activate which will also activate the
1109 ;; previous advice `fg-times-x'. Note the use of the special variable
1110 ;; `ad-return-value' in the body of the advice which is set to the result of
1111 ;; the original function. If we change its value then the value returned by
1112 ;; the advised function will be changed accordingly:
1114 ;; (defadvice foo (after fg-times-x-again act)
1115 ;; "Again multiply the result with X."
1116 ;; (setq ad-return-value (* ad-return-value x)))
1119 ;; Now the advices have an effect:
1124 ;; @@ Protecting advice execution:
1125 ;; ===============================
1126 ;; Once in a while we define an advice to perform some cleanup action,
1129 ;; (defadvice foo (after fg-cleanup last act)
1130 ;; "Do some cleanup."
1131 ;; (print "Let's clean up now!"))
1134 ;; However, in case of an error the cleanup won't be performed:
1136 ;; (condition-case error
1138 ;; (error 'error-in-foo))
1141 ;; To make sure a certain piece of advice gets executed even if some error or
1142 ;; non-local exit occurred in any preceding code, we can protect it by using
1143 ;; the `protect' keyword. (if any of the around advices is protected then the
1144 ;; whole around advice onion will be protected):
1146 ;; (defadvice foo (after fg-cleanup prot act)
1147 ;; "Do some protected cleanup."
1148 ;; (print "Let's clean up now!"))
1151 ;; Now the cleanup form will be executed even in case of an error:
1153 ;; (condition-case error
1155 ;; (error 'error-in-foo))
1156 ;; "Let's clean up now!"
1159 ;; Again, let's see what `foo' looks like:
1161 ;; (symbol-function 'foo)
1164 ;; (interactive (list 5))
1165 ;; (let (ad-return-value)
1167 ;; (progn (setq x (1- x))
1169 ;; (let ((x (* x 2)))
1170 ;; (let ((x (1+ x)))
1171 ;; (setq ad-return-value (ad-Orig-foo x))))
1172 ;; (setq ad-return-value (* ad-return-value x))
1173 ;; (setq ad-return-value (* ad-return-value x)))
1174 ;; (print "Let's clean up now!"))
1175 ;; ad-return-value))
1177 ;; @@ Compilation of advised definitions:
1178 ;; ======================================
1179 ;; Finally, we can specify the `compile' keyword in a `defadvice' to say
1180 ;; that we want the resulting advised function to be byte-compiled
1181 ;; (`compile' will be ignored unless we also specified `activate'):
1183 ;; (defadvice foo (after fg-cleanup prot act comp)
1184 ;; "Do some protected cleanup."
1185 ;; (print "Let's clean up now!"))
1188 ;; Now `foo' is byte-compiled:
1190 ;; (symbol-function 'foo)
1193 ;; (interactive (byte-code "....." [5] 1))
1194 ;; (byte-code "....." [ad-return-value x nil ((byte-code "....." [print "Let's clean up now!"] 2)) * 2 ad-Orig-foo] 6))
1197 ;; "Let's clean up now!"
1200 ;; @@ Enabling and disabling pieces of advice:
1201 ;; ===========================================
1202 ;; Once in a while it is desirable to temporarily disable a piece of advice
1203 ;; so that it won't be considered during activation, for example, if two
1204 ;; different packages advise the same function and one wants to temporarily
1205 ;; neutralize the effect of the advice of one of the packages.
1207 ;; The following disables the after advice `fg-times-x' in the function `foo'.
1208 ;; All that does is to change a flag for this particular advice. All the
1209 ;; other information defining it will be left unchanged (e.g., its relative
1210 ;; position in this advice class, etc.).
1212 ;; (ad-disable-advice 'foo 'after 'fg-times-x)
1215 ;; For this to have an effect we have to activate `foo':
1217 ;; (ad-activate 'foo)
1221 ;; "Let's clean up now!"
1224 ;; If we want to disable all multiplication advices in `foo' we can use a
1225 ;; regular expression that matches the names of such advices. Actually, any
1226 ;; advice name that contains a match for the regular expression will be
1227 ;; called a match. A special advice class `any' can be used to consider
1228 ;; all advice classes:
1230 ;; (ad-disable-advice 'foo 'any "^fg-.*times")
1233 ;; (ad-activate 'foo)
1237 ;; "Let's clean up now!"
1240 ;; To enable the disabled advice we could use either `ad-enable-advice'
1241 ;; similar to `ad-disable-advice', or as an alternative `ad-enable-regexp'
1242 ;; which will enable matching advices in ALL currently advised functions.
1243 ;; Hence, this can be used to dis/enable advices made by a particular
1244 ;; package to a set of functions as long as that package obeys standard
1245 ;; advice name conventions. We prefixed all advice names with `fg-', hence
1246 ;; the following will do the trick (`ad-enable-regexp' returns the number
1247 ;; of matched advices):
1249 ;; (ad-enable-regexp "^fg-")
1252 ;; The following will activate all currently active advised functions that
1253 ;; contain some advice matched by the regular expression. This is a save
1254 ;; way to update the activation of advised functions whose advice changed
1255 ;; in some way or other without accidentally also activating currently
1256 ;; inactive functions:
1258 ;; (ad-update-regexp "^fg-")
1262 ;; "Let's clean up now!"
1265 ;; Another use for the dis/enablement mechanism is to define a piece of advice
1266 ;; and keep it "dormant" until a particular condition is satisfied, i.e., until
1267 ;; then the advice will not be used during activation. The `disable' flag lets
1268 ;; one do that with `defadvice':
1270 ;; (defadvice foo (before fg-1-more dis)
1271 ;; "Add yet 1 more."
1275 ;; (ad-activate 'foo)
1279 ;; "Let's clean up now!"
1282 ;; (ad-enable-advice 'foo 'before 'fg-1-more)
1285 ;; (ad-activate 'foo)
1289 ;; "Let's clean up now!"
1294 ;; Advised definitions get cached to allow efficient activation/deactivation
1295 ;; without having to reconstruct them if nothing in the advice-info of a
1296 ;; function has changed. The following idiom can be used to temporarily
1297 ;; deactivate functions that have a piece of advice defined by a certain
1298 ;; package (we save the old definition to check out caching):
1300 ;; (setq old-definition (symbol-function 'foo))
1301 ;; (lambda (x) ....)
1303 ;; (ad-deactivate-regexp "^fg-")
1309 ;; (ad-activate-regexp "^fg-")
1312 ;; (eq old-definition (symbol-function 'foo))
1316 ;; "Let's clean up now!"
1319 ;; @@ Forward advice:
1320 ;; ==================
1321 ;; To enable automatic activation of forward advice we first have to set
1322 ;; `ad-activate-on-definition' to t and restart advice:
1324 ;; (setq ad-activate-on-definition t)
1327 ;; (ad-start-advice)
1328 ;; (ad-activate-defined-function)
1330 ;; Let's define a piece of advice for an undefined function:
1332 ;; (defadvice bar (before fg-sub-1-more act)
1333 ;; "Subtract one more from X."
1337 ;; `bar' is not yet defined:
1341 ;; Now we define it and the forward advice will get activated (only because
1342 ;; `ad-activate-on-definition' was t when we started advice above with
1343 ;; `ad-start-advice'):
1346 ;; "Subtract 1 from X."
1353 ;; Redefinition will activate any available advice if the value of
1354 ;; `ad-redefinition-action' is either `warn', `accept' or `discard':
1357 ;; "Subtract 2 from X."
1364 ;; @@ Preactivation:
1365 ;; =================
1366 ;; Constructing advised definitions is moderately expensive, hence, it is
1367 ;; desirable to have a way to construct them at byte-compile time.
1368 ;; Preactivation is a mechanism that allows one to do that.
1371 ;; "Multiply X by 2."
1375 ;; (defadvice fie (before fg-times-4 preact)
1376 ;; "Multiply X by 4."
1377 ;; (setq x (* x 2)))
1380 ;; This advice did not affect `fie'...
1385 ;; ...but it constructed a cached definition that will be used once `fie' gets
1386 ;; activated as long as its current advice state is the same as it was during
1389 ;; (setq cached-definition (ad-get-cache-definition 'fie))
1390 ;; (lambda (x) ....)
1392 ;; (ad-activate 'fie)
1395 ;; (eq cached-definition (symbol-function 'fie))
1401 ;; If you put a preactivating `defadvice' into a Lisp file that gets byte-
1402 ;; compiled then the constructed advised definition will get compiled by
1403 ;; the byte-compiler. For that to occur in a v18 emacs you have to put the
1404 ;; `defadvice' inside a `defun' because the v18 compiler does not compile
1405 ;; top-level forms other than `defun' or `defmacro', for example,
1407 ;; (defun fg-defadvice-fum ()
1408 ;; (defadvice fum (before fg-times-4 preact act)
1409 ;; "Multiply X by 4."
1410 ;; (setq x (* x 2))))
1413 ;; So far, no `defadvice' for `fum' got executed, but when we compile
1414 ;; `fg-defadvice-fum' the `defadvice' will be expanded by the byte compiler.
1415 ;; In order for preactivation to be effective we have to have a proper
1416 ;; definition of `fum' around at preactivation time, hence, we define it now:
1419 ;; "Multiply X by 2."
1423 ;; Now we compile the defining function which will construct an advised
1424 ;; definition during expansion of the `defadvice', compile it and store it
1425 ;; as part of the compiled `fg-defadvice-fum':
1427 ;; (ad-compile-function 'fg-defadvice-fum)
1428 ;; (lambda nil (byte-code ...))
1430 ;; `fum' is still completely unaffected:
1435 ;; (ad-get-advice-info 'fum)
1438 ;; (fg-defadvice-fum)
1441 ;; Now the advised version of `fum' is compiled because the compiled definition
1442 ;; constructed during preactivation was used, even though we did not specify
1443 ;; the `compile' flag:
1445 ;; (symbol-function 'fum)
1448 ;; (byte-code "....." [ad-return-value x nil * 2 ad-Orig-fum] 4))
1453 ;; A preactivated definition will only be used if it matches the current
1454 ;; function definition and advice information. If it does not match it
1455 ;; will simply be discarded and a new advised definition will be constructed
1456 ;; from scratch. For example, let's first remove all advice-info for `fum':
1458 ;; (ad-unadvise 'fum)
1459 ;; (("fie") ("bar") ("foo") ...)
1461 ;; And now define a new piece of advice:
1463 ;; (defadvice fum (before fg-interactive act)
1464 ;; "Make fum interactive."
1465 ;; (interactive "nEnter x: "))
1468 ;; When we now try to use a preactivation it will not be used because the
1469 ;; current advice state is different from the one at preactivation time. This
1470 ;; is no tragedy, everything will work as expected just not as efficient,
1471 ;; because a new advised definition has to be constructed from scratch:
1473 ;; (fg-defadvice-fum)
1476 ;; A new uncompiled advised definition got constructed:
1478 ;; (ad-compiled-p (symbol-function 'fum))
1484 ;; MORAL: To get all the efficiency out of preactivation the function
1485 ;; definition and advice state at preactivation time must be the same as the
1486 ;; state at activation time. Preactivation does work with forward advice, all
1487 ;; that's necessary is that the definition of the forward advised function is
1488 ;; available when the `defadvice' with the preactivation gets compiled.
1490 ;; @@ Portable argument access:
1491 ;; ============================
1492 ;; So far, we always used the actual argument variable names to access an
1493 ;; argument in a piece of advice. For many advice applications this is
1494 ;; perfectly ok and keeps advices simple. However, it decreases portability
1495 ;; of advices because it assumes specific argument variable names. For example,
1496 ;; if one advises a subr such as `eval-region' which then gets redefined by
1497 ;; some package (e.g., edebug) into a function with different argument names,
1498 ;; then a piece of advice written for `eval-region' that was written with
1499 ;; the subr arguments in mind will break. Similar situations arise when one
1500 ;; switches between major Emacs versions, e.g., certain subrs in v18 are
1501 ;; functions in v19 and vice versa. Also, in v19s subr argument lists
1502 ;; are available and will be used, while they are not available in v18.
1504 ;; Argument access text macros allow one to access arguments of an advised
1505 ;; function in a portable way without having to worry about all these
1506 ;; possibilities. These macros will be translated into the proper access forms
1507 ;; at activation time, hence, argument access will be as efficient as if
1508 ;; the arguments had been used directly in the definition of the advice.
1510 ;; (defun fuu (x y z)
1518 ;; Argument access macros specify actual arguments at a certain position.
1519 ;; Position 0 access the first actual argument, position 1 the second etc.
1520 ;; For example, the following advice adds 1 to each of the 3 arguments:
1522 ;; (defadvice fuu (before fg-add-1-to-all act)
1523 ;; "Adds 1 to all arguments."
1524 ;; (ad-set-arg 0 (1+ (ad-get-arg 0)))
1525 ;; (ad-set-arg 1 (1+ (ad-get-arg 1)))
1526 ;; (ad-set-arg 2 (1+ (ad-get-arg 2))))
1532 ;; Now suppose somebody redefines `fuu' with a rest argument. Our advice
1533 ;; will still work because we used access macros (note, that automatic
1534 ;; advice activation is still in effect, hence, the redefinition of `fuu'
1535 ;; will automatically activate all its advice):
1537 ;; (defun fuu (&rest numbers)
1539 ;; (apply '+ numbers))
1545 ;; (fuu 1 1 1 1 1 1)
1548 ;; What's important to notice is that argument access macros access actual
1549 ;; arguments regardless of how they got distributed onto argument variables.
1550 ;; In Emacs Lisp the semantics of an actual argument is determined purely
1551 ;; by position, hence, as long as nobody changes the semantics of what a
1552 ;; certain actual argument at a certain position means the access macros
1553 ;; will do the right thing.
1555 ;; Because of &rest arguments we need a second kind of access macro that
1556 ;; can access all actual arguments starting from a certain position:
1558 ;; (defadvice fuu (before fg-print-args act)
1559 ;; "Print all arguments."
1560 ;; (print (ad-get-args 0)))
1567 ;; (defadvice fuu (before fg-set-args act)
1568 ;; "Swaps 2nd and 3rd arg and discards all the rest."
1569 ;; (ad-set-args 1 (list (ad-get-arg 2) (ad-get-arg 1))))
1572 ;; (fuu 1 2 3 4 4 4 4 4 4)
1576 ;; (defun fuu (x y z)
1584 ;; @@ Defining the argument list of an advised function:
1585 ;; =====================================================
1586 ;; Once in a while it might be desirable to advise a function and additionally
1587 ;; give it an extra argument that controls the advised code, for example, one
1588 ;; might want to make an interactive function sensitive to a prefix argument.
1589 ;; For such cases `defadvice' allows the specification of an argument list
1590 ;; for the advised function. Similar to the redefinition of interactive
1591 ;; behavior, the first argument list specification found in the list of before/
1592 ;; around/after advices will be used. Of course, the specified argument list
1593 ;; should be downward compatible with the original argument list, otherwise
1594 ;; functions that call the advised function with the original argument list
1595 ;; in mind will break.
1602 ;; Now we advise `fii' to use an optional second argument that controls the
1603 ;; amount of incrementing. A list following the (optional) position
1604 ;; argument of the advice will be interpreted as an argument list
1605 ;; specification. This means you cannot specify an empty argument list, and
1606 ;; why would you want to anyway?
1608 ;; (defadvice fii (before fg-inc-x (x &optional incr) act)
1609 ;; "Increment X by INCR (default is 1)."
1610 ;; (setq x (+ x (1- (or incr 1)))))
1619 ;; @@ Advising interactive subrs:
1620 ;; ==============================
1621 ;; For the most part there is no difference between advising functions and
1622 ;; advising subrs. There is one situation though where one might have to write
1623 ;; slightly different advice code for subrs than for functions. This case
1624 ;; arises when one wants to access subr arguments in a before/around advice
1625 ;; when the arguments were determined by an interactive call to the subr.
1626 ;; Advice cannot determine what `interactive' form determines the interactive
1627 ;; behavior of the subr, hence, when it calls the original definition in an
1628 ;; interactive subr invocation it has to use `call-interactively' to generate
1629 ;; the proper interactive behavior. Thus up to that call the arguments of the
1630 ;; interactive subr will be nil. For example, the following advice for
1631 ;; `kill-buffer' will not work in an interactive invocation...
1633 ;; (defadvice kill-buffer (before fg-kill-buffer-hook first act preact comp)
1634 ;; (my-before-kill-buffer-hook (ad-get-arg 0)))
1637 ;; ...because the buffer argument will be nil in that case. The way out of
1638 ;; this dilemma is to provide an `interactive' specification that mirrors
1639 ;; the interactive behavior of the unadvised subr, for example, the following
1640 ;; will do the right thing even when `kill-buffer' is called interactively:
1642 ;; (defadvice kill-buffer (before fg-kill-buffer-hook first act preact comp)
1643 ;; (interactive "bKill buffer: ")
1644 ;; (my-before-kill-buffer-hook (ad-get-arg 0)))
1647 ;; @@ Advising macros:
1648 ;; ===================
1649 ;; Advising macros is slightly different because there are two significant
1650 ;; time points in the invocation of a macro: Expansion and evaluation time.
1651 ;; For an advised macro instead of evaluating the original definition we
1652 ;; use `macroexpand', that is, changing argument values and binding
1653 ;; environments by pieces of advice has an affect during macro expansion
1654 ;; but not necessarily during evaluation. In particular, any side effects
1655 ;; of pieces of advice will occur during macro expansion. To also affect
1656 ;; the behavior during evaluation time one has to change the value of
1657 ;; `ad-return-value' in a piece of after advice. For example:
1659 ;; (defmacro foom (x)
1660 ;; (` (list (, x))))
1666 ;; (defadvice foom (before fg-print-x act)
1667 ;; "Print the value of X."
1671 ;; The following works as expected because evaluation immediately follows
1678 ;; However, the printing happens during expansion (or byte-compile) time:
1680 ;; (macroexpand '(foom '(a)))
1682 ;; (list (quote (a)))
1684 ;; If we want it to happen during evaluation time we have to do the
1685 ;; following (first remove the old advice):
1687 ;; (ad-remove-advice 'foom 'before 'fg-print-x)
1690 ;; (defadvice foom (after fg-print-x act)
1691 ;; "Print the value of X."
1692 ;; (setq ad-return-value
1693 ;; (` (progn (print (, x))
1694 ;; (, ad-return-value)))))
1697 ;; (macroexpand '(foom '(a)))
1698 ;; (progn (print (quote (a))) (list (quote (a))))
1704 ;; While this method might seem somewhat cumbersome, it is very general
1705 ;; because it allows one to influence macro expansion as well as evaluation.
1706 ;; In general, advising macros should be a rather rare activity anyway, in
1707 ;; particular, because compile-time macro expansion takes away a lot of the
1708 ;; flexibility and effectiveness of the advice mechanism. Macros that were
1709 ;; compile-time expanded before the advice was activated will of course never
1710 ;; exhibit the advised behavior.
1712 ;; @@ Advising special forms:
1713 ;; ==========================
1714 ;; Now for something that should be even more rare than advising macros:
1715 ;; Advising special forms. Because special forms are irregular in their
1716 ;; argument evaluation behavior (e.g., `setq' evaluates the second but not
1717 ;; the first argument) they have to be advised into macros. A dangerous
1718 ;; consequence of this is that the byte-compiler will not recognize them
1719 ;; as special forms anymore (well, in most cases) and use their expansion
1720 ;; rather than the proper byte-code. Also, because the original definition
1721 ;; of a special form cannot be `funcall'ed, `eval' has to be used instead
1722 ;; which is less efficient.
1724 ;; MORAL: Do not advise special forms unless you are completely sure about
1725 ;; what you are doing (some of the forward advice behavior is
1726 ;; implemented via advice of the special forms `defun' and `defmacro').
1727 ;; As a safety measure one should always do `ad-deactivate-all' before
1728 ;; one byte-compiles a file to avoid any interference of advised
1731 ;; Apart from the safety concerns advising special forms is not any different
1732 ;; from advising plain functions or subrs.
1737 ;; @ Advice implementation:
1738 ;; ========================
1740 ;; @@ Compilation idiosyncrasies:
1741 ;; ==============================
1743 ;; `defadvice' expansion needs quite a few advice functions and variables,
1744 ;; hence, I need to preload the file before it can be compiled. To avoid
1745 ;; interference of bogus compiled files I always preload the source file:
1746 (provide 'advice-preload
)
1747 ;; During a normal load this is a noop:
1748 (require 'advice-preload
"advice.el")
1750 (eval-when-compile (require 'cl-lib
))
1752 ;; @@ Variable definitions:
1753 ;; ========================
1755 (defgroup advice nil
1756 "An overloading mechanism for Emacs Lisp functions."
1758 :link
'(custom-manual "(elisp)Advising Functions")
1761 (defconst ad-version
"2.14")
1764 (defcustom ad-redefinition-action
'warn
1765 "Defines what to do with redefinitions during Advice de/activation.
1766 Redefinition occurs if a previously activated function that already has an
1767 original definition associated with it gets redefined and then de/activated.
1768 In such a case we can either accept the current definition as the new
1769 original definition, discard the current definition and replace it with the
1770 old original, or keep it and raise an error. The values `accept', `discard',
1771 `error' or `warn' govern what will be done. `warn' is just like `accept' but
1772 it additionally prints a warning message. All other values will be
1773 interpreted as `error'."
1774 :type
'(choice (const accept
) (const discard
) (const warn
)
1775 (other :tag
"error" error
))
1779 (defcustom ad-default-compilation-action
'maybe
1780 "Defines whether to compile advised definitions during activation.
1781 A value of `always' will result in unconditional compilation, `never' will
1782 always avoid compilation, `maybe' will compile if the byte-compiler is already
1783 loaded, and `like-original' will compile if the original definition of the
1784 advised function is compiled or a built-in function. Every other value will
1785 be interpreted as `maybe'. This variable will only be considered if the
1786 COMPILE argument of `ad-activate' was supplied as nil."
1787 :type
'(choice (const always
) (const never
) (const like-original
)
1788 (other :tag
"maybe" maybe
))
1793 ;; @@ Some utilities:
1794 ;; ==================
1796 ;; We don't want the local arguments to interfere with anything
1797 ;; referenced in the supplied functions => the cryptic casing:
1798 (defun ad-substitute-tree (sUbTrEe-TeSt fUnCtIoN tReE
)
1799 "Substitute qualifying subTREEs with result of FUNCTION(subTREE).
1800 Only proper subtrees are considered, for example, if TREE is (1 (2 (3)) 4)
1801 then the subtrees will be 1 (2 (3)) 2 (3) 3 4, dotted structures are
1802 allowed too. Once a qualifying subtree has been found its subtrees will
1803 not be considered anymore. (ad-substitute-tree 'atom 'identity tree)
1804 generates a copy of TREE."
1806 (cons (if (funcall sUbTrEe-TeSt
(car tReE
))
1807 (funcall fUnCtIoN
(car tReE
))
1808 (if (consp (car tReE
))
1809 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN
(car tReE
))
1811 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN
(cdr tReE
))))
1812 ((funcall sUbTrEe-TeSt tReE
)
1813 (funcall fUnCtIoN tReE
))
1816 ;; @@ Save real definitions of subrs used by Advice:
1817 ;; =================================================
1818 ;; Advice depends on the real, unmodified functionality of various subrs,
1819 ;; we save them here so advised versions will not interfere (eventually,
1820 ;; we will save all subrs used in code generated by Advice):
1822 (defmacro ad-save-real-definition
(function)
1823 (let ((saved-function (intern (format "ad-real-%s" function
))))
1824 ;; Make sure the compiler is loaded during macro expansion:
1825 (require 'byte-compile
"bytecomp")
1826 `(if (not (fboundp ',saved-function
))
1827 (progn (fset ',saved-function
(symbol-function ',function
))
1828 ;; Copy byte-compiler properties:
1829 ,@(if (get function
'byte-compile
)
1830 `((put ',saved-function
'byte-compile
1831 ',(get function
'byte-compile
))))
1832 ,@(if (get function
'byte-opcode
)
1833 `((put ',saved-function
'byte-opcode
1834 ',(get function
'byte-opcode
))))))))
1836 (defun ad-save-real-definitions ()
1837 ;; Macro expansion will hardcode the values of the various byte-compiler
1838 ;; properties into the compiled version of this function such that the
1839 ;; proper values will be available at runtime without loading the compiler:
1840 (ad-save-real-definition fset
)
1841 (ad-save-real-definition documentation
))
1843 (ad-save-real-definitions)
1846 ;; @@ Advice info access fns:
1847 ;; ==========================
1849 ;; Advice information for a particular function is stored on the
1850 ;; advice-info property of the function symbol. It is stored as an
1851 ;; alist of the following format:
1853 ;; ((active . t/nil)
1854 ;; (before adv1 adv2 ...)
1855 ;; (around adv1 adv2 ...)
1856 ;; (after adv1 adv2 ...)
1857 ;; (activation adv1 adv2 ...)
1858 ;; (deactivation adv1 adv2 ...)
1859 ;; (origname . <symbol fbound to origdef>)
1860 ;; (cache . (<advised-definition> . <id>)))
1862 ;; List of currently advised though not necessarily activated functions
1863 ;; (this list is maintained as a completion table):
1864 (defvar ad-advised-functions nil
)
1866 (defmacro ad-pushnew-advised-function
(function)
1867 "Add FUNCTION to `ad-advised-functions' unless its already there."
1868 `(if (not (assoc (symbol-name ,function
) ad-advised-functions
))
1869 (setq ad-advised-functions
1870 (cons (list (symbol-name ,function
))
1871 ad-advised-functions
))))
1873 (defmacro ad-pop-advised-function
(function)
1874 "Remove FUNCTION from `ad-advised-functions'."
1875 `(setq ad-advised-functions
1876 (delq (assoc (symbol-name ,function
) ad-advised-functions
)
1877 ad-advised-functions
)))
1879 (defmacro ad-do-advised-functions
(varform &rest body
)
1880 "`dolist'-style iterator that maps over `ad-advised-functions'.
1881 \(ad-do-advised-functions (VAR [RESULT-FORM])
1883 On each iteration VAR will be bound to the name of an advised function
1885 `(cl-dolist (,(car varform
)
1886 ad-advised-functions
1887 ,(car (cdr varform
)))
1888 (setq ,(car varform
) (intern (car ,(car varform
))))
1891 (if (not (get 'ad-do-advised-functions
'lisp-indent-hook
))
1892 (put 'ad-do-advised-functions
'lisp-indent-hook
1))
1894 (defun ad-get-advice-info (function)
1895 (get function
'ad-advice-info
))
1897 (defmacro ad-get-advice-info-macro
(function)
1898 `(get ,function
'ad-advice-info
))
1900 (defmacro ad-set-advice-info
(function advice-info
)
1901 `(put ,function
'ad-advice-info
,advice-info
))
1903 (defmacro ad-copy-advice-info
(function)
1904 `(copy-tree (get ,function
'ad-advice-info
)))
1906 (defmacro ad-is-advised
(function)
1907 "Return non-nil if FUNCTION has any advice info associated with it.
1908 This does not mean that the advice is also active."
1909 (list 'ad-get-advice-info-macro function
))
1911 (defun ad-initialize-advice-info (function)
1912 "Initialize the advice info for FUNCTION.
1913 Assumes that FUNCTION has not yet been advised."
1914 (ad-pushnew-advised-function function
)
1915 (ad-set-advice-info function
(list (cons 'active nil
))))
1917 (defmacro ad-get-advice-info-field
(function field
)
1918 "Retrieve the value of the advice info FIELD of FUNCTION."
1919 `(cdr (assq ,field
(ad-get-advice-info-macro ,function
))))
1921 (defun ad-set-advice-info-field (function field value
)
1922 "Destructively modify VALUE of the advice info FIELD of FUNCTION."
1923 (and (ad-is-advised function
)
1924 (cond ((assq field
(ad-get-advice-info-macro function
))
1925 ;; A field with that name is already present:
1926 (rplacd (assq field
(ad-get-advice-info-macro function
)) value
))
1927 (t;; otherwise, create a new field with that name:
1928 (nconc (ad-get-advice-info-macro function
)
1929 (list (cons field value
)))))))
1931 ;; Don't make this a macro so we can use it as a predicate:
1932 (defun ad-is-active (function)
1933 "Return non-nil if FUNCTION is advised and activated."
1934 (ad-get-advice-info-field function
'active
))
1937 ;; @@ Access fns for single pieces of advice and related predicates:
1938 ;; =================================================================
1940 (defun ad-make-advice (name protect enable definition
)
1941 "Constructs single piece of advice to be stored in some advice-info.
1942 NAME should be a non-nil symbol, PROTECT and ENABLE should each be
1943 either t or nil, and DEFINITION should be a list of the form
1944 `(advice lambda ARGLIST [DOCSTRING] [INTERACTIVE-FORM] BODY...)'."
1945 (list name protect enable definition
))
1947 ;; ad-find-advice uses the alist structure directly ->
1948 ;; change if this data structure changes!!
1949 (defmacro ad-advice-name
(advice)
1951 (defmacro ad-advice-protected
(advice)
1952 (list 'nth
1 advice
))
1953 (defmacro ad-advice-enabled
(advice)
1954 (list 'nth
2 advice
))
1955 (defmacro ad-advice-definition
(advice)
1956 (list 'nth
3 advice
))
1958 (defun ad-advice-set-enabled (advice flag
)
1959 (rplaca (cdr (cdr advice
)) flag
))
1961 (defun ad-class-p (thing)
1962 (memq thing ad-advice-classes
))
1963 (defun ad-name-p (thing)
1964 (and thing
(symbolp thing
)))
1965 (defun ad-position-p (thing)
1967 (memq thing
'(first last
))))
1970 ;; @@ Advice access functions:
1971 ;; ===========================
1973 ;; List of defined advice classes:
1974 (defvar ad-advice-classes
'(before around after activation deactivation
))
1976 (defun ad-has-enabled-advice (function class
)
1977 "True if at least one of FUNCTION's advices in CLASS is enabled."
1978 (cl-dolist (advice (ad-get-advice-info-field function class
))
1979 (if (ad-advice-enabled advice
) (cl-return t
))))
1981 (defun ad-has-redefining-advice (function)
1982 "True if FUNCTION's advice info defines at least 1 redefining advice.
1983 Redefining advices affect the construction of an advised definition."
1984 (and (ad-is-advised function
)
1985 (or (ad-has-enabled-advice function
'before
)
1986 (ad-has-enabled-advice function
'around
)
1987 (ad-has-enabled-advice function
'after
))))
1989 (defun ad-has-any-advice (function)
1990 "True if the advice info of FUNCTION defines at least one advice."
1991 (and (ad-is-advised function
)
1992 (cl-dolist (class ad-advice-classes nil
)
1993 (if (ad-get-advice-info-field function class
)
1996 (defun ad-get-enabled-advices (function class
)
1997 "Return the list of enabled advices of FUNCTION in CLASS."
1998 (let (enabled-advices)
1999 (dolist (advice (ad-get-advice-info-field function class
))
2000 (if (ad-advice-enabled advice
)
2001 (push advice enabled-advices
)))
2002 (reverse enabled-advices
)))
2005 ;; @@ Dealing with automatic advice activation via `fset/defalias':
2006 ;; ================================================================
2008 ;; Since Emacs 19.26 the built-in versions of `fset' and `defalias'
2009 ;; take care of automatic advice activation, hence, we don't have to
2010 ;; hack it anymore by advising `fset/defun/defmacro/byte-code/etc'.
2012 ;; The functionality of the new `fset' is as follows:
2015 ;; assign NEWDEF to SYM
2016 ;; if (get SYM 'ad-advice-info)
2017 ;; ad-activate-internal(SYM, nil)
2018 ;; return (symbol-function SYM)
2020 ;; Whether advised definitions created by automatic activations will be
2021 ;; compiled depends on the value of `ad-default-compilation-action'.
2023 ;; Since calling `ad-activate-internal' in the built-in definition of `fset' can
2024 ;; create major disasters we have to be a bit careful. One precaution is
2025 ;; to provide a dummy definition for `ad-activate-internal' which can be used to
2026 ;; turn off automatic advice activation (e.g., when `ad-stop-advice' or
2027 ;; `ad-recover-normality' are called). Another is to avoid recursive calls
2028 ;; to `ad-activate' by using `ad-with-auto-activation-disabled' where
2029 ;; appropriate, especially in a safe version of `fset'.
2031 ;; For now define `ad-activate-internal' to the dummy definition:
2032 (defun ad-activate-internal (function &optional compile
)
2033 "Automatic advice activation is disabled. `ad-start-advice' enables it."
2036 ;; This is just a copy of the above:
2037 (defun ad-activate-internal-off (function &optional compile
)
2038 "Automatic advice activation is disabled. `ad-start-advice' enables it."
2041 ;; This will be t for top-level calls to `ad-activate-internal-on':
2042 (defvar ad-activate-on-top-level t
)
2044 (defmacro ad-with-auto-activation-disabled
(&rest body
)
2045 `(let ((ad-activate-on-top-level nil
))
2048 (defun ad-safe-fset (symbol definition
)
2049 "A safe `fset' which will never call `ad-activate-internal' recursively."
2050 (ad-with-auto-activation-disabled
2051 (ad-real-fset symbol definition
)))
2054 ;; @@ Access functions for original definitions:
2055 ;; ============================================
2056 ;; The advice-info of an advised function contains its `origname' which is
2057 ;; a symbol that is fbound to the original definition available at the first
2058 ;; proper activation of the function after a valid re/definition. If the
2059 ;; original was defined via fcell indirection then `origname' will be defined
2060 ;; just so. Hence, to get hold of the actual original definition of a function
2061 ;; we need to use `ad-real-orig-definition'.
2063 (defun ad-make-origname (function)
2064 "Make name to be used to call the original FUNCTION."
2065 (intern (format "ad-Orig-%s" function
)))
2067 (defmacro ad-get-orig-definition
(function)
2068 `(let ((origname (ad-get-advice-info-field ,function
'origname
)))
2069 (if (fboundp origname
)
2070 (symbol-function origname
))))
2072 (defmacro ad-set-orig-definition
(function definition
)
2074 (ad-get-advice-info-field ,function
'origname
) ,definition
))
2076 (defmacro ad-clear-orig-definition
(function)
2077 `(fmakunbound (ad-get-advice-info-field ,function
'origname
)))
2080 ;; @@ Interactive input functions:
2081 ;; ===============================
2083 (declare-function 'function-called-at-point
"help")
2085 (defun ad-read-advised-function (&optional prompt predicate default
)
2086 "Read name of advised function with completion from the minibuffer.
2087 An optional PROMPT will be used to prompt for the function. PREDICATE
2088 plays the same role as for `try-completion' (which see). DEFAULT will
2089 be returned on empty input (defaults to the first advised function or
2090 function at point for which PREDICATE returns non-nil)."
2091 (if (null ad-advised-functions
)
2092 (error "ad-read-advised-function: There are no advised functions"))
2095 ;; Prefer func name at point, if it's in ad-advised-functions etc.
2096 (let ((function (progn
2098 (function-called-at-point))))
2100 (assoc (symbol-name function
) ad-advised-functions
)
2101 (or (null predicate
)
2102 (funcall predicate function
))
2104 (ad-do-advised-functions (function)
2105 (if (or (null predicate
)
2106 (funcall predicate function
))
2107 (cl-return function
)))
2108 (error "ad-read-advised-function: %s"
2109 "There are no qualifying advised functions")))
2110 (let* ((ad-pReDiCaTe predicate
)
2113 (format "%s (default %s): " (or prompt
"Function") default
)
2114 ad-advised-functions
2118 ;; Oops, no closures - the joys of dynamic scoping:
2119 ;; `predicate' clashed with the `predicate' argument
2120 ;; of Lemacs' `completing-read'.....
2121 (funcall ad-pReDiCaTe
(intern (car function
))))))
2123 (if (equal function
"")
2124 (if (ad-is-advised default
)
2126 (error "ad-read-advised-function: `%s' is not advised" default
))
2127 (intern function
))))
2129 (defvar ad-advice-class-completion-table
2130 (mapcar (lambda (class) (list (symbol-name class
)))
2133 (defun ad-read-advice-class (function &optional prompt default
)
2134 "Read a valid advice class with completion from the minibuffer.
2135 An optional PROMPT will be used to prompt for the class. DEFAULT will
2136 be returned on empty input (defaults to the first non-empty advice
2137 class of FUNCTION)."
2140 (cl-dolist (class ad-advice-classes
)
2141 (if (ad-get-advice-info-field function class
)
2143 (error "ad-read-advice-class: `%s' has no advices" function
)))
2144 (let ((class (completing-read
2145 (format "%s (default %s): " (or prompt
"Class") default
)
2146 ad-advice-class-completion-table nil t
)))
2147 (if (equal class
"")
2151 (defun ad-read-advice-name (function class
&optional prompt
)
2152 "Read name of existing advice of CLASS for FUNCTION with completion.
2153 An optional PROMPT is used to prompt for the name."
2154 (let* ((name-completion-table
2155 (mapcar (function (lambda (advice)
2156 (list (symbol-name (ad-advice-name advice
)))))
2157 (ad-get-advice-info-field function class
)))
2159 (if (null name-completion-table
)
2160 (error "ad-read-advice-name: `%s' has no %s advice"
2162 (car (car name-completion-table
))))
2163 (prompt (format "%s (default %s): " (or prompt
"Name") default
))
2164 (name (completing-read prompt name-completion-table nil t
)))
2169 (defun ad-read-advice-specification (&optional prompt
)
2170 "Read a complete function/class/name specification from minibuffer.
2171 The list of read symbols will be returned. The optional PROMPT will
2172 be used to prompt for the function."
2173 (let* ((function (ad-read-advised-function prompt
))
2174 (class (ad-read-advice-class function
))
2175 (name (ad-read-advice-name function class
)))
2176 (list function class name
)))
2178 ;; Use previous regexp as a default:
2179 (defvar ad-last-regexp
"")
2181 (defun ad-read-regexp (&optional prompt
)
2182 "Read a regular expression from the minibuffer."
2183 (let ((regexp (read-from-minibuffer
2184 (concat (or prompt
"Regular expression")
2185 (if (equal ad-last-regexp
"") ": "
2186 (format " (default %s): " ad-last-regexp
))))))
2187 (setq ad-last-regexp
2188 (if (equal regexp
"") ad-last-regexp regexp
))))
2191 ;; @@ Finding, enabling, adding and removing pieces of advice:
2192 ;; ===========================================================
2194 (defmacro ad-find-advice
(function class name
)
2195 "Find the first advice of FUNCTION in CLASS with NAME."
2196 `(assq ,name
(ad-get-advice-info-field ,function
,class
)))
2198 (defun ad-advice-position (function class name
)
2199 "Return position of first advice of FUNCTION in CLASS with NAME."
2200 (let* ((found-advice (ad-find-advice function class name
))
2201 (advices (ad-get-advice-info-field function class
)))
2203 (- (length advices
) (length (memq found-advice advices
))))))
2205 (defun ad-find-some-advice (function class name
)
2206 "Find the first of FUNCTION's advices in CLASS matching NAME.
2207 NAME can be a symbol or a regular expression matching part of an advice name.
2208 If CLASS is `any' all valid advice classes will be checked."
2209 (if (ad-is-advised function
)
2211 (cl-dolist (advice-class ad-advice-classes
)
2212 (if (or (eq class
'any
) (eq advice-class class
))
2214 (cl-dolist (advice (ad-get-advice-info-field
2215 function advice-class
))
2216 (if (or (and (stringp name
)
2219 (ad-advice-name advice
))))
2220 (eq name
(ad-advice-name advice
)))
2221 (cl-return advice
)))))
2222 (if found-advice
(cl-return found-advice
))))))
2224 (defun ad-enable-advice-internal (function class name flag
)
2225 "Set enable FLAG of FUNCTION's advices in CLASS matching NAME.
2226 If NAME is a string rather than a symbol then it's interpreted as a regular
2227 expression and all advices whose name contain a match for it will be
2228 affected. If CLASS is `any' advices in all valid advice classes will be
2229 considered. The number of changed advices will be returned (or nil if
2230 FUNCTION was not advised)."
2231 (if (ad-is-advised function
)
2232 (let ((matched-advices 0))
2233 (dolist (advice-class ad-advice-classes
)
2234 (if (or (eq class
'any
) (eq advice-class class
))
2235 (dolist (advice (ad-get-advice-info-field
2236 function advice-class
))
2237 (cond ((or (and (stringp name
)
2239 name
(symbol-name (ad-advice-name advice
))))
2240 (eq name
(ad-advice-name advice
)))
2241 (setq matched-advices
(1+ matched-advices
))
2242 (ad-advice-set-enabled advice flag
))))))
2246 (defun ad-enable-advice (function class name
)
2247 "Enables the advice of FUNCTION with CLASS and NAME."
2248 (interactive (ad-read-advice-specification "Enable advice of"))
2249 (if (ad-is-advised function
)
2250 (if (eq (ad-enable-advice-internal function class name t
) 0)
2251 (error "ad-enable-advice: `%s' has no %s advice matching `%s'"
2252 function class name
))
2253 (error "ad-enable-advice: `%s' is not advised" function
)))
2256 (defun ad-disable-advice (function class name
)
2257 "Disable the advice of FUNCTION with CLASS and NAME."
2258 (interactive (ad-read-advice-specification "Disable advice of"))
2259 (if (ad-is-advised function
)
2260 (if (eq (ad-enable-advice-internal function class name nil
) 0)
2261 (error "ad-disable-advice: `%s' has no %s advice matching `%s'"
2262 function class name
))
2263 (error "ad-disable-advice: `%s' is not advised" function
)))
2265 (defun ad-enable-regexp-internal (regexp class flag
)
2266 "Set enable FLAGs of all CLASS advices whose name contains a REGEXP match.
2267 If CLASS is `any' all valid advice classes are considered. The number of
2268 affected advices will be returned."
2269 (let ((matched-advices 0))
2270 (ad-do-advised-functions (advised-function)
2271 (setq matched-advices
2273 (or (ad-enable-advice-internal
2274 advised-function class regexp flag
)
2278 (defun ad-enable-regexp (regexp)
2279 "Enables all advices with names that contain a match for REGEXP.
2280 All currently advised functions will be considered."
2282 (list (ad-read-regexp "Enable advices via regexp")))
2283 (let ((matched-advices (ad-enable-regexp-internal regexp
'any t
)))
2284 (if (called-interactively-p 'interactive
)
2285 (message "%d matching advices enabled" matched-advices
))
2288 (defun ad-disable-regexp (regexp)
2289 "Disable all advices with names that contain a match for REGEXP.
2290 All currently advised functions will be considered."
2292 (list (ad-read-regexp "Disable advices via regexp")))
2293 (let ((matched-advices (ad-enable-regexp-internal regexp
'any nil
)))
2294 (if (called-interactively-p 'interactive
)
2295 (message "%d matching advices disabled" matched-advices
))
2298 (defun ad-remove-advice (function class name
)
2299 "Remove FUNCTION's advice with NAME from its advices in CLASS.
2300 If such an advice was found it will be removed from the list of advices
2302 (interactive (ad-read-advice-specification "Remove advice of"))
2303 (if (ad-is-advised function
)
2304 (let ((advice-to-remove (ad-find-advice function class name
)))
2305 (if advice-to-remove
2306 (ad-set-advice-info-field
2308 (delq advice-to-remove
(ad-get-advice-info-field function class
)))
2309 (error "ad-remove-advice: `%s' has no %s advice `%s'"
2310 function class name
)))
2311 (error "ad-remove-advice: `%s' is not advised" function
)))
2314 (defun ad-add-advice (function advice class position
)
2315 "Add a piece of ADVICE to FUNCTION's list of advices in CLASS.
2317 ADVICE has the form (NAME PROTECTED ENABLED DEFINITION), where
2318 NAME is the advice name; PROTECTED is a flag specifying whether
2319 to protect against non-local exits; ENABLED is a flag specifying
2320 whether to initially enable the advice; and DEFINITION has the
2321 form (advice . LAMBDA), where LAMBDA is a lambda expression.
2323 If FUNCTION already has a piece of advice with the same name,
2324 then POSITION is ignored, and the old advice is overwritten with
2327 If FUNCTION already has one or more pieces of advice of the
2328 specified CLASS, then POSITION determines where the new piece
2329 goes. POSITION can either be `first', `last' or a number (where
2330 0 corresponds to `first', and numbers outside the valid range are
2331 mapped to the closest extremal position).
2333 If FUNCTION was not advised already, its advice info will be
2334 initialized. Redefining a piece of advice whose name is part of
2335 the cache-id will clear the cache.
2337 See Info node `(elisp)Computed Advice' for detailed documentation."
2338 (cond ((not (ad-is-advised function
))
2339 (ad-initialize-advice-info function
)
2340 (ad-set-advice-info-field
2341 function
'origname
(ad-make-origname function
))))
2342 (let* ((previous-position
2343 (ad-advice-position function class
(ad-advice-name advice
)))
2344 (advices (ad-get-advice-info-field function class
))
2345 ;; Determine a numerical position for the new advice:
2346 (position (cond (previous-position)
2347 ((eq position
'first
) 0)
2348 ((eq position
'last
) (length advices
))
2350 (max 0 (min position
(length advices
))))
2352 ;; Check whether we have to clear the cache:
2353 (if (memq (ad-advice-name advice
) (ad-get-cache-class-id function class
))
2354 (ad-clear-cache function
))
2355 (if previous-position
2356 (setcar (nthcdr position advices
) advice
)
2358 (ad-set-advice-info-field function class
(cons advice advices
))
2359 (setcdr (nthcdr (1- position
) advices
)
2360 (cons advice
(nthcdr position advices
)))))))
2363 ;; @@ Accessing and manipulating function definitions:
2364 ;; ===================================================
2366 (defmacro ad-macrofy
(definition)
2367 "Take a lambda function DEFINITION and make a macro out of it."
2368 `(cons 'macro
,definition
))
2370 (defmacro ad-lambdafy
(definition)
2371 "Take a macro function DEFINITION and make a lambda out of it."
2374 (defun ad-special-form-p (definition)
2375 "Non-nil if and only if DEFINITION is a special form."
2376 (if (and (symbolp definition
) (fboundp definition
))
2377 (setq definition
(indirect-function definition
)))
2378 (and (subrp definition
) (eq (cdr (subr-arity definition
)) 'unevalled
)))
2380 (defmacro ad-subr-p
(definition)
2381 ;;"non-nil if DEFINITION is a subr."
2382 (list 'subrp definition
))
2384 (defmacro ad-macro-p
(definition)
2385 ;;"non-nil if DEFINITION is a macro."
2386 `(eq (car-safe ,definition
) 'macro
))
2388 (defmacro ad-lambda-p
(definition)
2389 ;;"non-nil if DEFINITION is a lambda expression."
2390 `(eq (car-safe ,definition
) 'lambda
))
2392 ;; see ad-make-advice for the format of advice definitions:
2393 (defmacro ad-advice-p
(definition)
2394 ;;"non-nil if DEFINITION is a piece of advice."
2395 `(eq (car-safe ,definition
) 'advice
))
2397 ;; Emacs/Lemacs cross-compatibility
2398 ;; (compiled-function-p is an obsolete function in Emacs):
2399 (if (and (not (fboundp 'byte-code-function-p
))
2400 (fboundp 'compiled-function-p
))
2401 (ad-safe-fset 'byte-code-function-p
'compiled-function-p
))
2403 (defmacro ad-compiled-p
(definition)
2404 "Return non-nil if DEFINITION is a compiled byte-code object."
2405 `(or (byte-code-function-p ,definition
)
2406 (and (ad-macro-p ,definition
)
2407 (byte-code-function-p (ad-lambdafy ,definition
)))))
2409 (defmacro ad-compiled-code
(compiled-definition)
2410 "Return the byte-code object of a COMPILED-DEFINITION."
2411 `(if (ad-macro-p ,compiled-definition
)
2412 (ad-lambdafy ,compiled-definition
)
2413 ,compiled-definition
))
2415 (defun ad-lambda-expression (definition)
2416 "Return the lambda expression of a function/macro/advice DEFINITION."
2417 (cond ((ad-lambda-p definition
)
2419 ((ad-macro-p definition
)
2420 (ad-lambdafy definition
))
2421 ((ad-advice-p definition
)
2425 (defun ad-arglist (definition &optional name
)
2426 "Return the argument list of DEFINITION.
2427 If DEFINITION could be from a subr then its NAME should be
2428 supplied to make subr arglist lookup more efficient."
2430 (help-function-arglist
2431 (if (or (ad-macro-p definition
) (ad-advice-p definition
))
2436 (defun ad-docstring (definition)
2437 "Return the unexpanded docstring of DEFINITION."
2439 (if (ad-compiled-p definition
)
2440 (ad-real-documentation definition t
)
2441 (car (cdr (cdr (ad-lambda-expression definition
)))))))
2442 (if (or (stringp docstring
)
2443 (natnump docstring
))
2446 (defun ad-interactive-form (definition)
2447 "Return the interactive form of DEFINITION.
2448 Like `interactive-form', but also works on pieces of advice."
2450 (if (ad-advice-p definition
)
2451 (ad-lambda-expression definition
)
2454 (defun ad-body-forms (definition)
2455 "Return the list of body forms of DEFINITION."
2456 (cond ((ad-compiled-p definition
)
2459 (nthcdr (+ (if (ad-docstring definition
) 1 0)
2460 (if (ad-interactive-form definition
) 1 0))
2461 (cdr (cdr (ad-lambda-expression definition
)))))))
2463 (defun ad-make-advised-definition-docstring (function)
2464 "Make an identifying docstring for the advised definition of FUNCTION.
2465 Put function name into the documentation string so we can infer
2466 the name of the advised function from the docstring. This is needed
2467 to generate a proper advised docstring even if we are just given a
2468 definition (see the code for `documentation')."
2469 (propertize "Advice doc string" 'ad-advice-info function
))
2471 (defun ad-advised-definition-p (definition)
2472 "Return non-nil if DEFINITION was generated from advice information."
2473 (if (or (ad-lambda-p definition
)
2474 (ad-macro-p definition
)
2475 (ad-compiled-p definition
))
2476 (let ((docstring (ad-docstring definition
)))
2477 (and (stringp docstring
)
2478 (get-text-property 0 'ad-advice-info docstring
)))))
2480 (defun ad-definition-type (definition)
2481 "Return symbol that describes the type of DEFINITION."
2483 ((ad-macro-p definition
) 'macro
)
2484 ((ad-subr-p definition
)
2485 (if (ad-special-form-p definition
)
2488 ((or (ad-lambda-p definition
)
2489 (ad-compiled-p definition
))
2491 ((ad-advice-p definition
) 'advice
)))
2493 (defun ad-has-proper-definition (function)
2494 "True if FUNCTION is a symbol with a proper definition.
2495 For that it has to be fbound with a non-autoload definition."
2496 (and (symbolp function
)
2498 (not (autoloadp (symbol-function function
)))))
2500 ;; The following two are necessary for the sake of packages such as
2501 ;; ange-ftp which redefine functions via fcell indirection:
2502 (defun ad-real-definition (function)
2503 "Find FUNCTION's definition at the end of function cell indirection."
2504 (if (ad-has-proper-definition function
)
2505 (let ((definition (symbol-function function
)))
2506 (if (symbolp definition
)
2507 (ad-real-definition definition
)
2510 (defun ad-real-orig-definition (function)
2511 "Find FUNCTION's real original definition starting from its `origname'."
2512 (if (ad-is-advised function
)
2513 (ad-real-definition (ad-get-advice-info-field function
'origname
))))
2515 (defun ad-is-compilable (function)
2516 "True if FUNCTION has an interpreted definition that can be compiled."
2517 (and (ad-has-proper-definition function
)
2518 (or (ad-lambda-p (symbol-function function
))
2519 (ad-macro-p (symbol-function function
)))
2520 (not (ad-compiled-p (symbol-function function
)))))
2522 (defun ad-compile-function (function)
2523 "Byte-compiles FUNCTION (or macro) if it is not yet compiled."
2524 (interactive "aByte-compile function: ")
2525 (if (ad-is-compilable function
)
2526 ;; Need to turn off auto-activation
2527 ;; because `byte-compile' uses `fset':
2528 (ad-with-auto-activation-disabled
2530 (require 'warnings
) ;To define warning-suppress-types
2531 ;before we let-bind it.
2532 (let ((symbol (make-symbol "advice-compilation"))
2533 (byte-compile-warnings byte-compile-warnings
)
2534 ;; Don't pop up windows showing byte-compiler warnings.
2535 (warning-suppress-types '((bytecomp))))
2537 (byte-compile-disable-warning 'cl-functions
))
2538 (fset symbol
(symbol-function function
))
2539 (byte-compile symbol
)
2540 (fset function
(symbol-function symbol
))))))
2542 ;; @@@ Accessing argument lists:
2543 ;; =============================
2545 (defun ad-parse-arglist (arglist)
2546 "Parse ARGLIST into its required, optional and rest parameters.
2547 A three-element list is returned, where the 1st element is the list of
2548 required arguments, the 2nd is the list of optional arguments, and the 3rd
2549 is the name of an optional rest parameter (or nil)."
2550 (let (required optional rest
)
2551 (setq rest
(car (cdr (memq '&rest arglist
))))
2552 (if rest
(setq arglist
(reverse (cdr (memq '&rest
(reverse arglist
))))))
2553 (setq optional
(cdr (memq '&optional arglist
)))
2555 (setq required
(reverse (cdr (memq '&optional
(reverse arglist
)))))
2556 (setq required arglist
))
2557 (list required optional rest
)))
2559 (defun ad-retrieve-args-form (arglist)
2560 "Generate a form which evaluates into names/values/types of ARGLIST.
2561 When the form gets evaluated within a function with that argument list
2562 it will result in a list with one entry for each argument, where the
2563 first element of each entry is the name of the argument, the second
2564 element is its actual current value, and the third element is either
2565 `required', `optional' or `rest' depending on the type of the argument."
2566 (let* ((parsed-arglist (ad-parse-arglist arglist
))
2567 (rest (nth 2 parsed-arglist
)))
2571 `(list ',req
,req
'required
)))
2572 (nth 0 parsed-arglist
))
2575 `(list ',opt
,opt
'optional
)))
2576 (nth 1 parsed-arglist
))
2577 ,@(if rest
(list `(list ',rest
,rest
'rest
))))))
2579 (defun ad-arg-binding-field (binding field
)
2580 (cond ((eq field
'name
) (car binding
))
2581 ((eq field
'value
) (car (cdr binding
)))
2582 ((eq field
'type
) (car (cdr (cdr binding
))))))
2584 (defun ad-list-access (position list
)
2585 (cond ((= position
0) list
)
2586 ((= position
1) (list 'cdr list
))
2587 (t (list 'nthcdr position list
))))
2589 (defun ad-element-access (position list
)
2590 (cond ((= position
0) (list 'car list
))
2591 ((= position
1) `(car (cdr ,list
)))
2592 (t (list 'nth position list
))))
2594 (defun ad-access-argument (arglist index
)
2595 "Tell how to access ARGLIST's actual argument at position INDEX.
2596 For a required/optional arg it simply returns it, if a rest argument has
2597 to be accessed, it returns a list with the index and name."
2598 (let* ((parsed-arglist (ad-parse-arglist arglist
))
2599 (reqopt-args (append (nth 0 parsed-arglist
)
2600 (nth 1 parsed-arglist
)))
2601 (rest-arg (nth 2 parsed-arglist
)))
2602 (cond ((< index
(length reqopt-args
))
2603 (nth index reqopt-args
))
2605 (list (- index
(length reqopt-args
)) rest-arg
)))))
2607 (defun ad-get-argument (arglist index
)
2608 "Return form to access ARGLIST's actual argument at position INDEX.
2609 INDEX counts from zero."
2610 (let ((argument-access (ad-access-argument arglist index
)))
2611 (cond ((consp argument-access
)
2613 (car argument-access
) (car (cdr argument-access
))))
2614 (argument-access))))
2616 (defun ad-set-argument (arglist index value-form
)
2617 "Return form to set ARGLIST's actual arg at INDEX to VALUE-FORM.
2618 INDEX counts from zero."
2619 (let ((argument-access (ad-access-argument arglist index
)))
2620 (cond ((consp argument-access
)
2621 ;; should this check whether there actually is something to set?
2622 `(setcar ,(ad-list-access
2623 (car argument-access
) (car (cdr argument-access
)))
2626 `(setq ,argument-access
,value-form
))
2627 (t (error "ad-set-argument: No argument at position %d of `%s'"
2630 (defun ad-get-arguments (arglist index
)
2631 "Return form to access all actual arguments starting at position INDEX."
2632 (let* ((parsed-arglist (ad-parse-arglist arglist
))
2633 (reqopt-args (append (nth 0 parsed-arglist
)
2634 (nth 1 parsed-arglist
)))
2635 (rest-arg (nth 2 parsed-arglist
))
2637 (if (< index
(length reqopt-args
))
2638 (setq args-form
`(list ,@(nthcdr index reqopt-args
))))
2641 (setq args-form
`(nconc ,args-form
,rest-arg
))
2642 (setq args-form
(ad-list-access (- index
(length reqopt-args
))
2646 (defun ad-set-arguments (arglist index values-form
)
2647 "Make form to assign elements of VALUES-FORM as actual ARGLIST args.
2648 The assignment starts at position INDEX."
2649 (let ((values-index 0)
2650 argument-access set-forms
)
2651 (while (setq argument-access
(ad-access-argument arglist index
))
2652 (if (symbolp argument-access
)
2654 (cons (ad-set-argument
2656 (ad-element-access values-index
'ad-vAlUeS
))
2659 (cons (if (= (car argument-access
) 0)
2661 (car (cdr argument-access
))
2662 (ad-list-access values-index
'ad-vAlUeS
))
2664 (ad-list-access (1- (car argument-access
))
2665 (car (cdr argument-access
)))
2666 (ad-list-access values-index
'ad-vAlUeS
)))
2670 (setq index
(1+ index
))
2671 (setq values-index
(1+ values-index
)))
2672 (if (null set-forms
)
2673 (error "ad-set-arguments: No argument at position %d of `%s'"
2675 (if (= (length set-forms
) 1)
2676 ;; For exactly one set-form we can use values-form directly,...
2678 (function (lambda (form) (eq form
'ad-vAlUeS
)))
2679 (function (lambda (form) values-form
))
2681 ;; ...if we have more we have to bind it to a variable:
2682 `(let ((ad-vAlUeS ,values-form
))
2683 ,@(reverse set-forms
)
2684 ;; work around the old backquote bug:
2687 (defun ad-insert-argument-access-forms (definition arglist
)
2688 "Expands arg-access text macros in DEFINITION according to ARGLIST."
2692 (or (eq form
'ad-arg-bindings
)
2693 (and (memq (car-safe form
)
2694 '(ad-get-arg ad-get-args ad-set-arg ad-set-args
))
2695 (integerp (car-safe (cdr form
)))))))
2698 (if (eq form
'ad-arg-bindings
)
2699 (ad-retrieve-args-form arglist
)
2700 (let ((accessor (car form
))
2701 (index (car (cdr form
)))
2702 (val (car (cdr (ad-insert-argument-access-forms
2703 (cdr form
) arglist
)))))
2704 (cond ((eq accessor
'ad-get-arg
)
2705 (ad-get-argument arglist index
))
2706 ((eq accessor
'ad-set-arg
)
2707 (ad-set-argument arglist index val
))
2708 ((eq accessor
'ad-get-args
)
2709 (ad-get-arguments arglist index
))
2710 ((eq accessor
'ad-set-args
)
2711 (ad-set-arguments arglist index val
)))))))
2714 ;; @@@ Mapping argument lists:
2715 ;; ===========================
2716 ;; Here is the problem:
2717 ;; Suppose function foo was called with (foo 1 2 3 4 5), and foo has the
2718 ;; argument list (x y &rest z), and we want to call the function bar which
2719 ;; has argument list (a &rest b) with a combination of x, y and z so that
2720 ;; the effect is just as if we had called (bar 1 2 3 4 5) directly.
2721 ;; The mapping should work for any two argument lists.
2723 (defun ad-map-arglists (source-arglist target-arglist
)
2724 "Make `funcall/apply' form to map SOURCE-ARGLIST to TARGET-ARGLIST.
2725 The arguments supplied to TARGET-ARGLIST will be taken from SOURCE-ARGLIST just
2726 as if they had been supplied to a function with TARGET-ARGLIST directly.
2727 Excess source arguments will be neglected, missing source arguments will be
2728 supplied as nil. Returns a `funcall' or `apply' form with the second element
2729 being `function' which has to be replaced by an actual function argument.
2730 Example: `(ad-map-arglists '(a &rest args) '(w x y z))' will return
2731 `(funcall function a (car args) (car (cdr args)) (nth 2 args))'."
2732 (let* ((parsed-source-arglist (ad-parse-arglist source-arglist
))
2733 (source-reqopt-args (append (nth 0 parsed-source-arglist
)
2734 (nth 1 parsed-source-arglist
)))
2735 (source-rest-arg (nth 2 parsed-source-arglist
))
2736 (parsed-target-arglist (ad-parse-arglist target-arglist
))
2737 (target-reqopt-args (append (nth 0 parsed-target-arglist
)
2738 (nth 1 parsed-target-arglist
)))
2739 (target-rest-arg (nth 2 parsed-target-arglist
))
2740 (need-apply (and source-rest-arg target-rest-arg
))
2741 (target-arg-index -
1))
2742 ;; This produces ``error-proof'' target function calls with the exception
2743 ;; of a case like (&rest a) mapped onto (x &rest y) where the actual args
2744 ;; supplied to A might not be enough to supply the required target arg X
2745 (append (list (if need-apply
'apply
'funcall
) 'function
)
2747 ;; `apply' can take care of that directly:
2748 (append source-reqopt-args
(list source-rest-arg
)))
2749 (t (mapcar (function
2751 (setq target-arg-index
(1+ target-arg-index
))
2753 source-arglist target-arg-index
)))
2754 (append target-reqopt-args
2755 (and target-rest-arg
2756 ;; If we have a rest arg gobble up
2757 ;; remaining source args:
2758 (nthcdr (length target-reqopt-args
)
2759 source-reqopt-args
)))))))))
2761 (defun ad-make-mapped-call (source-arglist target-arglist target-function
)
2762 "Make form to call TARGET-FUNCTION with args from SOURCE-ARGLIST."
2763 (let ((mapped-form (ad-map-arglists source-arglist target-arglist
)))
2764 (if (eq (car mapped-form
) 'funcall
)
2765 (cons target-function
(cdr (cdr mapped-form
)))
2767 (setcar (cdr mapped-form
) (list 'quote target-function
))))))
2769 ;; @@@ Making an advised documentation string:
2770 ;; ===========================================
2771 ;; New policy: The documentation string for an advised function will be built
2772 ;; at the time the advised `documentation' function is called. This has the
2773 ;; following advantages:
2774 ;; 1) command-key substitutions will automatically be correct
2775 ;; 2) No wasted string space due to big advised docstrings in caches or
2776 ;; compiled files that contain preactivations
2777 ;; The overall overhead for this should be negligible because people normally
2778 ;; don't lookup documentation for the same function over and over again.
2780 (defun ad-make-single-advice-docstring (advice class
&optional style
)
2781 (let ((advice-docstring (ad-docstring (ad-advice-definition advice
))))
2782 (cond ((eq style
'plain
)
2785 (format "Permanent %s-advice `%s':%s%s"
2786 class
(ad-advice-name advice
)
2787 (if advice-docstring
"\n" "")
2788 (or advice-docstring
"")))
2789 (t (if advice-docstring
2790 (format "%s-advice `%s':\n%s"
2791 (capitalize (symbol-name class
))
2792 (ad-advice-name advice
)
2794 (format "%s-advice `%s'."
2795 (capitalize (symbol-name class
))
2796 (ad-advice-name advice
)))))))
2798 (require 'help-fns
) ;For help-split-fundoc and help-add-fundoc-usage.
2800 (defun ad-make-advised-docstring (function &optional style
)
2801 "Construct a documentation string for the advised FUNCTION.
2802 It concatenates the original documentation with the documentation
2803 strings of the individual pieces of advice which will be formatted
2804 according to STYLE. STYLE can be `plain' or `freeze', everything else
2805 will be interpreted as `default'. The order of the advice documentation
2806 strings corresponds to before/around/after and the individual ordering
2807 in any of these classes."
2808 (let* ((origdef (ad-real-orig-definition function
))
2809 (origtype (symbol-name (ad-definition-type origdef
)))
2811 ;; Retrieve raw doc, key substitution will be taken care of later:
2812 (ad-real-documentation origdef t
))
2813 (usage (help-split-fundoc origdoc function
))
2814 paragraphs advice-docstring ad-usage
)
2815 (setq usage
(if (null usage
) t
(setq origdoc
(cdr usage
)) (car usage
)))
2816 (if origdoc
(setq paragraphs
(list origdoc
)))
2817 (unless (eq style
'plain
)
2818 (push (concat "This " origtype
" is advised.") paragraphs
))
2819 (dolist (class ad-advice-classes
)
2820 (dolist (advice (ad-get-enabled-advices function class
))
2821 (setq advice-docstring
2822 (ad-make-single-advice-docstring advice class style
))
2823 (if advice-docstring
2824 (push advice-docstring paragraphs
))))
2825 (setq origdoc
(if paragraphs
2827 ;; separate paragraphs with blank lines:
2828 (mapconcat 'identity
(nreverse paragraphs
) "\n\n")
2829 'ad-advice-info function
)))
2830 (help-add-fundoc-usage origdoc usage
)))
2832 (defun ad-make-plain-docstring (function)
2833 (ad-make-advised-docstring function
'plain
))
2834 (defun ad-make-freeze-docstring (function)
2835 (ad-make-advised-docstring function
'freeze
))
2837 ;; @@@ Accessing overriding arglists and interactive forms:
2838 ;; ========================================================
2840 (defun ad-advised-arglist (function)
2841 "Find first defined arglist in FUNCTION's redefining advices."
2842 (cl-dolist (advice (append (ad-get-enabled-advices function
'before
)
2843 (ad-get-enabled-advices function
'around
)
2844 (ad-get-enabled-advices function
'after
)))
2845 (let ((arglist (ad-arglist (ad-advice-definition advice
))))
2847 ;; We found the first one, use it:
2848 (cl-return arglist
)))))
2850 (defun ad-advised-interactive-form (function)
2851 "Find first interactive form in FUNCTION's redefining advices."
2852 (cl-dolist (advice (append (ad-get-enabled-advices function
'before
)
2853 (ad-get-enabled-advices function
'around
)
2854 (ad-get-enabled-advices function
'after
)))
2855 (let ((interactive-form
2856 (ad-interactive-form (ad-advice-definition advice
))))
2857 (if interactive-form
2858 ;; We found the first one, use it:
2859 (cl-return interactive-form
)))))
2861 ;; @@@ Putting it all together:
2862 ;; ============================
2864 (defun ad-make-advised-definition (function)
2865 "Generate an advised definition of FUNCTION from its advice info."
2866 (if (and (ad-is-advised function
)
2867 (ad-has-redefining-advice function
))
2868 (let* ((origdef (ad-real-orig-definition function
))
2869 (origname (ad-get-advice-info-field function
'origname
))
2870 (orig-interactive-p (commandp origdef
))
2871 (orig-subr-p (ad-subr-p origdef
))
2872 (orig-special-form-p (ad-special-form-p origdef
))
2873 (orig-macro-p (ad-macro-p origdef
))
2874 ;; Construct the individual pieces that we need for assembly:
2875 (orig-arglist (ad-arglist origdef function
))
2876 (advised-arglist (or (ad-advised-arglist function
)
2878 (advised-interactive-form (ad-advised-interactive-form function
))
2880 (cond (orig-macro-p nil
)
2881 (advised-interactive-form)
2882 ((interactive-form origdef
)
2884 (if (and (symbolp function
) (get function
'elp-info
))
2885 (aref (get function
'elp-info
) 2)
2888 (cond ((or orig-special-form-p orig-macro-p
)
2889 ;; Special forms and macros will be advised into macros.
2890 ;; The trick is to construct an expansion for the advised
2891 ;; macro that does the correct thing when it gets eval'ed.
2892 ;; For macros we'll just use the expansion of the original
2893 ;; macro and return that. This way compiled advised macros
2894 ;; will be expanded into something useful. Note that after
2895 ;; advices have full control over whether they want to
2896 ;; evaluate the expansion (the value of `ad-return-value')
2897 ;; at macro expansion time or not. For special forms there
2898 ;; is no solution that interacts reasonably with the
2899 ;; compiler, hence we just evaluate the original at macro
2900 ;; expansion time and return the result. The moral of that
2901 ;; is that one should always deactivate advised special
2902 ;; forms before one byte-compiles a file.
2903 `(,(if orig-macro-p
'macroexpand
'eval
)
2905 ,(ad-get-arguments advised-arglist
0))))
2908 (not interactive-form
)
2909 (not advised-interactive-form
))
2910 ;; Check whether we were called interactively
2911 ;; in order to do proper prompting:
2912 `(if (called-interactively-p 'any
)
2913 (call-interactively ',origname
)
2914 ,(ad-make-mapped-call advised-arglist
2917 ;; And now for normal functions and non-interactive subrs
2918 ;; (or subrs whose interactive behavior was advised):
2919 (t (ad-make-mapped-call
2920 advised-arglist orig-arglist origname
)))))
2922 ;; Finally, build the sucker:
2923 (ad-assemble-advised-definition
2924 (cond (orig-macro-p 'macro
)
2925 (orig-special-form-p 'special-form
)
2928 (ad-make-advised-definition-docstring function
)
2931 (ad-get-enabled-advices function
'before
)
2932 (ad-get-enabled-advices function
'around
)
2933 (ad-get-enabled-advices function
'after
)))))
2935 (defun ad-assemble-advised-definition
2936 (type args docstring interactive orig
&optional befores arounds afters
)
2938 "Assembles an original and its advices into an advised function.
2939 It constructs a function or macro definition according to TYPE which has to
2940 be either `macro', `function' or `special-form'. ARGS is the argument list
2941 that has to be used, DOCSTRING if non-nil defines the documentation of the
2942 definition, INTERACTIVE if non-nil is the interactive form to be used,
2943 ORIG is a form that calls the body of the original unadvised function,
2944 and BEFORES, AROUNDS and AFTERS are the lists of advices with which ORIG
2945 should be modified. The assembled function will be returned."
2947 (let (before-forms around-form around-form-protected after-forms definition
)
2948 (dolist (advice befores
)
2949 (cond ((and (ad-advice-protected advice
)
2953 ,(macroexp-progn before-forms
)
2955 (ad-advice-definition advice
))))))
2956 (t (setq before-forms
2957 (append before-forms
2958 (ad-body-forms (ad-advice-definition advice
)))))))
2960 (setq around-form
`(setq ad-return-value
,orig
))
2961 (dolist (advice (reverse arounds
))
2962 ;; If any of the around advices is protected then we
2963 ;; protect the complete around advice onion:
2964 (if (ad-advice-protected advice
)
2965 (setq around-form-protected t
))
2968 (function (lambda (form) (eq form
'ad-do-it
)))
2969 (function (lambda (form) around-form
))
2970 (macroexp-progn (ad-body-forms (ad-advice-definition advice
))))))
2973 (if (and around-form-protected before-forms
)
2975 ,(macroexp-progn before-forms
)
2977 (append before-forms
(list around-form
))))
2978 (dolist (advice afters
)
2979 (cond ((and (ad-advice-protected advice
)
2983 ,(macroexp-progn after-forms
)
2985 (ad-advice-definition advice
))))))
2986 (t (setq after-forms
2988 (ad-body-forms (ad-advice-definition advice
)))))))
2991 `(,@(if (memq type
'(macro special-form
)) '(macro))
2994 ,@(if docstring
(list docstring
))
2995 ,@(if interactive
(list interactive
))
2996 (let (ad-return-value)
2998 ,(if (eq type
'special-form
)
2999 '(list 'quote ad-return-value
)
3000 'ad-return-value
))))
3002 (ad-insert-argument-access-forms definition args
)))
3004 ;; This is needed for activation/deactivation hooks:
3005 (defun ad-make-hook-form (function hook-name
)
3006 "Make hook-form from FUNCTION's advice bodies in class HOOK-NAME."
3008 (mapcar (function (lambda (advice)
3009 (ad-body-forms (ad-advice-definition advice
))))
3010 (ad-get-enabled-advices function hook-name
))))
3012 (macroexp-progn (apply 'append hook-forms
)))))
3017 ;; Generating an advised definition of a function is moderately expensive,
3018 ;; hence, it makes sense to cache it so we can reuse it in appropriate
3019 ;; circumstances. Of course, it only makes sense to reuse a cached
3020 ;; definition if the current advice and function definition state is the
3021 ;; same as it was at the time when the cached definition was generated.
3022 ;; For that purpose we associate every cache with an id so we can verify
3023 ;; if it is still valid at a certain point in time. This id mechanism
3024 ;; makes it possible to preactivate advised functions, write the compiled
3025 ;; advised definitions to a file and reuse them during the actual
3026 ;; activation without having to risk that the resulting definition will be
3027 ;; incorrect, well, almost.
3029 ;; A cache id is a list with six elements:
3030 ;; 1) the list of names of enabled before advices
3031 ;; 2) the list of names of enabled around advices
3032 ;; 3) the list of names of enabled after advices
3033 ;; 4) the type of the original function (macro, subr, etc.)
3034 ;; 5) the arglist of the original definition (or t if it was equal to the
3035 ;; arglist of the cached definition)
3036 ;; 6) t if the interactive form of the original definition was equal to the
3037 ;; interactive form of the cached definition
3039 ;; Here's how a cache can get invalidated or be incorrect:
3040 ;; A) a piece of advice used in the cache gets redefined
3041 ;; B) the current list of enabled advices is different from the ones used
3043 ;; C) the type of the original function changed, e.g., a function became a
3044 ;; macro, or a subr became a function
3045 ;; D) the arglist of the original function changed
3046 ;; E) the interactive form of the original function changed
3047 ;; F) a piece of advice used in the cache got redefined before the
3048 ;; defadvice with the cached definition got loaded: This is a PROBLEM!
3050 ;; Cases A and B are the normal ones. A is taken care of by `ad-add-advice'
3051 ;; which clears the cache in such a case, B is easily checked during
3052 ;; verification at activation time.
3054 ;; Cases C, D and E have to be considered if one is slightly paranoid, i.e.,
3055 ;; if one considers the case that the original function could be different
3056 ;; from the one available at caching time (e.g., for forward advice of
3057 ;; functions that get redefined by some packages - such as `eval-region' gets
3058 ;; redefined by edebug). All these cases can be easily checked during
3059 ;; verification. Element 4 of the id lets one check case C, element 5 takes
3060 ;; care of case D (using t in the equality case saves some space, because the
3061 ;; arglist can be recovered at validation time from the cached definition),
3062 ;; and element 6 takes care of case E which is only a problem if the original
3063 ;; was actually a function whose interactive form was not overridden by a
3066 ;; Case F is the only one which will lead to an incorrect advised function.
3067 ;; There is no way to avoid this without storing the complete advice definition
3068 ;; in the cache-id which is not feasible.
3070 ;; The cache-id of a typical advised function with one piece of advice and
3071 ;; no arglist redefinition takes 7 conses which is a small price to pay for
3072 ;; the added efficiency. The validation itself is also pretty cheap, certainly
3073 ;; a lot cheaper than reconstructing an advised definition.
3075 (defmacro ad-get-cache-definition
(function)
3076 `(car (ad-get-advice-info-field ,function
'cache
)))
3078 (defmacro ad-get-cache-id
(function)
3079 `(cdr (ad-get-advice-info-field ,function
'cache
)))
3081 (defmacro ad-set-cache
(function definition id
)
3082 `(ad-set-advice-info-field
3083 ,function
'cache
(cons ,definition
,id
)))
3085 (defun ad-clear-cache (function)
3086 "Clears a previously cached advised definition of FUNCTION.
3087 Clear the cache if you want to force `ad-activate' to construct a new
3088 advised definition from scratch."
3090 (list (ad-read-advised-function "Clear cached definition of")))
3091 (ad-set-advice-info-field function
'cache nil
))
3093 (defun ad-make-cache-id (function)
3094 "Generate an identifying image of the current advices of FUNCTION."
3095 (let ((original-definition (ad-real-orig-definition function
))
3096 (cached-definition (ad-get-cache-definition function
)))
3097 (list (mapcar (function (lambda (advice) (ad-advice-name advice
)))
3098 (ad-get-enabled-advices function
'before
))
3099 (mapcar (function (lambda (advice) (ad-advice-name advice
)))
3100 (ad-get-enabled-advices function
'around
))
3101 (mapcar (function (lambda (advice) (ad-advice-name advice
)))
3102 (ad-get-enabled-advices function
'after
))
3103 (ad-definition-type original-definition
)
3104 (if (equal (ad-arglist original-definition function
)
3105 (ad-arglist cached-definition
))
3107 (ad-arglist original-definition function
))
3108 (if (eq (ad-definition-type original-definition
) 'function
)
3109 (equal (interactive-form original-definition
)
3110 (interactive-form cached-definition
))))))
3112 (defun ad-get-cache-class-id (function class
)
3113 "Return the part of FUNCTION's cache id that identifies CLASS."
3114 (let ((cache-id (ad-get-cache-id function
)))
3115 (if (eq class
'before
)
3117 (if (eq class
'around
)
3119 (nth 2 cache-id
)))))
3121 (defun ad-verify-cache-class-id (cache-class-id advices
)
3122 (cl-dolist (advice advices
(null cache-class-id
))
3123 (if (ad-advice-enabled advice
)
3124 (if (eq (car cache-class-id
) (ad-advice-name advice
))
3125 (setq cache-class-id
(cdr cache-class-id
))
3128 ;; There should be a way to monitor if and why a cache verification failed
3129 ;; in order to determine whether a certain preactivation could be used or
3130 ;; not. Right now the only way to find out is to trace
3131 ;; `ad-cache-id-verification-code'. The code it returns indicates where the
3132 ;; verification failed. Tracing `ad-verify-cache-class-id' might provide
3133 ;; some additional useful information.
3135 (defun ad-cache-id-verification-code (function)
3136 (let ((cache-id (ad-get-cache-id function
))
3137 (code 'before-advice-mismatch
))
3138 (and (ad-verify-cache-class-id
3139 (car cache-id
) (ad-get-advice-info-field function
'before
))
3140 (setq code
'around-advice-mismatch
)
3141 (ad-verify-cache-class-id
3142 (nth 1 cache-id
) (ad-get-advice-info-field function
'around
))
3143 (setq code
'after-advice-mismatch
)
3144 (ad-verify-cache-class-id
3145 (nth 2 cache-id
) (ad-get-advice-info-field function
'after
))
3146 (setq code
'definition-type-mismatch
)
3147 (let ((original-definition (ad-real-orig-definition function
))
3148 (cached-definition (ad-get-cache-definition function
)))
3149 (and (eq (nth 3 cache-id
) (ad-definition-type original-definition
))
3150 (setq code
'arglist-mismatch
)
3151 (equal (if (eq (nth 4 cache-id
) t
)
3152 (ad-arglist original-definition function
)
3154 (ad-arglist cached-definition
))
3155 (setq code
'interactive-form-mismatch
)
3156 (or (null (nth 5 cache-id
))
3157 (equal (interactive-form original-definition
)
3158 (interactive-form cached-definition
)))
3159 (setq code
'verified
))))
3162 (defun ad-verify-cache-id (function)
3163 "True if FUNCTION's cache-id is compatible with its current advices."
3164 (eq (ad-cache-id-verification-code function
) 'verified
))
3167 ;; @@ Preactivation:
3168 ;; =================
3169 ;; Preactivation can be used to generate compiled advised definitions
3170 ;; at compile time without having to give up the dynamic runtime flexibility
3171 ;; of the advice mechanism. Preactivation is a special feature of `defadvice',
3172 ;; it involves the following steps:
3173 ;; - remembering the function's current state (definition and advice-info)
3174 ;; - advising it with the defined piece of advice
3175 ;; - clearing its cache
3176 ;; - generating an interpreted advised definition by activating it, this will
3177 ;; make use of all its current active advice and its current definition
3178 ;; - saving the so generated cached definition and id
3179 ;; - resetting the function's advice and definition state to what it was
3180 ;; before the preactivation
3181 ;; - Returning the saved definition and its id to be used in the expansion of
3182 ;; `defadvice' to assign it as an initial cache, hence it will be compiled
3183 ;; at time the `defadvice' gets compiled.
3184 ;; Naturally, for preactivation to be effective it has to be applied/compiled
3185 ;; at the right time, i.e., when the current state of advices and function
3186 ;; definition exactly reflects the state at activation time. Should that not
3187 ;; be the case, the precompiled definition will just be discarded and a new
3188 ;; advised definition will be generated.
3190 (defun ad-preactivate-advice (function advice class position
)
3191 "Preactivate FUNCTION and returns the constructed cache."
3192 (let* ((function-defined-p (fboundp function
))
3194 (if function-defined-p
3195 (symbol-function function
)))
3196 (old-advice-info (ad-copy-advice-info function
))
3197 (ad-advised-functions ad-advised-functions
))
3200 (ad-add-advice function advice class position
)
3201 (ad-enable-advice function class
(ad-advice-name advice
))
3202 (ad-clear-cache function
)
3203 (ad-activate function -
1)
3204 (if (and (ad-is-active function
)
3205 (ad-get-cache-definition function
))
3206 (list (ad-get-cache-definition function
)
3207 (ad-get-cache-id function
))))
3208 (ad-set-advice-info function old-advice-info
)
3209 ;; Don't `fset' function to nil if it was previously unbound:
3210 (if function-defined-p
3211 (ad-safe-fset function old-definition
)
3212 (fmakunbound function
)))))
3217 ;; Freezing transforms a `defadvice' into a redefining `defun/defmacro'
3218 ;; for the advised function without keeping any advice information. This
3219 ;; feature was jwz's idea: It generates a dumpable function definition
3220 ;; whose documentation can be written to the DOC file, and the generated
3221 ;; code does not need any Advice runtime support. Of course, frozen advices
3222 ;; cannot be undone.
3224 ;; Freezing only considers the advice of the particular `defadvice', other
3225 ;; already existing advices for the same function will be ignored. To ensure
3226 ;; proper interaction when an already advised function gets redefined with
3227 ;; a frozen advice, frozen advices always use the actual original definition
3228 ;; of the function, i.e., they are always at the core of the onion. E.g., if
3229 ;; an already advised function gets redefined with a frozen advice and then
3230 ;; unadvised, the frozen advice remains as the new definition of the function.
3232 ;; While multiple freeze advices for a single function or freeze-advising
3233 ;; of an already advised function are possible, they are better avoided,
3234 ;; because definition/compile/load ordering is relevant, and it becomes
3235 ;; incomprehensible pretty quickly.
3237 (defun ad-make-freeze-definition (function advice class position
)
3238 (if (not (ad-has-proper-definition function
))
3240 "ad-make-freeze-definition: `%s' is not yet defined"
3242 (let* ((name (ad-advice-name advice
))
3243 ;; With a unique origname we can have multiple freeze advices
3244 ;; for the same function, each overloading the previous one:
3246 (intern (format "%s-%s-%s" (ad-make-origname function
) class name
)))
3248 ;; If FUNCTION is already advised, we'll use its current origdef
3249 ;; as the original definition of the frozen advice:
3250 (or (ad-get-orig-definition function
)
3251 (symbol-function function
)))
3253 (if (ad-is-advised function
)
3254 (ad-copy-advice-info function
)))
3256 (symbol-function 'ad-make-advised-definition-docstring
))
3258 (symbol-function 'ad-make-origname
))
3262 ;; Make sure we construct a proper docstring:
3263 (ad-safe-fset 'ad-make-advised-definition-docstring
3264 'ad-make-freeze-docstring
)
3265 ;; Make sure `unique-origname' is used as the origname:
3266 (ad-safe-fset 'ad-make-origname
(lambda (x) unique-origname
))
3267 ;; No we reset all current advice information to nil and
3268 ;; generate an advised definition that's solely determined
3269 ;; by ADVICE and the current origdef of FUNCTION:
3270 (ad-set-advice-info function nil
)
3271 (ad-add-advice function advice class position
)
3272 ;; The following will provide proper real docstrings as
3273 ;; well as a definition that will make the compiler happy:
3274 (ad-set-orig-definition function orig-definition
)
3275 (ad-make-advised-definition function
))
3276 ;; Restore the old advice state:
3277 (ad-set-advice-info function old-advice-info
)
3278 ;; Restore functions:
3280 'ad-make-advised-definition-docstring real-docstring-fn
)
3281 (ad-safe-fset 'ad-make-origname real-origname-fn
))))
3282 (if frozen-definition
3283 (let* ((macro-p (ad-macro-p frozen-definition
))
3284 (body (cdr (if macro-p
3285 (ad-lambdafy frozen-definition
)
3286 frozen-definition
))))
3288 (if (not (fboundp ',unique-origname
))
3289 (fset ',unique-origname
3290 ;; avoid infinite recursion in case the function
3291 ;; we want to freeze is already advised:
3292 (or (ad-get-orig-definition ',function
)
3293 (symbol-function ',function
))))
3294 (,(if macro-p
'defmacro
'defun
)
3299 ;; @@ Activation and definition handling:
3300 ;; ======================================
3302 (defun ad-should-compile (function compile
)
3303 "Return non-nil if the advised FUNCTION should be compiled.
3304 If COMPILE is non-nil and not a negative number then it returns t.
3305 If COMPILE is a negative number then it returns nil.
3306 If COMPILE is nil then the result depends on the value of
3307 `ad-default-compilation-action' (which see)."
3308 (if (integerp compile
)
3312 (cond ((eq ad-default-compilation-action
'never
)
3314 ((eq ad-default-compilation-action
'always
)
3316 ((eq ad-default-compilation-action
'like-original
)
3317 (or (ad-subr-p (ad-get-orig-definition function
))
3318 (ad-compiled-p (ad-get-orig-definition function
))))
3319 ;; everything else means `maybe':
3320 (t (featurep 'byte-compile
))))))
3322 (defun ad-activate-advised-definition (function compile
)
3323 "Redefine FUNCTION with its advised definition from cache or scratch.
3324 The resulting FUNCTION will be compiled if `ad-should-compile' returns t.
3325 The current definition and its cache-id will be put into the cache."
3326 (let ((verified-cached-definition
3327 (if (ad-verify-cache-id function
)
3328 (ad-get-cache-definition function
))))
3329 (ad-safe-fset function
3330 (or verified-cached-definition
3331 (ad-make-advised-definition function
)))
3332 (if (ad-should-compile function compile
)
3333 (ad-compile-function function
))
3334 (if verified-cached-definition
3335 (if (not (eq verified-cached-definition
(symbol-function function
)))
3336 ;; we must have compiled, cache the compiled definition:
3338 function
(symbol-function function
) (ad-get-cache-id function
)))
3339 ;; We created a new advised definition, cache it with a proper id:
3340 (ad-clear-cache function
)
3341 ;; ad-make-cache-id needs the new cached definition:
3342 (ad-set-cache function
(symbol-function function
) nil
)
3344 function
(symbol-function function
) (ad-make-cache-id function
)))))
3346 (defun ad-handle-definition (function)
3347 "Handle re/definition of an advised FUNCTION during de/activation.
3348 If FUNCTION does not have an original definition associated with it and
3349 the current definition is usable, then it will be stored as FUNCTION's
3350 original definition. If no current definition is available (even in the
3351 case of undefinition) nothing will be done. In the case of redefinition
3352 the action taken depends on the value of `ad-redefinition-action' (which
3353 see). Redefinition occurs when FUNCTION already has an original definition
3354 associated with it but got redefined with a new definition and then
3355 de/activated. If you do not like the current redefinition action change
3356 the value of `ad-redefinition-action' and de/activate again."
3357 (let ((original-definition (ad-get-orig-definition function
))
3358 (current-definition (if (ad-real-definition function
)
3359 (symbol-function function
))))
3360 (if original-definition
3361 (if current-definition
3362 (if (and (not (eq current-definition original-definition
))
3363 ;; Redefinition with an advised definition from a
3364 ;; different function won't count as such:
3365 (not (ad-advised-definition-p current-definition
)))
3366 ;; we have a redefinition:
3367 (if (not (memq ad-redefinition-action
'(accept discard warn
)))
3368 (error "ad-handle-definition (see its doc): `%s' %s"
3369 function
"invalidly redefined")
3370 (if (eq ad-redefinition-action
'discard
)
3371 (ad-safe-fset function original-definition
)
3372 (ad-set-orig-definition function current-definition
)
3373 (if (eq ad-redefinition-action
'warn
)
3374 (message "ad-handle-definition: `%s' got redefined"
3376 ;; either advised def or correct original is in place:
3378 ;; we have an undefinition, ignore it:
3380 (if current-definition
3381 ;; we have a first definition, save it as original:
3382 (ad-set-orig-definition function current-definition
)
3383 ;; we don't have anything noteworthy:
3387 ;; @@ The top-level advice interface:
3388 ;; ==================================
3391 (defun ad-activate (function &optional compile
)
3392 "Activate all the advice information of an advised FUNCTION.
3393 If FUNCTION has a proper original definition then an advised
3394 definition will be generated from FUNCTION's advice info and the
3395 definition of FUNCTION will be replaced with it. If a previously
3396 cached advised definition was available, it will be used.
3397 The optional COMPILE argument determines whether the resulting function
3398 or a compilable cached definition will be compiled. If it is negative
3399 no compilation will be performed, if it is positive or otherwise non-nil
3400 the resulting function will be compiled, if it is nil the behavior depends
3401 on the value of `ad-default-compilation-action' (which see).
3402 Activation of an advised function that has an advice info but no actual
3403 pieces of advice is equivalent to a call to `ad-unadvise'. Activation of
3404 an advised function that has actual pieces of advice but none of them are
3405 enabled is equivalent to a call to `ad-deactivate'. The current advised
3406 definition will always be cached for later usage."
3408 (list (ad-read-advised-function "Activate advice of")
3409 current-prefix-arg
))
3410 (if ad-activate-on-top-level
3411 ;; avoid recursive calls to `ad-activate':
3412 (ad-with-auto-activation-disabled
3413 (if (not (ad-is-advised function
))
3414 (error "ad-activate: `%s' is not advised" function
)
3415 (ad-handle-definition function
)
3416 ;; Just return for forward advised and not yet defined functions:
3417 (if (ad-get-orig-definition function
)
3418 (if (not (ad-has-any-advice function
))
3419 (ad-unadvise function
)
3420 ;; Otherwise activate the advice:
3421 (cond ((ad-has-redefining-advice function
)
3422 (ad-activate-advised-definition function compile
)
3423 (ad-set-advice-info-field function
'active t
)
3424 (eval (ad-make-hook-form function
'activation
))
3426 ;; Here we are if we have all disabled advices:
3427 (t (ad-deactivate function
)))))))))
3429 (defalias 'ad-activate-on
'ad-activate
)
3431 (defun ad-deactivate (function)
3432 "Deactivate the advice of an actively advised FUNCTION.
3433 If FUNCTION has a proper original definition, then the current
3434 definition of FUNCTION will be replaced with it. All the advice
3435 information will still be available so it can be activated again with
3436 a call to `ad-activate'."
3438 (list (ad-read-advised-function "Deactivate advice of" 'ad-is-active
)))
3439 (if (not (ad-is-advised function
))
3440 (error "ad-deactivate: `%s' is not advised" function
)
3441 (cond ((ad-is-active function
)
3442 (ad-handle-definition function
)
3443 (if (not (ad-get-orig-definition function
))
3444 (error "ad-deactivate: `%s' has no original definition"
3446 (ad-safe-fset function
(ad-get-orig-definition function
))
3447 (ad-set-advice-info-field function
'active nil
)
3448 (eval (ad-make-hook-form function
'deactivation
))
3451 (defun ad-update (function &optional compile
)
3452 "Update the advised definition of FUNCTION if its advice is active.
3453 See `ad-activate' for documentation on the optional COMPILE argument."
3455 (list (ad-read-advised-function
3456 "Update advised definition of" 'ad-is-active
)))
3457 (if (ad-is-active function
)
3458 (ad-activate function compile
)))
3460 (defun ad-unadvise (function)
3461 "Deactivate FUNCTION and then remove all its advice information.
3462 If FUNCTION was not advised this will be a noop."
3464 (list (ad-read-advised-function "Unadvise function")))
3465 (cond ((ad-is-advised function
)
3466 (if (ad-is-active function
)
3467 (ad-deactivate function
))
3468 (ad-clear-orig-definition function
)
3469 (ad-set-advice-info function nil
)
3470 (ad-pop-advised-function function
))))
3472 (defun ad-recover (function)
3473 "Try to recover FUNCTION's original definition, and unadvise it.
3474 This is more low-level than `ad-unadvise' in that it does not do
3475 deactivation, which might run hooks and get into other trouble.
3476 Use in emergencies."
3477 ;; Use more primitive interactive behavior here: Accept any symbol that's
3478 ;; currently defined in obarray, not necessarily with a function definition:
3481 (completing-read "Recover advised function: " obarray nil t
))))
3482 (cond ((ad-is-advised function
)
3483 (cond ((ad-get-orig-definition function
)
3484 (ad-safe-fset function
(ad-get-orig-definition function
))
3485 (ad-clear-orig-definition function
)))
3486 (ad-set-advice-info function nil
)
3487 (ad-pop-advised-function function
))))
3489 (defun ad-activate-regexp (regexp &optional compile
)
3490 "Activate functions with an advice name containing a REGEXP match.
3491 This activates the advice for each function
3492 that has at least one piece of advice whose name includes a match for REGEXP.
3493 See `ad-activate' for documentation on the optional COMPILE argument."
3495 (list (ad-read-regexp "Activate via advice regexp")
3496 current-prefix-arg
))
3497 (ad-do-advised-functions (function)
3498 (if (ad-find-some-advice function
'any regexp
)
3499 (ad-activate function compile
))))
3501 (defun ad-deactivate-regexp (regexp)
3502 "Deactivate functions with an advice name containing REGEXP match.
3503 This deactivates the advice for each function
3504 that has at least one piece of advice whose name includes a match for REGEXP."
3506 (list (ad-read-regexp "Deactivate via advice regexp")))
3507 (ad-do-advised-functions (function)
3508 (if (ad-find-some-advice function
'any regexp
)
3509 (ad-deactivate function
))))
3511 (defun ad-update-regexp (regexp &optional compile
)
3512 "Update functions with an advice name containing a REGEXP match.
3513 This reactivates the advice for each function
3514 that has at least one piece of advice whose name includes a match for REGEXP.
3515 See `ad-activate' for documentation on the optional COMPILE argument."
3517 (list (ad-read-regexp "Update via advice regexp")
3518 current-prefix-arg
))
3519 (ad-do-advised-functions (function)
3520 (if (ad-find-some-advice function
'any regexp
)
3521 (ad-update function compile
))))
3523 (defun ad-activate-all (&optional compile
)
3524 "Activate all currently advised functions.
3525 See `ad-activate' for documentation on the optional COMPILE argument."
3527 (ad-do-advised-functions (function)
3528 (ad-activate function compile
)))
3530 (defun ad-deactivate-all ()
3531 "Deactivate all currently advised functions."
3533 (ad-do-advised-functions (function)
3534 (ad-deactivate function
)))
3536 (defun ad-update-all (&optional compile
)
3537 "Update all currently advised functions.
3538 With prefix argument, COMPILE resulting advised definitions."
3540 (ad-do-advised-functions (function)
3541 (ad-update function compile
)))
3543 (defun ad-unadvise-all ()
3544 "Unadvise all currently advised functions."
3546 (ad-do-advised-functions (function)
3547 (ad-unadvise function
)))
3549 (defun ad-recover-all ()
3550 "Recover all currently advised functions. Use in emergencies.
3551 To recover a function means to try to find its original (pre-advice)
3552 definition, and delete all advice.
3553 This is more low-level than `ad-unadvise' in that it does not do
3554 deactivation, which might run hooks and get into other trouble."
3556 (ad-do-advised-functions (function)
3558 (ad-recover function
)
3562 ;; Completion alist of valid `defadvice' flags
3563 (defvar ad-defadvice-flags
3564 '(("protect") ("disable") ("activate")
3565 ("compile") ("preactivate") ("freeze")))
3568 (defmacro defadvice
(function args
&rest body
)
3569 "Define a piece of advice for FUNCTION (a symbol).
3570 The syntax of `defadvice' is as follows:
3572 \(defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3573 [DOCSTRING] [INTERACTIVE-FORM]
3576 FUNCTION ::= Name of the function to be advised.
3577 CLASS ::= `before' | `around' | `after' | `activation' | `deactivation'.
3578 NAME ::= Non-nil symbol that names this piece of advice.
3579 POSITION ::= `first' | `last' | NUMBER. Optional, defaults to `first',
3580 see also `ad-add-advice'.
3581 ARGLIST ::= An optional argument list to be used for the advised function
3582 instead of the argument list of the original. The first one found in
3583 before/around/after-advices will be used.
3584 FLAG ::= `protect'|`disable'|`activate'|`compile'|`preactivate'|`freeze'.
3585 All flags can be specified with unambiguous initial substrings.
3586 DOCSTRING ::= Optional documentation for this piece of advice.
3587 INTERACTIVE-FORM ::= Optional interactive form to be used for the advised
3588 function. The first one found in before/around/after-advices will be used.
3589 BODY ::= Any s-expression.
3591 Semantics of the various flags:
3592 `protect': The piece of advice will be protected against non-local exits in
3593 any code that precedes it. If any around-advice of a function is protected
3594 then automatically all around-advices will be protected (the complete onion).
3596 `activate': All advice of FUNCTION will be activated immediately if
3597 FUNCTION has been properly defined prior to this application of `defadvice'.
3599 `compile': In conjunction with `activate' specifies that the resulting
3600 advised function should be compiled.
3602 `disable': The defined advice will be disabled, hence, it will not be used
3603 during activation until somebody enables it.
3605 `preactivate': Preactivates the advised FUNCTION at macro-expansion/compile
3606 time. This generates a compiled advised definition according to the current
3607 advice state that will be used during activation if appropriate. Only use
3608 this if the `defadvice' gets actually compiled.
3610 `freeze': Expands the `defadvice' into a redefining `defun/defmacro' according
3611 to this particular single advice. No other advice information will be saved.
3612 Frozen advices cannot be undone, they behave like a hard redefinition of
3613 the advised function. `freeze' implies `activate' and `preactivate'. The
3614 documentation of the advised function can be dumped onto the `DOC' file
3617 See Info node `(elisp)Advising Functions' for comprehensive documentation.
3618 usage: (defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3619 [DOCSTRING] [INTERACTIVE-FORM]
3621 (declare (doc-string 3)
3622 (debug (&define name
;; thing being advised.
3623 (name ;; class is [&or "before" "around" "after"
3624 ;; "activation" "deactivation"]
3625 name
;; name of advice
3626 &rest sexp
;; optional position and flags
3629 [&optional
("interactive" interactive
)]
3631 (if (not (ad-name-p function
))
3632 (error "defadvice: Invalid function name: %s" function
))
3633 (let* ((class (car args
))
3634 (name (if (not (ad-class-p class
))
3635 (error "defadvice: Invalid advice class: %s" class
)
3637 (position (if (not (ad-name-p name
))
3638 (error "defadvice: Invalid advice name: %s" name
)
3639 (setq args
(nthcdr 2 args
))
3640 (if (ad-position-p (car args
))
3642 (setq args
(cdr args
))))))
3643 (arglist (if (listp (car args
))
3645 (setq args
(cdr args
)))))
3651 (try-completion (symbol-name flag
) ad-defadvice-flags
)))
3652 (cond ((eq completion t
) flag
)
3653 ((assoc completion ad-defadvice-flags
)
3654 (intern completion
))
3655 (t (error "defadvice: Invalid or ambiguous flag: %s"
3658 (advice (ad-make-advice
3659 name
(memq 'protect flags
)
3660 (not (memq 'disable flags
))
3661 `(advice lambda
,arglist
,@body
)))
3662 (preactivation (if (memq 'preactivate flags
)
3663 (ad-preactivate-advice
3664 function advice class position
))))
3665 ;; Now for the things to be done at evaluation time:
3666 (if (memq 'freeze flags
)
3667 ;; jwz's idea: Freeze the advised definition into a dumpable
3668 ;; defun/defmacro whose docs can be written to the DOC file:
3669 (ad-make-freeze-definition function advice class position
)
3672 (ad-add-advice ',function
',advice
',class
',position
)
3676 ;; the function will get compiled:
3677 ,(cond ((ad-macro-p (car preactivation
))
3681 (car preactivation
)))))
3683 ,(car preactivation
))))
3684 ',(car (cdr preactivation
)))))
3685 ,@(if (memq 'activate flags
)
3686 `((ad-activate ',function
3687 ,(if (memq 'compile flags
) t
))))
3694 (defmacro ad-with-originals
(functions &rest body
)
3695 "Binds FUNCTIONS to their original definitions and execute BODY.
3696 For any members of FUNCTIONS that are not currently advised the rebinding will
3697 be a noop. Any modifications done to the definitions of FUNCTIONS will be
3698 undone on exit of this macro."
3700 ;; Make let-variables to store current definitions:
3704 (setq index
(1+ index
))
3705 (list (intern (format "ad-oRiGdEf-%d" index
))
3706 `(symbol-function ',function
))))
3708 `(let ,current-bindings
3712 ;; Make forms to redefine functions to their
3713 ;; original definitions if they are advised:
3718 (setq index
(1+ index
))
3721 (or (ad-get-orig-definition ',function
)
3722 ,(car (nth index current-bindings
))))))
3726 ;; Make forms to back-define functions to the definitions
3727 ;; they had outside this macro call:
3732 (setq index
(1+ index
))
3735 ,(car (nth index current-bindings
)))))
3738 (if (not (get 'ad-with-originals
'lisp-indent-hook
))
3739 (put 'ad-with-originals
'lisp-indent-hook
1))
3742 ;; @@ Advising `documentation':
3743 ;; ============================
3744 ;; Use the advice mechanism to advise `documentation' to make it
3745 ;; generate proper documentation strings for advised definitions:
3747 ;; @@ Starting, stopping and recovering from the advice package magic:
3748 ;; ===================================================================
3750 (defun ad-start-advice ()
3751 "Start the automatic advice handling magic."
3753 ;; Advising `ad-activate-internal' means death!!
3754 (ad-set-advice-info 'ad-activate-internal nil
)
3755 (ad-safe-fset 'ad-activate-internal
'ad-activate
))
3757 (defun ad-stop-advice ()
3758 "Stop the automatic advice handling magic.
3759 You should only need this in case of Advice-related emergencies."
3761 ;; Advising `ad-activate-internal' means death!!
3762 (ad-set-advice-info 'ad-activate-internal nil
)
3763 (ad-safe-fset 'ad-activate-internal
'ad-activate-internal-off
))
3765 (defun ad-recover-normality ()
3766 "Undo all advice related redefinitions and unadvises everything.
3767 Use only in REAL emergencies."
3769 ;; Advising `ad-activate-internal' means death!!
3770 (ad-set-advice-info 'ad-activate-internal nil
)
3771 (ad-safe-fset 'ad-activate-internal
'ad-activate-internal-off
)
3773 (setq ad-advised-functions nil
))
3779 ;;; advice.el ends here