Autoload more carefully from Lisp. Follow aliases for function properties.
[emacs.git] / lisp / emacs-lisp / advice.el
blobcac76d2bce1aa0b999d5338d9ab82636f1f909e6
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>
6 ;; Maintainer: FSF
7 ;; Created: 12 Dec 1992
8 ;; Keywords: extensions, lisp, tools
9 ;; Package: emacs
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/>.
26 ;; LCD Archive Entry:
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|
32 ;;; Commentary:
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.
40 ;; @ Introduction:
41 ;; ===============
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.
51 ;; @ Highlights:
52 ;; =============
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.
112 ;; @ Restrictions:
113 ;; ===============
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.
126 ;; @ Credits:
127 ;; ==========
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.
180 ;; @ Customization:
181 ;; ================
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.
193 ;; @ Motivation:
194 ;; =============
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
197 ;; is just a joke:
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."
202 ;; (interactive
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))))
211 ;; ad-do-it))
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: ")
220 ;; ad-do-it
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.
230 ;; @@ Terminology:
231 ;; ===============
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
235 ;; (such as Epoch)
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
247 ;; `defun/defmacro':
249 ;; (defadvice <function> (<class> <name> [<position>] [<arglist>] {<flags>}*)
250 ;; [ [<documentation-string>] [<interactive-form>] ]
251 ;; {<body-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>}*
327 ;; ....
328 ;; {<before-N-1-body-form>}*
329 ;; {<around-0-body-form>}*
330 ;; {<around-1-body-form>}*
331 ;; ....
332 ;; {<around-M-1-body-form>}*
333 ;; (setq ad-return-value
334 ;; <apply original definition to <arglist>>)
335 ;; {<other-around-M-1-body-form>}*
336 ;; ....
337 ;; {<other-around-1-body-form>}*
338 ;; {<other-around-0-body-form>}*
339 ;; {<after-0-body-form>}*
340 ;; ....
341 ;; {<after-K-1-body-form>}*
342 ;; ad-return-value))
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>.
450 ;; For example,
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)))
482 ;; ....)
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
536 ;; conventions.
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
673 ;; - see below).
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.
681 ;; @@ Preactivation:
682 ;; =================
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
689 ;; works:
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
730 ;; activated
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
772 ;; results.
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 ;; ===================================
814 ;; - Definition:
815 ;; A piece of advice gets defined with `defadvice' and added to the
816 ;; `advice-info' property of a function.
817 ;; - Enablement:
818 ;; Every piece of advice has an enablement flag associated with it. Only
819 ;; enabled advices are considered during construction of an advised
820 ;; definition.
821 ;; - Activation:
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.
825 ;; - Deactivation:
826 ;; Back-define an advised function to its original definition.
827 ;; - Update:
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.
832 ;; - Caching:
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.
835 ;; - Preactivation:
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
865 ;; expression.
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:
902 ;; (ad-start-advice)
903 ;; nil
905 ;; We start by defining an innocent looking function `foo' that simply
906 ;; adds 1 to its argument X:
908 ;; (defun foo (x)
909 ;; "Add 1 to X."
910 ;; (1+ x))
911 ;; foo
913 ;; (foo 3)
914 ;; 4
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)
939 ;; "Add 2 to X."
940 ;; (setq x (1+ x)))
941 ;; foo
943 ;; (foo 3)
944 ;; 5
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."
960 ;; (setq x (1- x)))
961 ;; foo
963 ;; (foo 3)
964 ;; 4
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."
978 ;; (setq x (1- x)))
979 ;; foo
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)
988 ;; "Add 1 to X.
990 ;; This function is advised with the following advice(s):
992 ;; fg-cancel-add2 (before):
993 ;; Again only add 1 to X.
995 ;; fg-add2 (before):
996 ;; Add 2 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)))
1009 ;; foo
1011 ;; (call-interactively 'foo)
1012 ;; 6
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)))
1021 ;; foo
1023 ;; (call-interactively 'foo)
1024 ;; 6
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)
1030 ;; (lambda (x)
1031 ;; "$ad-doc: foo$"
1032 ;; (interactive (list 5))
1033 ;; (let (ad-return-value)
1034 ;; (setq x (1- x))
1035 ;; (setq x (1+ x))
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)))
1054 ;; ad-do-it))
1055 ;; foo
1057 ;; (foo 3)
1058 ;; 7
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)
1068 ;; "Add 1 to X."
1069 ;; (let ((x (1+ x)))
1070 ;; ad-do-it))
1071 ;; foo
1073 ;; (foo 3)
1074 ;; 8
1076 ;; Again, let's see what the definition of `foo' looks like so far:
1078 ;; (symbol-function 'foo)
1079 ;; (lambda (x)
1080 ;; "$ad-doc: foo$"
1081 ;; (interactive (list 5))
1082 ;; (let (ad-return-value)
1083 ;; (setq x (1- x))
1084 ;; (setq x (1+ x))
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.
1097 ;; For example:
1099 ;; (defadvice foo (after fg-times-x)
1100 ;; "Multiply the result with X."
1101 ;; (setq ad-return-value (* ad-return-value x)))
1102 ;; foo
1104 ;; This still yields the same result as before:
1105 ;; (foo 3)
1106 ;; 8
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)))
1117 ;; foo
1119 ;; Now the advices have an effect:
1121 ;; (foo 3)
1122 ;; 72
1124 ;; @@ Protecting advice execution:
1125 ;; ===============================
1126 ;; Once in a while we define an advice to perform some cleanup action,
1127 ;; for example:
1129 ;; (defadvice foo (after fg-cleanup last act)
1130 ;; "Do some cleanup."
1131 ;; (print "Let's clean up now!"))
1132 ;; foo
1134 ;; However, in case of an error the cleanup won't be performed:
1136 ;; (condition-case error
1137 ;; (foo t)
1138 ;; (error 'error-in-foo))
1139 ;; 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!"))
1149 ;; foo
1151 ;; Now the cleanup form will be executed even in case of an error:
1153 ;; (condition-case error
1154 ;; (foo t)
1155 ;; (error 'error-in-foo))
1156 ;; "Let's clean up now!"
1157 ;; error-in-foo
1159 ;; Again, let's see what `foo' looks like:
1161 ;; (symbol-function 'foo)
1162 ;; (lambda (x)
1163 ;; "$ad-doc: foo$"
1164 ;; (interactive (list 5))
1165 ;; (let (ad-return-value)
1166 ;; (unwind-protect
1167 ;; (progn (setq x (1- x))
1168 ;; (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!"))
1186 ;; foo
1188 ;; Now `foo' is byte-compiled:
1190 ;; (symbol-function 'foo)
1191 ;; (lambda (x)
1192 ;; "$ad-doc: 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))
1196 ;; (foo 3)
1197 ;; "Let's clean up now!"
1198 ;; 72
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)
1213 ;; nil
1215 ;; For this to have an effect we have to activate `foo':
1217 ;; (ad-activate 'foo)
1218 ;; foo
1220 ;; (foo 3)
1221 ;; "Let's clean up now!"
1222 ;; 24
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")
1231 ;; nil
1233 ;; (ad-activate 'foo)
1234 ;; foo
1236 ;; (foo 3)
1237 ;; "Let's clean up now!"
1238 ;; 5
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-")
1250 ;; 9
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-")
1259 ;; nil
1261 ;; (foo 3)
1262 ;; "Let's clean up now!"
1263 ;; 72
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."
1272 ;; (setq x (1+ x)))
1273 ;; foo
1275 ;; (ad-activate 'foo)
1276 ;; foo
1278 ;; (foo 3)
1279 ;; "Let's clean up now!"
1280 ;; 72
1282 ;; (ad-enable-advice 'foo 'before 'fg-1-more)
1283 ;; nil
1285 ;; (ad-activate 'foo)
1286 ;; foo
1288 ;; (foo 3)
1289 ;; "Let's clean up now!"
1290 ;; 160
1292 ;; @@ Caching:
1293 ;; ===========
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-")
1304 ;; nil
1306 ;; (foo 3)
1307 ;; 4
1309 ;; (ad-activate-regexp "^fg-")
1310 ;; nil
1312 ;; (eq old-definition (symbol-function 'foo))
1313 ;; t
1315 ;; (foo 3)
1316 ;; "Let's clean up now!"
1317 ;; 160
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)
1325 ;; 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."
1334 ;; (setq x (1- x)))
1335 ;; bar
1337 ;; `bar' is not yet defined:
1338 ;; (fboundp 'bar)
1339 ;; nil
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'):
1345 ;; (defun bar (x)
1346 ;; "Subtract 1 from X."
1347 ;; (1- x))
1348 ;; bar
1350 ;; (bar 4)
1351 ;; 2
1353 ;; Redefinition will activate any available advice if the value of
1354 ;; `ad-redefinition-action' is either `warn', `accept' or `discard':
1356 ;; (defun bar (x)
1357 ;; "Subtract 2 from X."
1358 ;; (- x 2))
1359 ;; bar
1361 ;; (bar 4)
1362 ;; 1
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.
1370 ;; (defun fie (x)
1371 ;; "Multiply X by 2."
1372 ;; (* x 2))
1373 ;; fie
1375 ;; (defadvice fie (before fg-times-4 preact)
1376 ;; "Multiply X by 4."
1377 ;; (setq x (* x 2)))
1378 ;; fie
1380 ;; This advice did not affect `fie'...
1382 ;; (fie 2)
1383 ;; 4
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
1387 ;; preactivation:
1389 ;; (setq cached-definition (ad-get-cache-definition 'fie))
1390 ;; (lambda (x) ....)
1392 ;; (ad-activate 'fie)
1393 ;; fie
1395 ;; (eq cached-definition (symbol-function 'fie))
1396 ;; t
1398 ;; (fie 2)
1399 ;; 8
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))))
1411 ;; fg-defadvice-fum
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:
1418 ;; (defun fum (x)
1419 ;; "Multiply X by 2."
1420 ;; (* x 2))
1421 ;; fum
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:
1432 ;; (fum 2)
1433 ;; 4
1435 ;; (ad-get-advice-info 'fum)
1436 ;; nil
1438 ;; (fg-defadvice-fum)
1439 ;; 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)
1446 ;; (lambda (x)
1447 ;; "$ad-doc: fum$"
1448 ;; (byte-code "....." [ad-return-value x nil * 2 ad-Orig-fum] 4))
1450 ;; (fum 2)
1451 ;; 8
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: "))
1466 ;; fum
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)
1474 ;; fum
1476 ;; A new uncompiled advised definition got constructed:
1478 ;; (ad-compiled-p (symbol-function 'fum))
1479 ;; nil
1481 ;; (fum 2)
1482 ;; 8
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)
1511 ;; "Add 3 numbers."
1512 ;; (+ x y z))
1513 ;; fuu
1515 ;; (fuu 1 1 1)
1516 ;; 3
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))))
1527 ;; fuu
1529 ;; (fuu 1 1 1)
1530 ;; 6
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)
1538 ;; "Add NUMBERS."
1539 ;; (apply '+ numbers))
1540 ;; fuu
1542 ;; (fuu 1 1 1)
1543 ;; 6
1545 ;; (fuu 1 1 1 1 1 1)
1546 ;; 9
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)))
1561 ;; fuu
1563 ;; (fuu 1 2 3 4 5)
1564 ;; (1 2 3 4 5)
1565 ;; 18
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))))
1570 ;; fuu
1572 ;; (fuu 1 2 3 4 4 4 4 4 4)
1573 ;; (1 3 2)
1574 ;; 9
1576 ;; (defun fuu (x y z)
1577 ;; "Add 3 numbers."
1578 ;; (+ x y z))
1580 ;; (fuu 1 2 3)
1581 ;; (1 3 2)
1582 ;; 9
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.
1597 ;; (defun fii (x)
1598 ;; "Add 1 to X."
1599 ;; (1+ x))
1600 ;; fii
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)))))
1611 ;; fii
1613 ;; (fii 3)
1614 ;; 4
1616 ;; (fii 3 2)
1617 ;; 5
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)))
1635 ;; kill-buffer
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)))
1645 ;; kill-buffer
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))))
1661 ;; foom
1663 ;; (foom '(a))
1664 ;; ((a))
1666 ;; (defadvice foom (before fg-print-x act)
1667 ;; "Print the value of X."
1668 ;; (print x))
1669 ;; foom
1671 ;; The following works as expected because evaluation immediately follows
1672 ;; macro expansion:
1674 ;; (foom '(a))
1675 ;; (quote (a))
1676 ;; ((a))
1678 ;; However, the printing happens during expansion (or byte-compile) time:
1680 ;; (macroexpand '(foom '(a)))
1681 ;; (quote (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)
1688 ;; nil
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)))))
1695 ;; foom
1697 ;; (macroexpand '(foom '(a)))
1698 ;; (progn (print (quote (a))) (list (quote (a))))
1700 ;; (foom '(a))
1701 ;; (a)
1702 ;; ((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
1729 ;; special forms.
1731 ;; Apart from the safety concerns advising special forms is not any different
1732 ;; from advising plain functions or subrs.
1735 ;;; Code:
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")
1751 ;; @@ Variable definitions:
1752 ;; ========================
1754 (defgroup advice nil
1755 "An overloading mechanism for Emacs Lisp functions."
1756 :prefix "ad-"
1757 :link '(custom-manual "(elisp)Advising Functions")
1758 :group 'lisp)
1760 (defconst ad-version "2.14")
1762 ;;;###autoload
1763 (defcustom ad-redefinition-action 'warn
1764 "Defines what to do with redefinitions during Advice de/activation.
1765 Redefinition occurs if a previously activated function that already has an
1766 original definition associated with it gets redefined and then de/activated.
1767 In such a case we can either accept the current definition as the new
1768 original definition, discard the current definition and replace it with the
1769 old original, or keep it and raise an error. The values `accept', `discard',
1770 `error' or `warn' govern what will be done. `warn' is just like `accept' but
1771 it additionally prints a warning message. All other values will be
1772 interpreted as `error'."
1773 :type '(choice (const accept) (const discard) (const warn)
1774 (other :tag "error" error))
1775 :group 'advice)
1777 ;;;###autoload
1778 (defcustom ad-default-compilation-action 'maybe
1779 "Defines whether to compile advised definitions during activation.
1780 A value of `always' will result in unconditional compilation, `never' will
1781 always avoid compilation, `maybe' will compile if the byte-compiler is already
1782 loaded, and `like-original' will compile if the original definition of the
1783 advised function is compiled or a built-in function. Every other value will
1784 be interpreted as `maybe'. This variable will only be considered if the
1785 COMPILE argument of `ad-activate' was supplied as nil."
1786 :type '(choice (const always) (const never) (const like-original)
1787 (other :tag "maybe" maybe))
1788 :group 'advice)
1792 ;; @@ Some utilities:
1793 ;; ==================
1795 ;; We don't want the local arguments to interfere with anything
1796 ;; referenced in the supplied functions => the cryptic casing:
1797 (defun ad-substitute-tree (sUbTrEe-TeSt fUnCtIoN tReE)
1798 "Substitute qualifying subTREEs with result of FUNCTION(subTREE).
1799 Only proper subtrees are considered, for example, if TREE is (1 (2 (3)) 4)
1800 then the subtrees will be 1 (2 (3)) 2 (3) 3 4, dotted structures are
1801 allowed too. Once a qualifying subtree has been found its subtrees will
1802 not be considered anymore. (ad-substitute-tree 'atom 'identity tree)
1803 generates a copy of TREE."
1804 (cond ((consp tReE)
1805 (cons (if (funcall sUbTrEe-TeSt (car tReE))
1806 (funcall fUnCtIoN (car tReE))
1807 (if (consp (car tReE))
1808 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN (car tReE))
1809 (car tReE)))
1810 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN (cdr tReE))))
1811 ((funcall sUbTrEe-TeSt tReE)
1812 (funcall fUnCtIoN tReE))
1813 (t tReE)))
1815 ;; this is just faster than `ad-substitute-tree':
1816 (defun ad-copy-tree (tree)
1817 "Return a copy of the list structure of TREE."
1818 (cond ((consp tree)
1819 (cons (ad-copy-tree (car tree))
1820 (ad-copy-tree (cdr tree))))
1821 (t tree)))
1823 (defmacro ad-dolist (varform &rest body)
1824 "A Common-Lisp-style dolist iterator with the following syntax:
1826 (ad-dolist (VAR INIT-FORM [RESULT-FORM])
1827 BODY-FORM...)
1829 which will iterate over the list yielded by INIT-FORM binding VAR to the
1830 current head at every iteration. If RESULT-FORM is supplied its value will
1831 be returned at the end of the iteration, nil otherwise. The iteration can be
1832 exited prematurely with `(ad-do-return [VALUE])'."
1833 (let ((expansion
1834 `(let ((ad-dO-vAr ,(car (cdr varform)))
1835 ,(car varform))
1836 (while ad-dO-vAr
1837 (setq ,(car varform) (car ad-dO-vAr))
1838 ,@body
1839 ;;work around a backquote bug:
1840 ;;(` ((,@ '(foo)) (bar))) => (append '(foo) '(((bar)))) wrong
1841 ;;(` ((,@ '(foo)) (, '(bar)))) => (append '(foo) (list '(bar)))
1842 ,'(setq ad-dO-vAr (cdr ad-dO-vAr)))
1843 ,(car (cdr (cdr varform))))))
1844 ;;ok, this wastes some cons cells but only during compilation:
1845 (if (catch 'contains-return
1846 (ad-substitute-tree
1847 (function (lambda (subtree)
1848 (cond ((eq (car-safe subtree) 'ad-dolist))
1849 ((eq (car-safe subtree) 'ad-do-return)
1850 (throw 'contains-return t)))))
1851 'identity body)
1852 nil)
1853 `(catch 'ad-dO-eXiT ,expansion)
1854 expansion)))
1856 (defmacro ad-do-return (value)
1857 `(throw 'ad-dO-eXiT ,value))
1859 (if (not (get 'ad-dolist 'lisp-indent-hook))
1860 (put 'ad-dolist 'lisp-indent-hook 1))
1863 ;; @@ Save real definitions of subrs used by Advice:
1864 ;; =================================================
1865 ;; Advice depends on the real, unmodified functionality of various subrs,
1866 ;; we save them here so advised versions will not interfere (eventually,
1867 ;; we will save all subrs used in code generated by Advice):
1869 (defmacro ad-save-real-definition (function)
1870 (let ((saved-function (intern (format "ad-real-%s" function))))
1871 ;; Make sure the compiler is loaded during macro expansion:
1872 (require 'byte-compile "bytecomp")
1873 `(if (not (fboundp ',saved-function))
1874 (progn (fset ',saved-function (symbol-function ',function))
1875 ;; Copy byte-compiler properties:
1876 ,@(if (get function 'byte-compile)
1877 `((put ',saved-function 'byte-compile
1878 ',(get function 'byte-compile))))
1879 ,@(if (get function 'byte-opcode)
1880 `((put ',saved-function 'byte-opcode
1881 ',(get function 'byte-opcode))))))))
1883 (defun ad-save-real-definitions ()
1884 ;; Macro expansion will hardcode the values of the various byte-compiler
1885 ;; properties into the compiled version of this function such that the
1886 ;; proper values will be available at runtime without loading the compiler:
1887 (ad-save-real-definition fset)
1888 (ad-save-real-definition documentation))
1890 (ad-save-real-definitions)
1893 ;; @@ Advice info access fns:
1894 ;; ==========================
1896 ;; Advice information for a particular function is stored on the
1897 ;; advice-info property of the function symbol. It is stored as an
1898 ;; alist of the following format:
1900 ;; ((active . t/nil)
1901 ;; (before adv1 adv2 ...)
1902 ;; (around adv1 adv2 ...)
1903 ;; (after adv1 adv2 ...)
1904 ;; (activation adv1 adv2 ...)
1905 ;; (deactivation adv1 adv2 ...)
1906 ;; (origname . <symbol fbound to origdef>)
1907 ;; (cache . (<advised-definition> . <id>)))
1909 ;; List of currently advised though not necessarily activated functions
1910 ;; (this list is maintained as a completion table):
1911 (defvar ad-advised-functions nil)
1913 (defmacro ad-pushnew-advised-function (function)
1914 "Add FUNCTION to `ad-advised-functions' unless its already there."
1915 `(if (not (assoc (symbol-name ,function) ad-advised-functions))
1916 (setq ad-advised-functions
1917 (cons (list (symbol-name ,function))
1918 ad-advised-functions))))
1920 (defmacro ad-pop-advised-function (function)
1921 "Remove FUNCTION from `ad-advised-functions'."
1922 `(setq ad-advised-functions
1923 (delq (assoc (symbol-name ,function) ad-advised-functions)
1924 ad-advised-functions)))
1926 (defmacro ad-do-advised-functions (varform &rest body)
1927 "`ad-dolist'-style iterator that maps over `ad-advised-functions'.
1928 \(ad-do-advised-functions (VAR [RESULT-FORM])
1929 BODY-FORM...)
1930 On each iteration VAR will be bound to the name of an advised function
1931 \(a symbol)."
1932 `(ad-dolist (,(car varform)
1933 ad-advised-functions
1934 ,(car (cdr varform)))
1935 (setq ,(car varform) (intern (car ,(car varform))))
1936 ,@body))
1938 (if (not (get 'ad-do-advised-functions 'lisp-indent-hook))
1939 (put 'ad-do-advised-functions 'lisp-indent-hook 1))
1941 (defun ad-get-advice-info (function)
1942 (get function 'ad-advice-info))
1944 (defmacro ad-get-advice-info-macro (function)
1945 `(get ,function 'ad-advice-info))
1947 (defmacro ad-set-advice-info (function advice-info)
1948 `(put ,function 'ad-advice-info ,advice-info))
1950 (defmacro ad-copy-advice-info (function)
1951 `(ad-copy-tree (get ,function 'ad-advice-info)))
1953 (defmacro ad-is-advised (function)
1954 "Return non-nil if FUNCTION has any advice info associated with it.
1955 This does not mean that the advice is also active."
1956 (list 'ad-get-advice-info-macro function))
1958 (defun ad-initialize-advice-info (function)
1959 "Initialize the advice info for FUNCTION.
1960 Assumes that FUNCTION has not yet been advised."
1961 (ad-pushnew-advised-function function)
1962 (ad-set-advice-info function (list (cons 'active nil))))
1964 (defmacro ad-get-advice-info-field (function field)
1965 "Retrieve the value of the advice info FIELD of FUNCTION."
1966 `(cdr (assq ,field (ad-get-advice-info-macro ,function))))
1968 (defun ad-set-advice-info-field (function field value)
1969 "Destructively modify VALUE of the advice info FIELD of FUNCTION."
1970 (and (ad-is-advised function)
1971 (cond ((assq field (ad-get-advice-info-macro function))
1972 ;; A field with that name is already present:
1973 (rplacd (assq field (ad-get-advice-info-macro function)) value))
1974 (t;; otherwise, create a new field with that name:
1975 (nconc (ad-get-advice-info-macro function)
1976 (list (cons field value)))))))
1978 ;; Don't make this a macro so we can use it as a predicate:
1979 (defun ad-is-active (function)
1980 "Return non-nil if FUNCTION is advised and activated."
1981 (ad-get-advice-info-field function 'active))
1984 ;; @@ Access fns for single pieces of advice and related predicates:
1985 ;; =================================================================
1987 (defun ad-make-advice (name protect enable definition)
1988 "Constructs single piece of advice to be stored in some advice-info.
1989 NAME should be a non-nil symbol, PROTECT and ENABLE should each be
1990 either t or nil, and DEFINITION should be a list of the form
1991 `(advice lambda ARGLIST [DOCSTRING] [INTERACTIVE-FORM] BODY...)'."
1992 (list name protect enable definition))
1994 ;; ad-find-advice uses the alist structure directly ->
1995 ;; change if this data structure changes!!
1996 (defmacro ad-advice-name (advice)
1997 (list 'car advice))
1998 (defmacro ad-advice-protected (advice)
1999 (list 'nth 1 advice))
2000 (defmacro ad-advice-enabled (advice)
2001 (list 'nth 2 advice))
2002 (defmacro ad-advice-definition (advice)
2003 (list 'nth 3 advice))
2005 (defun ad-advice-set-enabled (advice flag)
2006 (rplaca (cdr (cdr advice)) flag))
2008 (defun ad-class-p (thing)
2009 (memq thing ad-advice-classes))
2010 (defun ad-name-p (thing)
2011 (and thing (symbolp thing)))
2012 (defun ad-position-p (thing)
2013 (or (natnump thing)
2014 (memq thing '(first last))))
2017 ;; @@ Advice access functions:
2018 ;; ===========================
2020 ;; List of defined advice classes:
2021 (defvar ad-advice-classes '(before around after activation deactivation))
2023 (defun ad-has-enabled-advice (function class)
2024 "True if at least one of FUNCTION's advices in CLASS is enabled."
2025 (ad-dolist (advice (ad-get-advice-info-field function class))
2026 (if (ad-advice-enabled advice) (ad-do-return t))))
2028 (defun ad-has-redefining-advice (function)
2029 "True if FUNCTION's advice info defines at least 1 redefining advice.
2030 Redefining advices affect the construction of an advised definition."
2031 (and (ad-is-advised function)
2032 (or (ad-has-enabled-advice function 'before)
2033 (ad-has-enabled-advice function 'around)
2034 (ad-has-enabled-advice function 'after))))
2036 (defun ad-has-any-advice (function)
2037 "True if the advice info of FUNCTION defines at least one advice."
2038 (and (ad-is-advised function)
2039 (ad-dolist (class ad-advice-classes nil)
2040 (if (ad-get-advice-info-field function class)
2041 (ad-do-return t)))))
2043 (defun ad-get-enabled-advices (function class)
2044 "Return the list of enabled advices of FUNCTION in CLASS."
2045 (let (enabled-advices)
2046 (ad-dolist (advice (ad-get-advice-info-field function class))
2047 (if (ad-advice-enabled advice)
2048 (push advice enabled-advices)))
2049 (reverse enabled-advices)))
2052 ;; @@ Dealing with automatic advice activation via `fset/defalias':
2053 ;; ================================================================
2055 ;; Since Emacs 19.26 the built-in versions of `fset' and `defalias'
2056 ;; take care of automatic advice activation, hence, we don't have to
2057 ;; hack it anymore by advising `fset/defun/defmacro/byte-code/etc'.
2059 ;; The functionality of the new `fset' is as follows:
2061 ;; fset(sym,newdef)
2062 ;; assign NEWDEF to SYM
2063 ;; if (get SYM 'ad-advice-info)
2064 ;; ad-activate-internal(SYM, nil)
2065 ;; return (symbol-function SYM)
2067 ;; Whether advised definitions created by automatic activations will be
2068 ;; compiled depends on the value of `ad-default-compilation-action'.
2070 ;; Since calling `ad-activate-internal' in the built-in definition of `fset' can
2071 ;; create major disasters we have to be a bit careful. One precaution is
2072 ;; to provide a dummy definition for `ad-activate-internal' which can be used to
2073 ;; turn off automatic advice activation (e.g., when `ad-stop-advice' or
2074 ;; `ad-recover-normality' are called). Another is to avoid recursive calls
2075 ;; to `ad-activate' by using `ad-with-auto-activation-disabled' where
2076 ;; appropriate, especially in a safe version of `fset'.
2078 ;; For now define `ad-activate-internal' to the dummy definition:
2079 (defun ad-activate-internal (function &optional compile)
2080 "Automatic advice activation is disabled. `ad-start-advice' enables it."
2081 nil)
2083 ;; This is just a copy of the above:
2084 (defun ad-activate-internal-off (function &optional compile)
2085 "Automatic advice activation is disabled. `ad-start-advice' enables it."
2086 nil)
2088 ;; This will be t for top-level calls to `ad-activate-internal-on':
2089 (defvar ad-activate-on-top-level t)
2091 (defmacro ad-with-auto-activation-disabled (&rest body)
2092 `(let ((ad-activate-on-top-level nil))
2093 ,@body))
2095 (defun ad-safe-fset (symbol definition)
2096 "A safe `fset' which will never call `ad-activate-internal' recursively."
2097 (ad-with-auto-activation-disabled
2098 (ad-real-fset symbol definition)))
2101 ;; @@ Access functions for original definitions:
2102 ;; ============================================
2103 ;; The advice-info of an advised function contains its `origname' which is
2104 ;; a symbol that is fbound to the original definition available at the first
2105 ;; proper activation of the function after a valid re/definition. If the
2106 ;; original was defined via fcell indirection then `origname' will be defined
2107 ;; just so. Hence, to get hold of the actual original definition of a function
2108 ;; we need to use `ad-real-orig-definition'.
2110 (defun ad-make-origname (function)
2111 "Make name to be used to call the original FUNCTION."
2112 (intern (format "ad-Orig-%s" function)))
2114 (defmacro ad-get-orig-definition (function)
2115 `(let ((origname (ad-get-advice-info-field ,function 'origname)))
2116 (if (fboundp origname)
2117 (symbol-function origname))))
2119 (defmacro ad-set-orig-definition (function definition)
2120 `(ad-safe-fset
2121 (ad-get-advice-info-field ,function 'origname) ,definition))
2123 (defmacro ad-clear-orig-definition (function)
2124 `(fmakunbound (ad-get-advice-info-field ,function 'origname)))
2127 ;; @@ Interactive input functions:
2128 ;; ===============================
2130 (declare-function 'function-called-at-point "help")
2132 (defun ad-read-advised-function (&optional prompt predicate default)
2133 "Read name of advised function with completion from the minibuffer.
2134 An optional PROMPT will be used to prompt for the function. PREDICATE
2135 plays the same role as for `try-completion' (which see). DEFAULT will
2136 be returned on empty input (defaults to the first advised function or
2137 function at point for which PREDICATE returns non-nil)."
2138 (if (null ad-advised-functions)
2139 (error "ad-read-advised-function: There are no advised functions"))
2140 (setq default
2141 (or default
2142 ;; Prefer func name at point, if it's in ad-advised-functions etc.
2143 (let ((function (progn
2144 (require 'help)
2145 (function-called-at-point))))
2146 (and function
2147 (assoc (symbol-name function) ad-advised-functions)
2148 (or (null predicate)
2149 (funcall predicate function))
2150 function))
2151 (ad-do-advised-functions (function)
2152 (if (or (null predicate)
2153 (funcall predicate function))
2154 (ad-do-return function)))
2155 (error "ad-read-advised-function: %s"
2156 "There are no qualifying advised functions")))
2157 (let* ((ad-pReDiCaTe predicate)
2158 (function
2159 (completing-read
2160 (format "%s (default %s): " (or prompt "Function") default)
2161 ad-advised-functions
2162 (if predicate
2163 (function
2164 (lambda (function)
2165 ;; Oops, no closures - the joys of dynamic scoping:
2166 ;; `predicate' clashed with the `predicate' argument
2167 ;; of Lemacs' `completing-read'.....
2168 (funcall ad-pReDiCaTe (intern (car function))))))
2169 t)))
2170 (if (equal function "")
2171 (if (ad-is-advised default)
2172 default
2173 (error "ad-read-advised-function: `%s' is not advised" default))
2174 (intern function))))
2176 (defvar ad-advice-class-completion-table
2177 (mapcar (lambda (class) (list (symbol-name class)))
2178 ad-advice-classes))
2180 (defun ad-read-advice-class (function &optional prompt default)
2181 "Read a valid advice class with completion from the minibuffer.
2182 An optional PROMPT will be used to prompt for the class. DEFAULT will
2183 be returned on empty input (defaults to the first non-empty advice
2184 class of FUNCTION)."
2185 (setq default
2186 (or default
2187 (ad-dolist (class ad-advice-classes)
2188 (if (ad-get-advice-info-field function class)
2189 (ad-do-return class)))
2190 (error "ad-read-advice-class: `%s' has no advices" function)))
2191 (let ((class (completing-read
2192 (format "%s (default %s): " (or prompt "Class") default)
2193 ad-advice-class-completion-table nil t)))
2194 (if (equal class "")
2195 default
2196 (intern class))))
2198 (defun ad-read-advice-name (function class &optional prompt)
2199 "Read name of existing advice of CLASS for FUNCTION with completion.
2200 An optional PROMPT is used to prompt for the name."
2201 (let* ((name-completion-table
2202 (mapcar (function (lambda (advice)
2203 (list (symbol-name (ad-advice-name advice)))))
2204 (ad-get-advice-info-field function class)))
2205 (default
2206 (if (null name-completion-table)
2207 (error "ad-read-advice-name: `%s' has no %s advice"
2208 function class)
2209 (car (car name-completion-table))))
2210 (prompt (format "%s (default %s): " (or prompt "Name") default))
2211 (name (completing-read prompt name-completion-table nil t)))
2212 (if (equal name "")
2213 (intern default)
2214 (intern name))))
2216 (defun ad-read-advice-specification (&optional prompt)
2217 "Read a complete function/class/name specification from minibuffer.
2218 The list of read symbols will be returned. The optional PROMPT will
2219 be used to prompt for the function."
2220 (let* ((function (ad-read-advised-function prompt))
2221 (class (ad-read-advice-class function))
2222 (name (ad-read-advice-name function class)))
2223 (list function class name)))
2225 ;; Use previous regexp as a default:
2226 (defvar ad-last-regexp "")
2228 (defun ad-read-regexp (&optional prompt)
2229 "Read a regular expression from the minibuffer."
2230 (let ((regexp (read-from-minibuffer
2231 (concat (or prompt "Regular expression")
2232 (if (equal ad-last-regexp "") ": "
2233 (format " (default %s): " ad-last-regexp))))))
2234 (setq ad-last-regexp
2235 (if (equal regexp "") ad-last-regexp regexp))))
2238 ;; @@ Finding, enabling, adding and removing pieces of advice:
2239 ;; ===========================================================
2241 (defmacro ad-find-advice (function class name)
2242 "Find the first advice of FUNCTION in CLASS with NAME."
2243 `(assq ,name (ad-get-advice-info-field ,function ,class)))
2245 (defun ad-advice-position (function class name)
2246 "Return position of first advice of FUNCTION in CLASS with NAME."
2247 (let* ((found-advice (ad-find-advice function class name))
2248 (advices (ad-get-advice-info-field function class)))
2249 (if found-advice
2250 (- (length advices) (length (memq found-advice advices))))))
2252 (defun ad-find-some-advice (function class name)
2253 "Find the first of FUNCTION's advices in CLASS matching NAME.
2254 NAME can be a symbol or a regular expression matching part of an advice name.
2255 If CLASS is `any' all valid advice classes will be checked."
2256 (if (ad-is-advised function)
2257 (let (found-advice)
2258 (ad-dolist (advice-class ad-advice-classes)
2259 (if (or (eq class 'any) (eq advice-class class))
2260 (setq found-advice
2261 (ad-dolist (advice (ad-get-advice-info-field
2262 function advice-class))
2263 (if (or (and (stringp name)
2264 (string-match
2265 name (symbol-name
2266 (ad-advice-name advice))))
2267 (eq name (ad-advice-name advice)))
2268 (ad-do-return advice)))))
2269 (if found-advice (ad-do-return found-advice))))))
2271 (defun ad-enable-advice-internal (function class name flag)
2272 "Set enable FLAG of FUNCTION's advices in CLASS matching NAME.
2273 If NAME is a string rather than a symbol then it's interpreted as a regular
2274 expression and all advices whose name contain a match for it will be
2275 affected. If CLASS is `any' advices in all valid advice classes will be
2276 considered. The number of changed advices will be returned (or nil if
2277 FUNCTION was not advised)."
2278 (if (ad-is-advised function)
2279 (let ((matched-advices 0))
2280 (ad-dolist (advice-class ad-advice-classes)
2281 (if (or (eq class 'any) (eq advice-class class))
2282 (ad-dolist (advice (ad-get-advice-info-field
2283 function advice-class))
2284 (cond ((or (and (stringp name)
2285 (string-match
2286 name (symbol-name (ad-advice-name advice))))
2287 (eq name (ad-advice-name advice)))
2288 (setq matched-advices (1+ matched-advices))
2289 (ad-advice-set-enabled advice flag))))))
2290 matched-advices)))
2292 ;;;###autoload
2293 (defun ad-enable-advice (function class name)
2294 "Enables the advice of FUNCTION with CLASS and NAME."
2295 (interactive (ad-read-advice-specification "Enable advice of"))
2296 (if (ad-is-advised function)
2297 (if (eq (ad-enable-advice-internal function class name t) 0)
2298 (error "ad-enable-advice: `%s' has no %s advice matching `%s'"
2299 function class name))
2300 (error "ad-enable-advice: `%s' is not advised" function)))
2302 ;;;###autoload
2303 (defun ad-disable-advice (function class name)
2304 "Disable the advice of FUNCTION with CLASS and NAME."
2305 (interactive (ad-read-advice-specification "Disable advice of"))
2306 (if (ad-is-advised function)
2307 (if (eq (ad-enable-advice-internal function class name nil) 0)
2308 (error "ad-disable-advice: `%s' has no %s advice matching `%s'"
2309 function class name))
2310 (error "ad-disable-advice: `%s' is not advised" function)))
2312 (defun ad-enable-regexp-internal (regexp class flag)
2313 "Set enable FLAGs of all CLASS advices whose name contains a REGEXP match.
2314 If CLASS is `any' all valid advice classes are considered. The number of
2315 affected advices will be returned."
2316 (let ((matched-advices 0))
2317 (ad-do-advised-functions (advised-function)
2318 (setq matched-advices
2319 (+ matched-advices
2320 (or (ad-enable-advice-internal
2321 advised-function class regexp flag)
2322 0))))
2323 matched-advices))
2325 (defun ad-enable-regexp (regexp)
2326 "Enables all advices with names that contain a match for REGEXP.
2327 All currently advised functions will be considered."
2328 (interactive
2329 (list (ad-read-regexp "Enable advices via regexp")))
2330 (let ((matched-advices (ad-enable-regexp-internal regexp 'any t)))
2331 (if (called-interactively-p 'interactive)
2332 (message "%d matching advices enabled" matched-advices))
2333 matched-advices))
2335 (defun ad-disable-regexp (regexp)
2336 "Disable all advices with names that contain a match for REGEXP.
2337 All currently advised functions will be considered."
2338 (interactive
2339 (list (ad-read-regexp "Disable advices via regexp")))
2340 (let ((matched-advices (ad-enable-regexp-internal regexp 'any nil)))
2341 (if (called-interactively-p 'interactive)
2342 (message "%d matching advices disabled" matched-advices))
2343 matched-advices))
2345 (defun ad-remove-advice (function class name)
2346 "Remove FUNCTION's advice with NAME from its advices in CLASS.
2347 If such an advice was found it will be removed from the list of advices
2348 in that CLASS."
2349 (interactive (ad-read-advice-specification "Remove advice of"))
2350 (if (ad-is-advised function)
2351 (let ((advice-to-remove (ad-find-advice function class name)))
2352 (if advice-to-remove
2353 (ad-set-advice-info-field
2354 function class
2355 (delq advice-to-remove (ad-get-advice-info-field function class)))
2356 (error "ad-remove-advice: `%s' has no %s advice `%s'"
2357 function class name)))
2358 (error "ad-remove-advice: `%s' is not advised" function)))
2360 ;;;###autoload
2361 (defun ad-add-advice (function advice class position)
2362 "Add a piece of ADVICE to FUNCTION's list of advices in CLASS.
2364 ADVICE has the form (NAME PROTECTED ENABLED DEFINITION), where
2365 NAME is the advice name; PROTECTED is a flag specifying whether
2366 to protect against non-local exits; ENABLED is a flag specifying
2367 whether to initially enable the advice; and DEFINITION has the
2368 form (advice . LAMBDA), where LAMBDA is a lambda expression.
2370 If FUNCTION already has a piece of advice with the same name,
2371 then POSITION is ignored, and the old advice is overwritten with
2372 the new one.
2374 If FUNCTION already has one or more pieces of advice of the
2375 specified CLASS, then POSITION determines where the new piece
2376 goes. POSITION can either be `first', `last' or a number (where
2377 0 corresponds to `first', and numbers outside the valid range are
2378 mapped to the closest extremal position).
2380 If FUNCTION was not advised already, its advice info will be
2381 initialized. Redefining a piece of advice whose name is part of
2382 the cache-id will clear the cache.
2384 See Info node `(elisp)Computed Advice' for detailed documentation."
2385 (cond ((not (ad-is-advised function))
2386 (ad-initialize-advice-info function)
2387 (ad-set-advice-info-field
2388 function 'origname (ad-make-origname function))))
2389 (let* ((previous-position
2390 (ad-advice-position function class (ad-advice-name advice)))
2391 (advices (ad-get-advice-info-field function class))
2392 ;; Determine a numerical position for the new advice:
2393 (position (cond (previous-position)
2394 ((eq position 'first) 0)
2395 ((eq position 'last) (length advices))
2396 ((numberp position)
2397 (max 0 (min position (length advices))))
2398 (t 0))))
2399 ;; Check whether we have to clear the cache:
2400 (if (memq (ad-advice-name advice) (ad-get-cache-class-id function class))
2401 (ad-clear-cache function))
2402 (if previous-position
2403 (setcar (nthcdr position advices) advice)
2404 (if (= position 0)
2405 (ad-set-advice-info-field function class (cons advice advices))
2406 (setcdr (nthcdr (1- position) advices)
2407 (cons advice (nthcdr position advices)))))))
2410 ;; @@ Accessing and manipulating function definitions:
2411 ;; ===================================================
2413 (defmacro ad-macrofy (definition)
2414 "Take a lambda function DEFINITION and make a macro out of it."
2415 `(cons 'macro ,definition))
2417 (defmacro ad-lambdafy (definition)
2418 "Take a macro function DEFINITION and make a lambda out of it."
2419 `(cdr ,definition))
2421 (defun ad-special-form-p (definition)
2422 "Non-nil if and only if DEFINITION is a special form."
2423 (if (and (symbolp definition) (fboundp definition))
2424 (setq definition (indirect-function definition)))
2425 (and (subrp definition) (eq (cdr (subr-arity definition)) 'unevalled)))
2427 (defmacro ad-subr-p (definition)
2428 ;;"non-nil if DEFINITION is a subr."
2429 (list 'subrp definition))
2431 (defmacro ad-macro-p (definition)
2432 ;;"non-nil if DEFINITION is a macro."
2433 `(eq (car-safe ,definition) 'macro))
2435 (defmacro ad-lambda-p (definition)
2436 ;;"non-nil if DEFINITION is a lambda expression."
2437 `(eq (car-safe ,definition) 'lambda))
2439 ;; see ad-make-advice for the format of advice definitions:
2440 (defmacro ad-advice-p (definition)
2441 ;;"non-nil if DEFINITION is a piece of advice."
2442 `(eq (car-safe ,definition) 'advice))
2444 ;; Emacs/Lemacs cross-compatibility
2445 ;; (compiled-function-p is an obsolete function in Emacs):
2446 (if (and (not (fboundp 'byte-code-function-p))
2447 (fboundp 'compiled-function-p))
2448 (ad-safe-fset 'byte-code-function-p 'compiled-function-p))
2450 (defmacro ad-compiled-p (definition)
2451 "Return non-nil if DEFINITION is a compiled byte-code object."
2452 `(or (byte-code-function-p ,definition)
2453 (and (ad-macro-p ,definition)
2454 (byte-code-function-p (ad-lambdafy ,definition)))))
2456 (defmacro ad-compiled-code (compiled-definition)
2457 "Return the byte-code object of a COMPILED-DEFINITION."
2458 `(if (ad-macro-p ,compiled-definition)
2459 (ad-lambdafy ,compiled-definition)
2460 ,compiled-definition))
2462 (defun ad-lambda-expression (definition)
2463 "Return the lambda expression of a function/macro/advice DEFINITION."
2464 (cond ((ad-lambda-p definition)
2465 definition)
2466 ((ad-macro-p definition)
2467 (ad-lambdafy definition))
2468 ((ad-advice-p definition)
2469 (cdr definition))
2470 (t nil)))
2472 (defun ad-arglist (definition &optional name)
2473 "Return the argument list of DEFINITION.
2474 If DEFINITION could be from a subr then its NAME should be
2475 supplied to make subr arglist lookup more efficient."
2476 (require 'help-fns)
2477 (help-function-arglist
2478 (if (or (ad-macro-p definition) (ad-advice-p definition))
2479 (cdr definition)
2480 definition)
2481 'preserve-names))
2483 (defun ad-docstring (definition)
2484 "Return the unexpanded docstring of DEFINITION."
2485 (let ((docstring
2486 (if (ad-compiled-p definition)
2487 (ad-real-documentation definition t)
2488 (car (cdr (cdr (ad-lambda-expression definition)))))))
2489 (if (or (stringp docstring)
2490 (natnump docstring))
2491 docstring)))
2493 (defun ad-interactive-form (definition)
2494 "Return the interactive form of DEFINITION.
2495 Like `interactive-form', but also works on pieces of advice."
2496 (interactive-form
2497 (if (ad-advice-p definition)
2498 (ad-lambda-expression definition)
2499 definition)))
2501 (defun ad-body-forms (definition)
2502 "Return the list of body forms of DEFINITION."
2503 (cond ((ad-compiled-p definition)
2504 nil)
2505 ((consp definition)
2506 (nthcdr (+ (if (ad-docstring definition) 1 0)
2507 (if (ad-interactive-form definition) 1 0))
2508 (cdr (cdr (ad-lambda-expression definition)))))))
2510 (defun ad-make-advised-definition-docstring (function)
2511 "Make an identifying docstring for the advised definition of FUNCTION.
2512 Put function name into the documentation string so we can infer
2513 the name of the advised function from the docstring. This is needed
2514 to generate a proper advised docstring even if we are just given a
2515 definition (see the code for `documentation')."
2516 (propertize "Advice doc string" 'ad-advice-info function))
2518 (defun ad-advised-definition-p (definition)
2519 "Return non-nil if DEFINITION was generated from advice information."
2520 (if (or (ad-lambda-p definition)
2521 (ad-macro-p definition)
2522 (ad-compiled-p definition))
2523 (let ((docstring (ad-docstring definition)))
2524 (and (stringp docstring)
2525 (get-text-property 0 'ad-advice-info docstring)))))
2527 (defun ad-definition-type (definition)
2528 "Return symbol that describes the type of DEFINITION."
2529 (cond
2530 ((ad-macro-p definition) 'macro)
2531 ((ad-subr-p definition)
2532 (if (ad-special-form-p definition)
2533 'special-form
2534 'subr))
2535 ((or (ad-lambda-p definition)
2536 (ad-compiled-p definition))
2537 'function)
2538 ((ad-advice-p definition) 'advice)))
2540 (defun ad-has-proper-definition (function)
2541 "True if FUNCTION is a symbol with a proper definition.
2542 For that it has to be fbound with a non-autoload definition."
2543 (and (symbolp function)
2544 (fboundp function)
2545 (not (autoloadp (symbol-function function)))))
2547 ;; The following two are necessary for the sake of packages such as
2548 ;; ange-ftp which redefine functions via fcell indirection:
2549 (defun ad-real-definition (function)
2550 "Find FUNCTION's definition at the end of function cell indirection."
2551 (if (ad-has-proper-definition function)
2552 (let ((definition (symbol-function function)))
2553 (if (symbolp definition)
2554 (ad-real-definition definition)
2555 definition))))
2557 (defun ad-real-orig-definition (function)
2558 "Find FUNCTION's real original definition starting from its `origname'."
2559 (if (ad-is-advised function)
2560 (ad-real-definition (ad-get-advice-info-field function 'origname))))
2562 (defun ad-is-compilable (function)
2563 "True if FUNCTION has an interpreted definition that can be compiled."
2564 (and (ad-has-proper-definition function)
2565 (or (ad-lambda-p (symbol-function function))
2566 (ad-macro-p (symbol-function function)))
2567 (not (ad-compiled-p (symbol-function function)))))
2569 (defun ad-compile-function (function)
2570 "Byte-compiles FUNCTION (or macro) if it is not yet compiled."
2571 (interactive "aByte-compile function: ")
2572 (if (ad-is-compilable function)
2573 ;; Need to turn off auto-activation
2574 ;; because `byte-compile' uses `fset':
2575 (ad-with-auto-activation-disabled
2576 (require 'bytecomp)
2577 (require 'warnings) ;To define warning-suppress-types
2578 ;before we let-bind it.
2579 (let ((symbol (make-symbol "advice-compilation"))
2580 (byte-compile-warnings byte-compile-warnings)
2581 ;; Don't pop up windows showing byte-compiler warnings.
2582 (warning-suppress-types '((bytecomp))))
2583 (if (featurep 'cl)
2584 (byte-compile-disable-warning 'cl-functions))
2585 (fset symbol (symbol-function function))
2586 (byte-compile symbol)
2587 (fset function (symbol-function symbol))))))
2589 (defun ad-prognify (forms)
2590 (cond ((<= (length forms) 1)
2591 (car forms))
2592 (t (cons 'progn forms))))
2594 ;; @@@ Accessing argument lists:
2595 ;; =============================
2597 (defun ad-parse-arglist (arglist)
2598 "Parse ARGLIST into its required, optional and rest parameters.
2599 A three-element list is returned, where the 1st element is the list of
2600 required arguments, the 2nd is the list of optional arguments, and the 3rd
2601 is the name of an optional rest parameter (or nil)."
2602 (let (required optional rest)
2603 (setq rest (car (cdr (memq '&rest arglist))))
2604 (if rest (setq arglist (reverse (cdr (memq '&rest (reverse arglist))))))
2605 (setq optional (cdr (memq '&optional arglist)))
2606 (if optional
2607 (setq required (reverse (cdr (memq '&optional (reverse arglist)))))
2608 (setq required arglist))
2609 (list required optional rest)))
2611 (defun ad-retrieve-args-form (arglist)
2612 "Generate a form which evaluates into names/values/types of ARGLIST.
2613 When the form gets evaluated within a function with that argument list
2614 it will result in a list with one entry for each argument, where the
2615 first element of each entry is the name of the argument, the second
2616 element is its actual current value, and the third element is either
2617 `required', `optional' or `rest' depending on the type of the argument."
2618 (let* ((parsed-arglist (ad-parse-arglist arglist))
2619 (rest (nth 2 parsed-arglist)))
2620 `(list
2621 ,@(mapcar (function
2622 (lambda (req)
2623 `(list ',req ,req 'required)))
2624 (nth 0 parsed-arglist))
2625 ,@(mapcar (function
2626 (lambda (opt)
2627 `(list ',opt ,opt 'optional)))
2628 (nth 1 parsed-arglist))
2629 ,@(if rest (list `(list ',rest ,rest 'rest))))))
2631 (defun ad-arg-binding-field (binding field)
2632 (cond ((eq field 'name) (car binding))
2633 ((eq field 'value) (car (cdr binding)))
2634 ((eq field 'type) (car (cdr (cdr binding))))))
2636 (defun ad-list-access (position list)
2637 (cond ((= position 0) list)
2638 ((= position 1) (list 'cdr list))
2639 (t (list 'nthcdr position list))))
2641 (defun ad-element-access (position list)
2642 (cond ((= position 0) (list 'car list))
2643 ((= position 1) `(car (cdr ,list)))
2644 (t (list 'nth position list))))
2646 (defun ad-access-argument (arglist index)
2647 "Tell how to access ARGLIST's actual argument at position INDEX.
2648 For a required/optional arg it simply returns it, if a rest argument has
2649 to be accessed, it returns a list with the index and name."
2650 (let* ((parsed-arglist (ad-parse-arglist arglist))
2651 (reqopt-args (append (nth 0 parsed-arglist)
2652 (nth 1 parsed-arglist)))
2653 (rest-arg (nth 2 parsed-arglist)))
2654 (cond ((< index (length reqopt-args))
2655 (nth index reqopt-args))
2656 (rest-arg
2657 (list (- index (length reqopt-args)) rest-arg)))))
2659 (defun ad-get-argument (arglist index)
2660 "Return form to access ARGLIST's actual argument at position INDEX.
2661 INDEX counts from zero."
2662 (let ((argument-access (ad-access-argument arglist index)))
2663 (cond ((consp argument-access)
2664 (ad-element-access
2665 (car argument-access) (car (cdr argument-access))))
2666 (argument-access))))
2668 (defun ad-set-argument (arglist index value-form)
2669 "Return form to set ARGLIST's actual arg at INDEX to VALUE-FORM.
2670 INDEX counts from zero."
2671 (let ((argument-access (ad-access-argument arglist index)))
2672 (cond ((consp argument-access)
2673 ;; should this check whether there actually is something to set?
2674 `(setcar ,(ad-list-access
2675 (car argument-access) (car (cdr argument-access)))
2676 ,value-form))
2677 (argument-access
2678 `(setq ,argument-access ,value-form))
2679 (t (error "ad-set-argument: No argument at position %d of `%s'"
2680 index arglist)))))
2682 (defun ad-get-arguments (arglist index)
2683 "Return form to access all actual arguments starting at position INDEX."
2684 (let* ((parsed-arglist (ad-parse-arglist arglist))
2685 (reqopt-args (append (nth 0 parsed-arglist)
2686 (nth 1 parsed-arglist)))
2687 (rest-arg (nth 2 parsed-arglist))
2688 args-form)
2689 (if (< index (length reqopt-args))
2690 (setq args-form `(list ,@(nthcdr index reqopt-args))))
2691 (if rest-arg
2692 (if args-form
2693 (setq args-form `(nconc ,args-form ,rest-arg))
2694 (setq args-form (ad-list-access (- index (length reqopt-args))
2695 rest-arg))))
2696 args-form))
2698 (defun ad-set-arguments (arglist index values-form)
2699 "Make form to assign elements of VALUES-FORM as actual ARGLIST args.
2700 The assignment starts at position INDEX."
2701 (let ((values-index 0)
2702 argument-access set-forms)
2703 (while (setq argument-access (ad-access-argument arglist index))
2704 (if (symbolp argument-access)
2705 (setq set-forms
2706 (cons (ad-set-argument
2707 arglist index
2708 (ad-element-access values-index 'ad-vAlUeS))
2709 set-forms))
2710 (setq set-forms
2711 (cons (if (= (car argument-access) 0)
2712 (list 'setq
2713 (car (cdr argument-access))
2714 (ad-list-access values-index 'ad-vAlUeS))
2715 (list 'setcdr
2716 (ad-list-access (1- (car argument-access))
2717 (car (cdr argument-access)))
2718 (ad-list-access values-index 'ad-vAlUeS)))
2719 set-forms))
2720 ;; terminate loop
2721 (setq arglist nil))
2722 (setq index (1+ index))
2723 (setq values-index (1+ values-index)))
2724 (if (null set-forms)
2725 (error "ad-set-arguments: No argument at position %d of `%s'"
2726 index arglist)
2727 (if (= (length set-forms) 1)
2728 ;; For exactly one set-form we can use values-form directly,...
2729 (ad-substitute-tree
2730 (function (lambda (form) (eq form 'ad-vAlUeS)))
2731 (function (lambda (form) values-form))
2732 (car set-forms))
2733 ;; ...if we have more we have to bind it to a variable:
2734 `(let ((ad-vAlUeS ,values-form))
2735 ,@(reverse set-forms)
2736 ;; work around the old backquote bug:
2737 ,'ad-vAlUeS)))))
2739 (defun ad-insert-argument-access-forms (definition arglist)
2740 "Expands arg-access text macros in DEFINITION according to ARGLIST."
2741 (ad-substitute-tree
2742 (function
2743 (lambda (form)
2744 (or (eq form 'ad-arg-bindings)
2745 (and (memq (car-safe form)
2746 '(ad-get-arg ad-get-args ad-set-arg ad-set-args))
2747 (integerp (car-safe (cdr form)))))))
2748 (function
2749 (lambda (form)
2750 (if (eq form 'ad-arg-bindings)
2751 (ad-retrieve-args-form arglist)
2752 (let ((accessor (car form))
2753 (index (car (cdr form)))
2754 (val (car (cdr (ad-insert-argument-access-forms
2755 (cdr form) arglist)))))
2756 (cond ((eq accessor 'ad-get-arg)
2757 (ad-get-argument arglist index))
2758 ((eq accessor 'ad-set-arg)
2759 (ad-set-argument arglist index val))
2760 ((eq accessor 'ad-get-args)
2761 (ad-get-arguments arglist index))
2762 ((eq accessor 'ad-set-args)
2763 (ad-set-arguments arglist index val)))))))
2764 definition))
2766 ;; @@@ Mapping argument lists:
2767 ;; ===========================
2768 ;; Here is the problem:
2769 ;; Suppose function foo was called with (foo 1 2 3 4 5), and foo has the
2770 ;; argument list (x y &rest z), and we want to call the function bar which
2771 ;; has argument list (a &rest b) with a combination of x, y and z so that
2772 ;; the effect is just as if we had called (bar 1 2 3 4 5) directly.
2773 ;; The mapping should work for any two argument lists.
2775 (defun ad-map-arglists (source-arglist target-arglist)
2776 "Make `funcall/apply' form to map SOURCE-ARGLIST to TARGET-ARGLIST.
2777 The arguments supplied to TARGET-ARGLIST will be taken from SOURCE-ARGLIST just
2778 as if they had been supplied to a function with TARGET-ARGLIST directly.
2779 Excess source arguments will be neglected, missing source arguments will be
2780 supplied as nil. Returns a `funcall' or `apply' form with the second element
2781 being `function' which has to be replaced by an actual function argument.
2782 Example: `(ad-map-arglists '(a &rest args) '(w x y z))' will return
2783 `(funcall function a (car args) (car (cdr args)) (nth 2 args))'."
2784 (let* ((parsed-source-arglist (ad-parse-arglist source-arglist))
2785 (source-reqopt-args (append (nth 0 parsed-source-arglist)
2786 (nth 1 parsed-source-arglist)))
2787 (source-rest-arg (nth 2 parsed-source-arglist))
2788 (parsed-target-arglist (ad-parse-arglist target-arglist))
2789 (target-reqopt-args (append (nth 0 parsed-target-arglist)
2790 (nth 1 parsed-target-arglist)))
2791 (target-rest-arg (nth 2 parsed-target-arglist))
2792 (need-apply (and source-rest-arg target-rest-arg))
2793 (target-arg-index -1))
2794 ;; This produces ``error-proof'' target function calls with the exception
2795 ;; of a case like (&rest a) mapped onto (x &rest y) where the actual args
2796 ;; supplied to A might not be enough to supply the required target arg X
2797 (append (list (if need-apply 'apply 'funcall) 'function)
2798 (cond (need-apply
2799 ;; `apply' can take care of that directly:
2800 (append source-reqopt-args (list source-rest-arg)))
2801 (t (mapcar (function
2802 (lambda (arg)
2803 (setq target-arg-index (1+ target-arg-index))
2804 (ad-get-argument
2805 source-arglist target-arg-index)))
2806 (append target-reqopt-args
2807 (and target-rest-arg
2808 ;; If we have a rest arg gobble up
2809 ;; remaining source args:
2810 (nthcdr (length target-reqopt-args)
2811 source-reqopt-args)))))))))
2813 (defun ad-make-mapped-call (source-arglist target-arglist target-function)
2814 "Make form to call TARGET-FUNCTION with args from SOURCE-ARGLIST."
2815 (let ((mapped-form (ad-map-arglists source-arglist target-arglist)))
2816 (if (eq (car mapped-form) 'funcall)
2817 (cons target-function (cdr (cdr mapped-form)))
2818 (prog1 mapped-form
2819 (setcar (cdr mapped-form) (list 'quote target-function))))))
2821 ;; @@@ Making an advised documentation string:
2822 ;; ===========================================
2823 ;; New policy: The documentation string for an advised function will be built
2824 ;; at the time the advised `documentation' function is called. This has the
2825 ;; following advantages:
2826 ;; 1) command-key substitutions will automatically be correct
2827 ;; 2) No wasted string space due to big advised docstrings in caches or
2828 ;; compiled files that contain preactivations
2829 ;; The overall overhead for this should be negligible because people normally
2830 ;; don't lookup documentation for the same function over and over again.
2832 (defun ad-make-single-advice-docstring (advice class &optional style)
2833 (let ((advice-docstring (ad-docstring (ad-advice-definition advice))))
2834 (cond ((eq style 'plain)
2835 advice-docstring)
2836 ((eq style 'freeze)
2837 (format "Permanent %s-advice `%s':%s%s"
2838 class (ad-advice-name advice)
2839 (if advice-docstring "\n" "")
2840 (or advice-docstring "")))
2841 (t (if advice-docstring
2842 (format "%s-advice `%s':\n%s"
2843 (capitalize (symbol-name class))
2844 (ad-advice-name advice)
2845 advice-docstring)
2846 (format "%s-advice `%s'."
2847 (capitalize (symbol-name class))
2848 (ad-advice-name advice)))))))
2850 (require 'help-fns) ;For help-split-fundoc and help-add-fundoc-usage.
2852 (defun ad-make-advised-docstring (function &optional style)
2853 "Construct a documentation string for the advised FUNCTION.
2854 It concatenates the original documentation with the documentation
2855 strings of the individual pieces of advice which will be formatted
2856 according to STYLE. STYLE can be `plain' or `freeze', everything else
2857 will be interpreted as `default'. The order of the advice documentation
2858 strings corresponds to before/around/after and the individual ordering
2859 in any of these classes."
2860 (let* ((origdef (ad-real-orig-definition function))
2861 (origtype (symbol-name (ad-definition-type origdef)))
2862 (origdoc
2863 ;; Retrieve raw doc, key substitution will be taken care of later:
2864 (ad-real-documentation origdef t))
2865 (usage (help-split-fundoc origdoc function))
2866 paragraphs advice-docstring ad-usage)
2867 (setq usage (if (null usage) t (setq origdoc (cdr usage)) (car usage)))
2868 (if origdoc (setq paragraphs (list origdoc)))
2869 (unless (eq style 'plain)
2870 (push (concat "This " origtype " is advised.") paragraphs))
2871 (ad-dolist (class ad-advice-classes)
2872 (ad-dolist (advice (ad-get-enabled-advices function class))
2873 (setq advice-docstring
2874 (ad-make-single-advice-docstring advice class style))
2875 (if advice-docstring
2876 (push advice-docstring paragraphs))))
2877 (setq origdoc (if paragraphs
2878 (propertize
2879 ;; separate paragraphs with blank lines:
2880 (mapconcat 'identity (nreverse paragraphs) "\n\n")
2881 'ad-advice-info function)))
2882 (help-add-fundoc-usage origdoc usage)))
2884 (defun ad-make-plain-docstring (function)
2885 (ad-make-advised-docstring function 'plain))
2886 (defun ad-make-freeze-docstring (function)
2887 (ad-make-advised-docstring function 'freeze))
2889 ;; @@@ Accessing overriding arglists and interactive forms:
2890 ;; ========================================================
2892 (defun ad-advised-arglist (function)
2893 "Find first defined arglist in FUNCTION's redefining advices."
2894 (ad-dolist (advice (append (ad-get-enabled-advices function 'before)
2895 (ad-get-enabled-advices function 'around)
2896 (ad-get-enabled-advices function 'after)))
2897 (let ((arglist (ad-arglist (ad-advice-definition advice))))
2898 (if arglist
2899 ;; We found the first one, use it:
2900 (ad-do-return arglist)))))
2902 (defun ad-advised-interactive-form (function)
2903 "Find first interactive form in FUNCTION's redefining advices."
2904 (ad-dolist (advice (append (ad-get-enabled-advices function 'before)
2905 (ad-get-enabled-advices function 'around)
2906 (ad-get-enabled-advices function 'after)))
2907 (let ((interactive-form
2908 (ad-interactive-form (ad-advice-definition advice))))
2909 (if interactive-form
2910 ;; We found the first one, use it:
2911 (ad-do-return interactive-form)))))
2913 ;; @@@ Putting it all together:
2914 ;; ============================
2916 (defun ad-make-advised-definition (function)
2917 "Generate an advised definition of FUNCTION from its advice info."
2918 (if (and (ad-is-advised function)
2919 (ad-has-redefining-advice function))
2920 (let* ((origdef (ad-real-orig-definition function))
2921 (origname (ad-get-advice-info-field function 'origname))
2922 (orig-interactive-p (commandp origdef))
2923 (orig-subr-p (ad-subr-p origdef))
2924 (orig-special-form-p (ad-special-form-p origdef))
2925 (orig-macro-p (ad-macro-p origdef))
2926 ;; Construct the individual pieces that we need for assembly:
2927 (orig-arglist (ad-arglist origdef function))
2928 (advised-arglist (or (ad-advised-arglist function)
2929 orig-arglist))
2930 (advised-interactive-form (ad-advised-interactive-form function))
2931 (interactive-form
2932 (cond (orig-macro-p nil)
2933 (advised-interactive-form)
2934 ((interactive-form origdef)
2935 (interactive-form
2936 (if (and (symbolp function) (get function 'elp-info))
2937 (aref (get function 'elp-info) 2)
2938 origdef)))))
2939 (orig-form
2940 (cond ((or orig-special-form-p orig-macro-p)
2941 ;; Special forms and macros will be advised into macros.
2942 ;; The trick is to construct an expansion for the advised
2943 ;; macro that does the correct thing when it gets eval'ed.
2944 ;; For macros we'll just use the expansion of the original
2945 ;; macro and return that. This way compiled advised macros
2946 ;; will be expanded into something useful. Note that after
2947 ;; advices have full control over whether they want to
2948 ;; evaluate the expansion (the value of `ad-return-value')
2949 ;; at macro expansion time or not. For special forms there
2950 ;; is no solution that interacts reasonably with the
2951 ;; compiler, hence we just evaluate the original at macro
2952 ;; expansion time and return the result. The moral of that
2953 ;; is that one should always deactivate advised special
2954 ;; forms before one byte-compiles a file.
2955 `(,(if orig-macro-p 'macroexpand 'eval)
2956 (cons ',origname
2957 ,(ad-get-arguments advised-arglist 0))))
2958 ((and orig-subr-p
2959 orig-interactive-p
2960 (not interactive-form)
2961 (not advised-interactive-form))
2962 ;; Check whether we were called interactively
2963 ;; in order to do proper prompting:
2964 `(if (called-interactively-p 'any)
2965 (call-interactively ',origname)
2966 ,(ad-make-mapped-call advised-arglist
2967 orig-arglist
2968 origname)))
2969 ;; And now for normal functions and non-interactive subrs
2970 ;; (or subrs whose interactive behavior was advised):
2971 (t (ad-make-mapped-call
2972 advised-arglist orig-arglist origname)))))
2974 ;; Finally, build the sucker:
2975 (ad-assemble-advised-definition
2976 (cond (orig-macro-p 'macro)
2977 (orig-special-form-p 'special-form)
2978 (t 'function))
2979 advised-arglist
2980 (ad-make-advised-definition-docstring function)
2981 interactive-form
2982 orig-form
2983 (ad-get-enabled-advices function 'before)
2984 (ad-get-enabled-advices function 'around)
2985 (ad-get-enabled-advices function 'after)))))
2987 (defun ad-assemble-advised-definition
2988 (type args docstring interactive orig &optional befores arounds afters)
2990 "Assembles an original and its advices into an advised function.
2991 It constructs a function or macro definition according to TYPE which has to
2992 be either `macro', `function' or `special-form'. ARGS is the argument list
2993 that has to be used, DOCSTRING if non-nil defines the documentation of the
2994 definition, INTERACTIVE if non-nil is the interactive form to be used,
2995 ORIG is a form that calls the body of the original unadvised function,
2996 and BEFORES, AROUNDS and AFTERS are the lists of advices with which ORIG
2997 should be modified. The assembled function will be returned."
2999 (let (before-forms around-form around-form-protected after-forms definition)
3000 (ad-dolist (advice befores)
3001 (cond ((and (ad-advice-protected advice)
3002 before-forms)
3003 (setq before-forms
3004 `((unwind-protect
3005 ,(ad-prognify before-forms)
3006 ,@(ad-body-forms
3007 (ad-advice-definition advice))))))
3008 (t (setq before-forms
3009 (append before-forms
3010 (ad-body-forms (ad-advice-definition advice)))))))
3012 (setq around-form `(setq ad-return-value ,orig))
3013 (ad-dolist (advice (reverse arounds))
3014 ;; If any of the around advices is protected then we
3015 ;; protect the complete around advice onion:
3016 (if (ad-advice-protected advice)
3017 (setq around-form-protected t))
3018 (setq around-form
3019 (ad-substitute-tree
3020 (function (lambda (form) (eq form 'ad-do-it)))
3021 (function (lambda (form) around-form))
3022 (ad-prognify (ad-body-forms (ad-advice-definition advice))))))
3024 (setq after-forms
3025 (if (and around-form-protected before-forms)
3026 `((unwind-protect
3027 ,(ad-prognify before-forms)
3028 ,around-form))
3029 (append before-forms (list around-form))))
3030 (ad-dolist (advice afters)
3031 (cond ((and (ad-advice-protected advice)
3032 after-forms)
3033 (setq after-forms
3034 `((unwind-protect
3035 ,(ad-prognify after-forms)
3036 ,@(ad-body-forms
3037 (ad-advice-definition advice))))))
3038 (t (setq after-forms
3039 (append after-forms
3040 (ad-body-forms (ad-advice-definition advice)))))))
3042 (setq definition
3043 `(,@(if (memq type '(macro special-form)) '(macro))
3044 lambda
3045 ,args
3046 ,@(if docstring (list docstring))
3047 ,@(if interactive (list interactive))
3048 (let (ad-return-value)
3049 ,@after-forms
3050 ,(if (eq type 'special-form)
3051 '(list 'quote ad-return-value)
3052 'ad-return-value))))
3054 (ad-insert-argument-access-forms definition args)))
3056 ;; This is needed for activation/deactivation hooks:
3057 (defun ad-make-hook-form (function hook-name)
3058 "Make hook-form from FUNCTION's advice bodies in class HOOK-NAME."
3059 (let ((hook-forms
3060 (mapcar (function (lambda (advice)
3061 (ad-body-forms (ad-advice-definition advice))))
3062 (ad-get-enabled-advices function hook-name))))
3063 (if hook-forms
3064 (ad-prognify (apply 'append hook-forms)))))
3067 ;; @@ Caching:
3068 ;; ===========
3069 ;; Generating an advised definition of a function is moderately expensive,
3070 ;; hence, it makes sense to cache it so we can reuse it in appropriate
3071 ;; circumstances. Of course, it only makes sense to reuse a cached
3072 ;; definition if the current advice and function definition state is the
3073 ;; same as it was at the time when the cached definition was generated.
3074 ;; For that purpose we associate every cache with an id so we can verify
3075 ;; if it is still valid at a certain point in time. This id mechanism
3076 ;; makes it possible to preactivate advised functions, write the compiled
3077 ;; advised definitions to a file and reuse them during the actual
3078 ;; activation without having to risk that the resulting definition will be
3079 ;; incorrect, well, almost.
3081 ;; A cache id is a list with six elements:
3082 ;; 1) the list of names of enabled before advices
3083 ;; 2) the list of names of enabled around advices
3084 ;; 3) the list of names of enabled after advices
3085 ;; 4) the type of the original function (macro, subr, etc.)
3086 ;; 5) the arglist of the original definition (or t if it was equal to the
3087 ;; arglist of the cached definition)
3088 ;; 6) t if the interactive form of the original definition was equal to the
3089 ;; interactive form of the cached definition
3091 ;; Here's how a cache can get invalidated or be incorrect:
3092 ;; A) a piece of advice used in the cache gets redefined
3093 ;; B) the current list of enabled advices is different from the ones used
3094 ;; for the cache
3095 ;; C) the type of the original function changed, e.g., a function became a
3096 ;; macro, or a subr became a function
3097 ;; D) the arglist of the original function changed
3098 ;; E) the interactive form of the original function changed
3099 ;; F) a piece of advice used in the cache got redefined before the
3100 ;; defadvice with the cached definition got loaded: This is a PROBLEM!
3102 ;; Cases A and B are the normal ones. A is taken care of by `ad-add-advice'
3103 ;; which clears the cache in such a case, B is easily checked during
3104 ;; verification at activation time.
3106 ;; Cases C, D and E have to be considered if one is slightly paranoid, i.e.,
3107 ;; if one considers the case that the original function could be different
3108 ;; from the one available at caching time (e.g., for forward advice of
3109 ;; functions that get redefined by some packages - such as `eval-region' gets
3110 ;; redefined by edebug). All these cases can be easily checked during
3111 ;; verification. Element 4 of the id lets one check case C, element 5 takes
3112 ;; care of case D (using t in the equality case saves some space, because the
3113 ;; arglist can be recovered at validation time from the cached definition),
3114 ;; and element 6 takes care of case E which is only a problem if the original
3115 ;; was actually a function whose interactive form was not overridden by a
3116 ;; piece of advice.
3118 ;; Case F is the only one which will lead to an incorrect advised function.
3119 ;; There is no way to avoid this without storing the complete advice definition
3120 ;; in the cache-id which is not feasible.
3122 ;; The cache-id of a typical advised function with one piece of advice and
3123 ;; no arglist redefinition takes 7 conses which is a small price to pay for
3124 ;; the added efficiency. The validation itself is also pretty cheap, certainly
3125 ;; a lot cheaper than reconstructing an advised definition.
3127 (defmacro ad-get-cache-definition (function)
3128 `(car (ad-get-advice-info-field ,function 'cache)))
3130 (defmacro ad-get-cache-id (function)
3131 `(cdr (ad-get-advice-info-field ,function 'cache)))
3133 (defmacro ad-set-cache (function definition id)
3134 `(ad-set-advice-info-field
3135 ,function 'cache (cons ,definition ,id)))
3137 (defun ad-clear-cache (function)
3138 "Clears a previously cached advised definition of FUNCTION.
3139 Clear the cache if you want to force `ad-activate' to construct a new
3140 advised definition from scratch."
3141 (interactive
3142 (list (ad-read-advised-function "Clear cached definition of")))
3143 (ad-set-advice-info-field function 'cache nil))
3145 (defun ad-make-cache-id (function)
3146 "Generate an identifying image of the current advices of FUNCTION."
3147 (let ((original-definition (ad-real-orig-definition function))
3148 (cached-definition (ad-get-cache-definition function)))
3149 (list (mapcar (function (lambda (advice) (ad-advice-name advice)))
3150 (ad-get-enabled-advices function 'before))
3151 (mapcar (function (lambda (advice) (ad-advice-name advice)))
3152 (ad-get-enabled-advices function 'around))
3153 (mapcar (function (lambda (advice) (ad-advice-name advice)))
3154 (ad-get-enabled-advices function 'after))
3155 (ad-definition-type original-definition)
3156 (if (equal (ad-arglist original-definition function)
3157 (ad-arglist cached-definition))
3159 (ad-arglist original-definition function))
3160 (if (eq (ad-definition-type original-definition) 'function)
3161 (equal (interactive-form original-definition)
3162 (interactive-form cached-definition))))))
3164 (defun ad-get-cache-class-id (function class)
3165 "Return the part of FUNCTION's cache id that identifies CLASS."
3166 (let ((cache-id (ad-get-cache-id function)))
3167 (if (eq class 'before)
3168 (car cache-id)
3169 (if (eq class 'around)
3170 (nth 1 cache-id)
3171 (nth 2 cache-id)))))
3173 (defun ad-verify-cache-class-id (cache-class-id advices)
3174 (ad-dolist (advice advices (null cache-class-id))
3175 (if (ad-advice-enabled advice)
3176 (if (eq (car cache-class-id) (ad-advice-name advice))
3177 (setq cache-class-id (cdr cache-class-id))
3178 (ad-do-return nil)))))
3180 ;; There should be a way to monitor if and why a cache verification failed
3181 ;; in order to determine whether a certain preactivation could be used or
3182 ;; not. Right now the only way to find out is to trace
3183 ;; `ad-cache-id-verification-code'. The code it returns indicates where the
3184 ;; verification failed. Tracing `ad-verify-cache-class-id' might provide
3185 ;; some additional useful information.
3187 (defun ad-cache-id-verification-code (function)
3188 (let ((cache-id (ad-get-cache-id function))
3189 (code 'before-advice-mismatch))
3190 (and (ad-verify-cache-class-id
3191 (car cache-id) (ad-get-advice-info-field function 'before))
3192 (setq code 'around-advice-mismatch)
3193 (ad-verify-cache-class-id
3194 (nth 1 cache-id) (ad-get-advice-info-field function 'around))
3195 (setq code 'after-advice-mismatch)
3196 (ad-verify-cache-class-id
3197 (nth 2 cache-id) (ad-get-advice-info-field function 'after))
3198 (setq code 'definition-type-mismatch)
3199 (let ((original-definition (ad-real-orig-definition function))
3200 (cached-definition (ad-get-cache-definition function)))
3201 (and (eq (nth 3 cache-id) (ad-definition-type original-definition))
3202 (setq code 'arglist-mismatch)
3203 (equal (if (eq (nth 4 cache-id) t)
3204 (ad-arglist original-definition function)
3205 (nth 4 cache-id) )
3206 (ad-arglist cached-definition))
3207 (setq code 'interactive-form-mismatch)
3208 (or (null (nth 5 cache-id))
3209 (equal (interactive-form original-definition)
3210 (interactive-form cached-definition)))
3211 (setq code 'verified))))
3212 code))
3214 (defun ad-verify-cache-id (function)
3215 "True if FUNCTION's cache-id is compatible with its current advices."
3216 (eq (ad-cache-id-verification-code function) 'verified))
3219 ;; @@ Preactivation:
3220 ;; =================
3221 ;; Preactivation can be used to generate compiled advised definitions
3222 ;; at compile time without having to give up the dynamic runtime flexibility
3223 ;; of the advice mechanism. Preactivation is a special feature of `defadvice',
3224 ;; it involves the following steps:
3225 ;; - remembering the function's current state (definition and advice-info)
3226 ;; - advising it with the defined piece of advice
3227 ;; - clearing its cache
3228 ;; - generating an interpreted advised definition by activating it, this will
3229 ;; make use of all its current active advice and its current definition
3230 ;; - saving the so generated cached definition and id
3231 ;; - resetting the function's advice and definition state to what it was
3232 ;; before the preactivation
3233 ;; - Returning the saved definition and its id to be used in the expansion of
3234 ;; `defadvice' to assign it as an initial cache, hence it will be compiled
3235 ;; at time the `defadvice' gets compiled.
3236 ;; Naturally, for preactivation to be effective it has to be applied/compiled
3237 ;; at the right time, i.e., when the current state of advices and function
3238 ;; definition exactly reflects the state at activation time. Should that not
3239 ;; be the case, the precompiled definition will just be discarded and a new
3240 ;; advised definition will be generated.
3242 (defun ad-preactivate-advice (function advice class position)
3243 "Preactivate FUNCTION and returns the constructed cache."
3244 (let* ((function-defined-p (fboundp function))
3245 (old-definition
3246 (if function-defined-p
3247 (symbol-function function)))
3248 (old-advice-info (ad-copy-advice-info function))
3249 (ad-advised-functions ad-advised-functions))
3250 (unwind-protect
3251 (progn
3252 (ad-add-advice function advice class position)
3253 (ad-enable-advice function class (ad-advice-name advice))
3254 (ad-clear-cache function)
3255 (ad-activate function -1)
3256 (if (and (ad-is-active function)
3257 (ad-get-cache-definition function))
3258 (list (ad-get-cache-definition function)
3259 (ad-get-cache-id function))))
3260 (ad-set-advice-info function old-advice-info)
3261 ;; Don't `fset' function to nil if it was previously unbound:
3262 (if function-defined-p
3263 (ad-safe-fset function old-definition)
3264 (fmakunbound function)))))
3267 ;; @@ Freezing:
3268 ;; ============
3269 ;; Freezing transforms a `defadvice' into a redefining `defun/defmacro'
3270 ;; for the advised function without keeping any advice information. This
3271 ;; feature was jwz's idea: It generates a dumpable function definition
3272 ;; whose documentation can be written to the DOC file, and the generated
3273 ;; code does not need any Advice runtime support. Of course, frozen advices
3274 ;; cannot be undone.
3276 ;; Freezing only considers the advice of the particular `defadvice', other
3277 ;; already existing advices for the same function will be ignored. To ensure
3278 ;; proper interaction when an already advised function gets redefined with
3279 ;; a frozen advice, frozen advices always use the actual original definition
3280 ;; of the function, i.e., they are always at the core of the onion. E.g., if
3281 ;; an already advised function gets redefined with a frozen advice and then
3282 ;; unadvised, the frozen advice remains as the new definition of the function.
3284 ;; While multiple freeze advices for a single function or freeze-advising
3285 ;; of an already advised function are possible, they are better avoided,
3286 ;; because definition/compile/load ordering is relevant, and it becomes
3287 ;; incomprehensible pretty quickly.
3289 (defun ad-make-freeze-definition (function advice class position)
3290 (if (not (ad-has-proper-definition function))
3291 (error
3292 "ad-make-freeze-definition: `%s' is not yet defined"
3293 function))
3294 (let* ((name (ad-advice-name advice))
3295 ;; With a unique origname we can have multiple freeze advices
3296 ;; for the same function, each overloading the previous one:
3297 (unique-origname
3298 (intern (format "%s-%s-%s" (ad-make-origname function) class name)))
3299 (orig-definition
3300 ;; If FUNCTION is already advised, we'll use its current origdef
3301 ;; as the original definition of the frozen advice:
3302 (or (ad-get-orig-definition function)
3303 (symbol-function function)))
3304 (old-advice-info
3305 (if (ad-is-advised function)
3306 (ad-copy-advice-info function)))
3307 (real-docstring-fn
3308 (symbol-function 'ad-make-advised-definition-docstring))
3309 (real-origname-fn
3310 (symbol-function 'ad-make-origname))
3311 (frozen-definition
3312 (unwind-protect
3313 (progn
3314 ;; Make sure we construct a proper docstring:
3315 (ad-safe-fset 'ad-make-advised-definition-docstring
3316 'ad-make-freeze-docstring)
3317 ;; Make sure `unique-origname' is used as the origname:
3318 (ad-safe-fset 'ad-make-origname (lambda (x) unique-origname))
3319 ;; No we reset all current advice information to nil and
3320 ;; generate an advised definition that's solely determined
3321 ;; by ADVICE and the current origdef of FUNCTION:
3322 (ad-set-advice-info function nil)
3323 (ad-add-advice function advice class position)
3324 ;; The following will provide proper real docstrings as
3325 ;; well as a definition that will make the compiler happy:
3326 (ad-set-orig-definition function orig-definition)
3327 (ad-make-advised-definition function))
3328 ;; Restore the old advice state:
3329 (ad-set-advice-info function old-advice-info)
3330 ;; Restore functions:
3331 (ad-safe-fset
3332 'ad-make-advised-definition-docstring real-docstring-fn)
3333 (ad-safe-fset 'ad-make-origname real-origname-fn))))
3334 (if frozen-definition
3335 (let* ((macro-p (ad-macro-p frozen-definition))
3336 (body (cdr (if macro-p
3337 (ad-lambdafy frozen-definition)
3338 frozen-definition))))
3339 `(progn
3340 (if (not (fboundp ',unique-origname))
3341 (fset ',unique-origname
3342 ;; avoid infinite recursion in case the function
3343 ;; we want to freeze is already advised:
3344 (or (ad-get-orig-definition ',function)
3345 (symbol-function ',function))))
3346 (,(if macro-p 'defmacro 'defun)
3347 ,function
3348 ,@body))))))
3351 ;; @@ Activation and definition handling:
3352 ;; ======================================
3354 (defun ad-should-compile (function compile)
3355 "Return non-nil if the advised FUNCTION should be compiled.
3356 If COMPILE is non-nil and not a negative number then it returns t.
3357 If COMPILE is a negative number then it returns nil.
3358 If COMPILE is nil then the result depends on the value of
3359 `ad-default-compilation-action' (which see)."
3360 (if (integerp compile)
3361 (>= compile 0)
3362 (if compile
3363 compile
3364 (cond ((eq ad-default-compilation-action 'never)
3365 nil)
3366 ((eq ad-default-compilation-action 'always)
3368 ((eq ad-default-compilation-action 'like-original)
3369 (or (ad-subr-p (ad-get-orig-definition function))
3370 (ad-compiled-p (ad-get-orig-definition function))))
3371 ;; everything else means `maybe':
3372 (t (featurep 'byte-compile))))))
3374 (defun ad-activate-advised-definition (function compile)
3375 "Redefine FUNCTION with its advised definition from cache or scratch.
3376 The resulting FUNCTION will be compiled if `ad-should-compile' returns t.
3377 The current definition and its cache-id will be put into the cache."
3378 (let ((verified-cached-definition
3379 (if (ad-verify-cache-id function)
3380 (ad-get-cache-definition function))))
3381 (ad-safe-fset function
3382 (or verified-cached-definition
3383 (ad-make-advised-definition function)))
3384 (if (ad-should-compile function compile)
3385 (ad-compile-function function))
3386 (if verified-cached-definition
3387 (if (not (eq verified-cached-definition (symbol-function function)))
3388 ;; we must have compiled, cache the compiled definition:
3389 (ad-set-cache
3390 function (symbol-function function) (ad-get-cache-id function)))
3391 ;; We created a new advised definition, cache it with a proper id:
3392 (ad-clear-cache function)
3393 ;; ad-make-cache-id needs the new cached definition:
3394 (ad-set-cache function (symbol-function function) nil)
3395 (ad-set-cache
3396 function (symbol-function function) (ad-make-cache-id function)))))
3398 (defun ad-handle-definition (function)
3399 "Handle re/definition of an advised FUNCTION during de/activation.
3400 If FUNCTION does not have an original definition associated with it and
3401 the current definition is usable, then it will be stored as FUNCTION's
3402 original definition. If no current definition is available (even in the
3403 case of undefinition) nothing will be done. In the case of redefinition
3404 the action taken depends on the value of `ad-redefinition-action' (which
3405 see). Redefinition occurs when FUNCTION already has an original definition
3406 associated with it but got redefined with a new definition and then
3407 de/activated. If you do not like the current redefinition action change
3408 the value of `ad-redefinition-action' and de/activate again."
3409 (let ((original-definition (ad-get-orig-definition function))
3410 (current-definition (if (ad-real-definition function)
3411 (symbol-function function))))
3412 (if original-definition
3413 (if current-definition
3414 (if (and (not (eq current-definition original-definition))
3415 ;; Redefinition with an advised definition from a
3416 ;; different function won't count as such:
3417 (not (ad-advised-definition-p current-definition)))
3418 ;; we have a redefinition:
3419 (if (not (memq ad-redefinition-action '(accept discard warn)))
3420 (error "ad-handle-definition (see its doc): `%s' %s"
3421 function "invalidly redefined")
3422 (if (eq ad-redefinition-action 'discard)
3423 (ad-safe-fset function original-definition)
3424 (ad-set-orig-definition function current-definition)
3425 (if (eq ad-redefinition-action 'warn)
3426 (message "ad-handle-definition: `%s' got redefined"
3427 function))))
3428 ;; either advised def or correct original is in place:
3429 nil)
3430 ;; we have an undefinition, ignore it:
3431 nil)
3432 (if current-definition
3433 ;; we have a first definition, save it as original:
3434 (ad-set-orig-definition function current-definition)
3435 ;; we don't have anything noteworthy:
3436 nil))))
3439 ;; @@ The top-level advice interface:
3440 ;; ==================================
3442 ;;;###autoload
3443 (defun ad-activate (function &optional compile)
3444 "Activate all the advice information of an advised FUNCTION.
3445 If FUNCTION has a proper original definition then an advised
3446 definition will be generated from FUNCTION's advice info and the
3447 definition of FUNCTION will be replaced with it. If a previously
3448 cached advised definition was available, it will be used.
3449 The optional COMPILE argument determines whether the resulting function
3450 or a compilable cached definition will be compiled. If it is negative
3451 no compilation will be performed, if it is positive or otherwise non-nil
3452 the resulting function will be compiled, if it is nil the behavior depends
3453 on the value of `ad-default-compilation-action' (which see).
3454 Activation of an advised function that has an advice info but no actual
3455 pieces of advice is equivalent to a call to `ad-unadvise'. Activation of
3456 an advised function that has actual pieces of advice but none of them are
3457 enabled is equivalent to a call to `ad-deactivate'. The current advised
3458 definition will always be cached for later usage."
3459 (interactive
3460 (list (ad-read-advised-function "Activate advice of")
3461 current-prefix-arg))
3462 (if ad-activate-on-top-level
3463 ;; avoid recursive calls to `ad-activate':
3464 (ad-with-auto-activation-disabled
3465 (if (not (ad-is-advised function))
3466 (error "ad-activate: `%s' is not advised" function)
3467 (ad-handle-definition function)
3468 ;; Just return for forward advised and not yet defined functions:
3469 (if (ad-get-orig-definition function)
3470 (if (not (ad-has-any-advice function))
3471 (ad-unadvise function)
3472 ;; Otherwise activate the advice:
3473 (cond ((ad-has-redefining-advice function)
3474 (ad-activate-advised-definition function compile)
3475 (ad-set-advice-info-field function 'active t)
3476 (eval (ad-make-hook-form function 'activation))
3477 function)
3478 ;; Here we are if we have all disabled advices:
3479 (t (ad-deactivate function)))))))))
3481 (defalias 'ad-activate-on 'ad-activate)
3483 (defun ad-deactivate (function)
3484 "Deactivate the advice of an actively advised FUNCTION.
3485 If FUNCTION has a proper original definition, then the current
3486 definition of FUNCTION will be replaced with it. All the advice
3487 information will still be available so it can be activated again with
3488 a call to `ad-activate'."
3489 (interactive
3490 (list (ad-read-advised-function "Deactivate advice of" 'ad-is-active)))
3491 (if (not (ad-is-advised function))
3492 (error "ad-deactivate: `%s' is not advised" function)
3493 (cond ((ad-is-active function)
3494 (ad-handle-definition function)
3495 (if (not (ad-get-orig-definition function))
3496 (error "ad-deactivate: `%s' has no original definition"
3497 function)
3498 (ad-safe-fset function (ad-get-orig-definition function))
3499 (ad-set-advice-info-field function 'active nil)
3500 (eval (ad-make-hook-form function 'deactivation))
3501 function)))))
3503 (defun ad-update (function &optional compile)
3504 "Update the advised definition of FUNCTION if its advice is active.
3505 See `ad-activate' for documentation on the optional COMPILE argument."
3506 (interactive
3507 (list (ad-read-advised-function
3508 "Update advised definition of" 'ad-is-active)))
3509 (if (ad-is-active function)
3510 (ad-activate function compile)))
3512 (defun ad-unadvise (function)
3513 "Deactivate FUNCTION and then remove all its advice information.
3514 If FUNCTION was not advised this will be a noop."
3515 (interactive
3516 (list (ad-read-advised-function "Unadvise function")))
3517 (cond ((ad-is-advised function)
3518 (if (ad-is-active function)
3519 (ad-deactivate function))
3520 (ad-clear-orig-definition function)
3521 (ad-set-advice-info function nil)
3522 (ad-pop-advised-function function))))
3524 (defun ad-recover (function)
3525 "Try to recover FUNCTION's original definition, and unadvise it.
3526 This is more low-level than `ad-unadvise' in that it does not do
3527 deactivation, which might run hooks and get into other trouble.
3528 Use in emergencies."
3529 ;; Use more primitive interactive behavior here: Accept any symbol that's
3530 ;; currently defined in obarray, not necessarily with a function definition:
3531 (interactive
3532 (list (intern
3533 (completing-read "Recover advised function: " obarray nil t))))
3534 (cond ((ad-is-advised function)
3535 (cond ((ad-get-orig-definition function)
3536 (ad-safe-fset function (ad-get-orig-definition function))
3537 (ad-clear-orig-definition function)))
3538 (ad-set-advice-info function nil)
3539 (ad-pop-advised-function function))))
3541 (defun ad-activate-regexp (regexp &optional compile)
3542 "Activate functions with an advice name containing a REGEXP match.
3543 This activates the advice for each function
3544 that has at least one piece of advice whose name includes a match for REGEXP.
3545 See `ad-activate' for documentation on the optional COMPILE argument."
3546 (interactive
3547 (list (ad-read-regexp "Activate via advice regexp")
3548 current-prefix-arg))
3549 (ad-do-advised-functions (function)
3550 (if (ad-find-some-advice function 'any regexp)
3551 (ad-activate function compile))))
3553 (defun ad-deactivate-regexp (regexp)
3554 "Deactivate functions with an advice name containing REGEXP match.
3555 This deactivates the advice for each function
3556 that has at least one piece of advice whose name includes a match for REGEXP."
3557 (interactive
3558 (list (ad-read-regexp "Deactivate via advice regexp")))
3559 (ad-do-advised-functions (function)
3560 (if (ad-find-some-advice function 'any regexp)
3561 (ad-deactivate function))))
3563 (defun ad-update-regexp (regexp &optional compile)
3564 "Update functions with an advice name containing a REGEXP match.
3565 This reactivates the advice for each function
3566 that has at least one piece of advice whose name includes a match for REGEXP.
3567 See `ad-activate' for documentation on the optional COMPILE argument."
3568 (interactive
3569 (list (ad-read-regexp "Update via advice regexp")
3570 current-prefix-arg))
3571 (ad-do-advised-functions (function)
3572 (if (ad-find-some-advice function 'any regexp)
3573 (ad-update function compile))))
3575 (defun ad-activate-all (&optional compile)
3576 "Activate all currently advised functions.
3577 See `ad-activate' for documentation on the optional COMPILE argument."
3578 (interactive "P")
3579 (ad-do-advised-functions (function)
3580 (ad-activate function compile)))
3582 (defun ad-deactivate-all ()
3583 "Deactivate all currently advised functions."
3584 (interactive)
3585 (ad-do-advised-functions (function)
3586 (ad-deactivate function)))
3588 (defun ad-update-all (&optional compile)
3589 "Update all currently advised functions.
3590 With prefix argument, COMPILE resulting advised definitions."
3591 (interactive "P")
3592 (ad-do-advised-functions (function)
3593 (ad-update function compile)))
3595 (defun ad-unadvise-all ()
3596 "Unadvise all currently advised functions."
3597 (interactive)
3598 (ad-do-advised-functions (function)
3599 (ad-unadvise function)))
3601 (defun ad-recover-all ()
3602 "Recover all currently advised functions. Use in emergencies.
3603 To recover a function means to try to find its original (pre-advice)
3604 definition, and delete all advice.
3605 This is more low-level than `ad-unadvise' in that it does not do
3606 deactivation, which might run hooks and get into other trouble."
3607 (interactive)
3608 (ad-do-advised-functions (function)
3609 (condition-case nil
3610 (ad-recover function)
3611 (error nil))))
3614 ;; Completion alist of valid `defadvice' flags
3615 (defvar ad-defadvice-flags
3616 '(("protect") ("disable") ("activate")
3617 ("compile") ("preactivate") ("freeze")))
3619 ;;;###autoload
3620 (defmacro defadvice (function args &rest body)
3621 "Define a piece of advice for FUNCTION (a symbol).
3622 The syntax of `defadvice' is as follows:
3624 \(defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3625 [DOCSTRING] [INTERACTIVE-FORM]
3626 BODY...)
3628 FUNCTION ::= Name of the function to be advised.
3629 CLASS ::= `before' | `around' | `after' | `activation' | `deactivation'.
3630 NAME ::= Non-nil symbol that names this piece of advice.
3631 POSITION ::= `first' | `last' | NUMBER. Optional, defaults to `first',
3632 see also `ad-add-advice'.
3633 ARGLIST ::= An optional argument list to be used for the advised function
3634 instead of the argument list of the original. The first one found in
3635 before/around/after-advices will be used.
3636 FLAG ::= `protect'|`disable'|`activate'|`compile'|`preactivate'|`freeze'.
3637 All flags can be specified with unambiguous initial substrings.
3638 DOCSTRING ::= Optional documentation for this piece of advice.
3639 INTERACTIVE-FORM ::= Optional interactive form to be used for the advised
3640 function. The first one found in before/around/after-advices will be used.
3641 BODY ::= Any s-expression.
3643 Semantics of the various flags:
3644 `protect': The piece of advice will be protected against non-local exits in
3645 any code that precedes it. If any around-advice of a function is protected
3646 then automatically all around-advices will be protected (the complete onion).
3648 `activate': All advice of FUNCTION will be activated immediately if
3649 FUNCTION has been properly defined prior to this application of `defadvice'.
3651 `compile': In conjunction with `activate' specifies that the resulting
3652 advised function should be compiled.
3654 `disable': The defined advice will be disabled, hence, it will not be used
3655 during activation until somebody enables it.
3657 `preactivate': Preactivates the advised FUNCTION at macro-expansion/compile
3658 time. This generates a compiled advised definition according to the current
3659 advice state that will be used during activation if appropriate. Only use
3660 this if the `defadvice' gets actually compiled.
3662 `freeze': Expands the `defadvice' into a redefining `defun/defmacro' according
3663 to this particular single advice. No other advice information will be saved.
3664 Frozen advices cannot be undone, they behave like a hard redefinition of
3665 the advised function. `freeze' implies `activate' and `preactivate'. The
3666 documentation of the advised function can be dumped onto the `DOC' file
3667 during preloading.
3669 See Info node `(elisp)Advising Functions' for comprehensive documentation.
3670 usage: (defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3671 [DOCSTRING] [INTERACTIVE-FORM]
3672 BODY...)"
3673 (declare (doc-string 3))
3674 (if (not (ad-name-p function))
3675 (error "defadvice: Invalid function name: %s" function))
3676 (let* ((class (car args))
3677 (name (if (not (ad-class-p class))
3678 (error "defadvice: Invalid advice class: %s" class)
3679 (nth 1 args)))
3680 (position (if (not (ad-name-p name))
3681 (error "defadvice: Invalid advice name: %s" name)
3682 (setq args (nthcdr 2 args))
3683 (if (ad-position-p (car args))
3684 (prog1 (car args)
3685 (setq args (cdr args))))))
3686 (arglist (if (listp (car args))
3687 (prog1 (car args)
3688 (setq args (cdr args)))))
3689 (flags
3690 (mapcar
3691 (function
3692 (lambda (flag)
3693 (let ((completion
3694 (try-completion (symbol-name flag) ad-defadvice-flags)))
3695 (cond ((eq completion t) flag)
3696 ((assoc completion ad-defadvice-flags)
3697 (intern completion))
3698 (t (error "defadvice: Invalid or ambiguous flag: %s"
3699 flag))))))
3700 args))
3701 (advice (ad-make-advice
3702 name (memq 'protect flags)
3703 (not (memq 'disable flags))
3704 `(advice lambda ,arglist ,@body)))
3705 (preactivation (if (memq 'preactivate flags)
3706 (ad-preactivate-advice
3707 function advice class position))))
3708 ;; Now for the things to be done at evaluation time:
3709 (if (memq 'freeze flags)
3710 ;; jwz's idea: Freeze the advised definition into a dumpable
3711 ;; defun/defmacro whose docs can be written to the DOC file:
3712 (ad-make-freeze-definition function advice class position)
3713 ;; the normal case:
3714 `(progn
3715 (ad-add-advice ',function ',advice ',class ',position)
3716 ,@(if preactivation
3717 `((ad-set-cache
3718 ',function
3719 ;; the function will get compiled:
3720 ,(cond ((ad-macro-p (car preactivation))
3721 `(ad-macrofy
3722 (function
3723 ,(ad-lambdafy
3724 (car preactivation)))))
3725 (t `(function
3726 ,(car preactivation))))
3727 ',(car (cdr preactivation)))))
3728 ,@(if (memq 'activate flags)
3729 `((ad-activate ',function
3730 ,(if (memq 'compile flags) t))))
3731 ',function))))
3734 ;; @@ Tools:
3735 ;; =========
3737 (defmacro ad-with-originals (functions &rest body)
3738 "Binds FUNCTIONS to their original definitions and execute BODY.
3739 For any members of FUNCTIONS that are not currently advised the rebinding will
3740 be a noop. Any modifications done to the definitions of FUNCTIONS will be
3741 undone on exit of this macro."
3742 (let* ((index -1)
3743 ;; Make let-variables to store current definitions:
3744 (current-bindings
3745 (mapcar (function
3746 (lambda (function)
3747 (setq index (1+ index))
3748 (list (intern (format "ad-oRiGdEf-%d" index))
3749 `(symbol-function ',function))))
3750 functions)))
3751 `(let ,current-bindings
3752 (unwind-protect
3753 (progn
3754 ,@(progn
3755 ;; Make forms to redefine functions to their
3756 ;; original definitions if they are advised:
3757 (setq index -1)
3758 (mapcar
3759 (function
3760 (lambda (function)
3761 (setq index (1+ index))
3762 `(ad-safe-fset
3763 ',function
3764 (or (ad-get-orig-definition ',function)
3765 ,(car (nth index current-bindings))))))
3766 functions))
3767 ,@body)
3768 ,@(progn
3769 ;; Make forms to back-define functions to the definitions
3770 ;; they had outside this macro call:
3771 (setq index -1)
3772 (mapcar
3773 (function
3774 (lambda (function)
3775 (setq index (1+ index))
3776 `(ad-safe-fset
3777 ',function
3778 ,(car (nth index current-bindings)))))
3779 functions))))))
3781 (if (not (get 'ad-with-originals 'lisp-indent-hook))
3782 (put 'ad-with-originals 'lisp-indent-hook 1))
3785 ;; @@ Advising `documentation':
3786 ;; ============================
3787 ;; Use the advice mechanism to advise `documentation' to make it
3788 ;; generate proper documentation strings for advised definitions:
3790 ;; @@ Starting, stopping and recovering from the advice package magic:
3791 ;; ===================================================================
3793 (defun ad-start-advice ()
3794 "Start the automatic advice handling magic."
3795 (interactive)
3796 ;; Advising `ad-activate-internal' means death!!
3797 (ad-set-advice-info 'ad-activate-internal nil)
3798 (ad-safe-fset 'ad-activate-internal 'ad-activate))
3800 (defun ad-stop-advice ()
3801 "Stop the automatic advice handling magic.
3802 You should only need this in case of Advice-related emergencies."
3803 (interactive)
3804 ;; Advising `ad-activate-internal' means death!!
3805 (ad-set-advice-info 'ad-activate-internal nil)
3806 (ad-safe-fset 'ad-activate-internal 'ad-activate-internal-off))
3808 (defun ad-recover-normality ()
3809 "Undo all advice related redefinitions and unadvises everything.
3810 Use only in REAL emergencies."
3811 (interactive)
3812 ;; Advising `ad-activate-internal' means death!!
3813 (ad-set-advice-info 'ad-activate-internal nil)
3814 (ad-safe-fset 'ad-activate-internal 'ad-activate-internal-off)
3815 (ad-recover-all)
3816 (setq ad-advised-functions nil))
3818 (ad-start-advice)
3820 (provide 'advice)
3822 ;;; advice.el ends here