Merge from trunk.
[bpt/emacs.git] / lisp / emacs-lisp / advice.el
1 ;;; advice.el --- An overloading mechanism for Emacs Lisp functions -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 1993-1994, 2000-2012 Free Software Foundation, Inc.
4
5 ;; Author: Hans Chalupsky <hans@cs.buffalo.edu>
6 ;; Maintainer: FSF
7 ;; Created: 12 Dec 1992
8 ;; Keywords: extensions, lisp, tools
9 ;; Package: emacs
10
11 ;; This file is part of GNU Emacs.
12
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.
17
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.
22
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/>.
25
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|
30
31
32 ;;; Commentary:
33
34 ;; Advice is documented in the Emacs Lisp Manual.
35
36 ;; @ Introduction:
37 ;; ===============
38 ;; This package implements a full-fledged Lisp-style advice mechanism
39 ;; for Emacs Lisp. Advice is a clean and efficient way to modify the
40 ;; behavior of Emacs Lisp functions without having to keep personal
41 ;; modified copies of such functions around. A great number of such
42 ;; modifications can be achieved by treating the original function as a
43 ;; black box and specifying a different execution environment for it
44 ;; with a piece of advice. Think of a piece of advice as a kind of fancy
45 ;; hook that you can attach to any function/macro/subr.
46
47 ;; @ Highlights:
48 ;; =============
49 ;; - Clean definition of multiple, named before/around/after advices
50 ;; for functions, macros, subrs and special forms
51 ;; - Full control over the arguments an advised function will receive,
52 ;; the binding environment in which it will be executed, as well as the
53 ;; value it will return.
54 ;; - Allows re/definition of interactive behavior for functions and subrs
55 ;; - Every piece of advice can have its documentation string which will be
56 ;; combined with the original documentation of the advised function at
57 ;; call-time of `documentation' for proper command-key substitution.
58 ;; - The execution of every piece of advice can be protected against error
59 ;; and non-local exits in preceding code or advices.
60 ;; - Simple argument access either by name, or, more portable but as
61 ;; efficient, via access macros
62 ;; - Allows the specification of a different argument list for the advised
63 ;; version of a function.
64 ;; - Advised functions can be byte-compiled either at file-compile time
65 ;; (see preactivation) or activation time.
66 ;; - Separation of advice definition and activation
67 ;; - Forward advice is possible, that is
68 ;; as yet undefined or autoload functions can be advised without having to
69 ;; preload the file in which they are defined.
70 ;; - Forward redefinition is possible because around advice can be used to
71 ;; completely redefine a function.
72 ;; - A caching mechanism for advised definition provides for cheap deactivation
73 ;; and reactivation of advised functions.
74 ;; - Preactivation allows efficient construction and compilation of advised
75 ;; definitions at file compile time without giving up the flexibility of
76 ;; the advice mechanism.
77 ;; - En/disablement mechanism allows the use of different "views" of advised
78 ;; functions depending on what pieces of advice are currently en/disabled
79 ;; - Provides manipulation mechanisms for sets of advised functions via
80 ;; regular expressions that match advice names
81
82 ;; @ Overview, or how to read this file:
83 ;; =====================================
84 ;; You can use `outline-mode' to help you read this documentation (set
85 ;; `outline-regexp' to `";; @+"').
86 ;;
87 ;; The four major sections of this file are:
88 ;;
89 ;; @ This initial information ...installation, customization etc.
90 ;; @ Advice documentation: ...general documentation
91 ;; @ Foo games: An advice tutorial ...teaches about Advice by example
92 ;; @ Advice implementation: ...actual code, yeah!!
93 ;;
94 ;; The latter three are actual headings which you can search for
95 ;; directly in case `outline-mode' doesn't work for you.
96
97 ;; @ Restrictions:
98 ;; ===============
99 ;; - Advised functions/macros/subrs will only exhibit their advised behavior
100 ;; when they are invoked via their function cell. This means that advice will
101 ;; not work for the following:
102 ;; + advised subrs that are called directly from other subrs or C-code
103 ;; + advised subrs that got replaced with their byte-code during
104 ;; byte-compilation (e.g., car)
105 ;; + advised macros which were expanded during byte-compilation before
106 ;; their advice was activated.
107
108 ;; @ Credits:
109 ;; ==========
110 ;; This package is an extension and generalization of packages such as
111 ;; insert-hooks.el written by Noah S. Friedman, and advise.el written by
112 ;; Raul J. Acevedo. Some ideas used in here come from these packages,
113 ;; others come from the various Lisp advice mechanisms I've come across
114 ;; so far, and a few are simply mine.
115
116 ;; @ Comments, suggestions, bug reports:
117 ;; =====================================
118 ;; If you find any bugs, have suggestions for new advice features, find the
119 ;; documentation wrong, confusing, incomplete, or otherwise unsatisfactory,
120 ;; have any questions about Advice, or have otherwise enlightening
121 ;; comments feel free to send me email at <hans@cs.buffalo.edu>.
122
123 ;; @ Safety Rules and Emergency Exits:
124 ;; ===================================
125 ;; Before we begin: CAUTION!!
126 ;; Advice provides you with a lot of rope to hang yourself on very
127 ;; easily accessible trees, so, here are a few important things you
128 ;; should know: Once Advice has been started with `ad-start-advice'
129 ;; (which happens automatically when you load this file), it
130 ;; generates an advised definition of the `documentation' function, and
131 ;; it will enable automatic advice activation when functions get defined.
132 ;; All of this can be undone at any time with `M-x ad-stop-advice'.
133 ;;
134 ;; If you experience any strange behavior/errors etc. that you attribute to
135 ;; Advice or to some ill-advised function do one of the following:
136
137 ;; - M-x ad-deactivate FUNCTION (if you have a definite suspicion what
138 ;; function gives you problems)
139 ;; - M-x ad-deactivate-all (if you don't have a clue what's going wrong)
140 ;; - M-x ad-stop-advice (if you think the problem is related to the
141 ;; advised functions used by Advice itself)
142 ;; - M-x ad-recover-normality (for real emergencies)
143 ;; - If none of the above solves your Advice-related problem go to another
144 ;; terminal, kill your Emacs process and send me some hate mail.
145
146 ;; The first three measures have restarts, i.e., once you've figured out
147 ;; the problem you can reactivate advised functions with either `ad-activate',
148 ;; `ad-activate-all', or `ad-start-advice'. `ad-recover-normality' unadvises
149 ;; everything so you won't be able to reactivate any advised functions, you'll
150 ;; have to stick with their standard incarnations for the rest of the session.
151
152 ;; IMPORTANT: With Advice loaded always do `M-x ad-deactivate-all' before
153 ;; you byte-compile a file, because advised special forms and macros can lead
154 ;; to unwanted compilation results. When you are done compiling use
155 ;; `M-x ad-activate-all' to go back to the advised state of all your
156 ;; advised functions.
157
158 ;; RELAX: Advice is pretty safe even if you are oblivious to the above.
159 ;; I use it extensively and haven't run into any serious trouble in a long
160 ;; time. Just wanted you to be warned.
161
162 ;; @ Customization:
163 ;; ================
164
165 ;; Look at the documentation of `ad-redefinition-action' for possible values
166 ;; of this variable. Its default value is `warn' which will print a warning
167 ;; message when an already defined advised function gets redefined with a
168 ;; new original definition and de/activated.
169
170 ;; Look at the documentation of `ad-default-compilation-action' for possible
171 ;; values of this variable. Its default value is `maybe' which will compile
172 ;; advised definitions during activation in case the byte-compiler is already
173 ;; loaded. Otherwise, it will leave them uncompiled.
174
175 ;; @ Motivation:
176 ;; =============
177 ;; Before I go on explaining how advice works, here are four simple examples
178 ;; how this package can be used. The first three are very useful, the last one
179 ;; is just a joke:
180
181 ;;(defadvice switch-to-buffer (before existing-buffers-only activate)
182 ;; "When called interactively switch to existing buffers only, unless
183 ;;when called with a prefix argument."
184 ;; (interactive
185 ;; (list (read-buffer "Switch to buffer: " (other-buffer)
186 ;; (null current-prefix-arg)))))
187 ;;
188 ;;(defadvice switch-to-buffer (around confirm-non-existing-buffers activate)
189 ;; "Switch to non-existing buffers only upon confirmation."
190 ;; (interactive "BSwitch to buffer: ")
191 ;; (if (or (get-buffer (ad-get-arg 0))
192 ;; (y-or-n-p (format "`%s' does not exist, create? " (ad-get-arg 0))))
193 ;; ad-do-it))
194 ;;
195 ;;(defadvice find-file (before existing-files-only activate)
196 ;; "Find existing files only"
197 ;; (interactive "fFind file: "))
198 ;;
199 ;;(defadvice car (around interactive activate)
200 ;; "Make `car' an interactive function."
201 ;; (interactive "xCar of list: ")
202 ;; ad-do-it
203 ;; (if (called-interactively-p 'interactive)
204 ;; (message "%s" ad-return-value)))
205
206
207 ;; @ Advice documentation:
208 ;; =======================
209 ;; Below is general documentation of the various features of advice. For more
210 ;; concrete examples check the corresponding sections in the tutorial part.
211
212 ;; @@ Terminology:
213 ;; ===============
214 ;; - Emacs: Emacs as released by the GNU Project
215 ;; - jwz: Jamie Zawinski - creator of the byte-compiler used in v19s.
216 ;; - Advice: The name of this package.
217 ;; - advices: Short for "pieces of advice".
218
219 ;; @@ Defining a piece of advice with `defadvice':
220 ;; ===============================================
221 ;; The main means of defining a piece of advice is the macro `defadvice',
222 ;; there is no interactive way of specifying a piece of advice. A call to
223 ;; `defadvice' has the following syntax which is similar to the syntax of
224 ;; `defun/defmacro':
225 ;;
226 ;; (defadvice <function> (<class> <name> [<position>] [<arglist>] {<flags>}*)
227 ;; [ [<documentation-string>] [<interactive-form>] ]
228 ;; {<body-form>}* )
229
230 ;; <function> is the name of the function/macro/subr to be advised.
231
232 ;; <class> is the class of the advice which has to be one of `before',
233 ;; `around', `after', `activation' or `deactivation' (the last two allow
234 ;; definition of special act/deactivation hooks).
235
236 ;; <name> is the name of the advice which has to be a non-nil symbol.
237 ;; Names uniquely identify a piece of advice in a certain advice class,
238 ;; hence, advices can be redefined by defining an advice with the same class
239 ;; and name. Advice names are global symbols, hence, the same name space
240 ;; conventions used for function names should be applied.
241
242 ;; An optional <position> specifies where in the current list of advices of
243 ;; the specified <class> this new advice will be placed. <position> has to
244 ;; be either `first', `last' or a number that specifies a zero-based
245 ;; position (`first' is equivalent to 0). If no position is specified
246 ;; `first' will be used as a default. If this call to `defadvice' redefines
247 ;; an already existing advice (see above) then the position argument will
248 ;; be ignored and the position of the already existing advice will be used.
249
250 ;; An optional <arglist> which has to be a list can be used to define the
251 ;; argument list of the advised function. This argument list should of
252 ;; course be compatible with the argument list of the original function,
253 ;; otherwise functions that call the advised function with the original
254 ;; argument list in mind will break. If more than one advice specify an
255 ;; argument list then the first one (the one with the smallest position)
256 ;; found in the list of before/around/after advices will be used.
257
258 ;; <flags> is a list of symbols that specify further information about the
259 ;; advice. All flags can be specified with unambiguous initial substrings.
260 ;; `activate': Specifies that the advice information of the advised
261 ;; function should be activated right after this advice has been
262 ;; defined. In forward advices `activate' will be ignored.
263 ;; `protect': Specifies that this advice should be protected against
264 ;; non-local exits and errors in preceding code/advices.
265 ;; `compile': Specifies that the advised function should be byte-compiled.
266 ;; This flag will be ignored unless `activate' is also specified.
267 ;; `disable': Specifies that the defined advice should be disabled, hence,
268 ;; it will not be used in an activation until somebody enables it.
269 ;; `preactivate': Specifies that the advised function should get preactivated
270 ;; at macro-expansion/compile time of this `defadvice'. This
271 ;; generates a compiled advised definition according to the
272 ;; current advice state which will be used during activation
273 ;; if appropriate. Only use this if the `defadvice' gets
274 ;; actually compiled.
275
276 ;; An optional <documentation-string> can be supplied to document the advice.
277 ;; On call of the `documentation' function it will be combined with the
278 ;; documentation strings of the original function and other advices.
279
280 ;; An optional <interactive-form> form can be supplied to change/add
281 ;; interactive behavior of the original function. If more than one advice
282 ;; has an `(interactive ...)' specification then the first one (the one
283 ;; with the smallest position) found in the list of before/around/after
284 ;; advices will be used.
285
286 ;; A possibly empty list of <body-forms> specifies the body of the advice in
287 ;; an implicit progn. The body of an advice can access/change arguments,
288 ;; the return value, the binding environment, and can have all sorts of
289 ;; other side effects.
290
291 ;; @@ Assembling advised definitions:
292 ;; ==================================
293 ;; Suppose a function/macro/subr/special-form has N pieces of before advice,
294 ;; M pieces of around advice and K pieces of after advice. Assuming none of
295 ;; the advices is protected, its advised definition will look like this
296 ;; (body-form indices correspond to the position of the respective advice in
297 ;; that advice class):
298
299 ;; ([macro] lambda <arglist>
300 ;; [ [<advised-docstring>] [(interactive ...)] ]
301 ;; (let (ad-return-value)
302 ;; {<before-0-body-form>}*
303 ;; ....
304 ;; {<before-N-1-body-form>}*
305 ;; {<around-0-body-form>}*
306 ;; {<around-1-body-form>}*
307 ;; ....
308 ;; {<around-M-1-body-form>}*
309 ;; (setq ad-return-value
310 ;; <apply original definition to <arglist>>)
311 ;; {<other-around-M-1-body-form>}*
312 ;; ....
313 ;; {<other-around-1-body-form>}*
314 ;; {<other-around-0-body-form>}*
315 ;; {<after-0-body-form>}*
316 ;; ....
317 ;; {<after-K-1-body-form>}*
318 ;; ad-return-value))
319
320 ;; Macros and special forms will be redefined as macros, hence the optional
321 ;; [macro] in the beginning of the definition.
322
323 ;; <arglist> is either the argument list of the original function or the
324 ;; first argument list defined in the list of before/around/after advices.
325 ;; The values of <arglist> variables can be accessed/changed in the body of
326 ;; an advice by simply referring to them by their original name, however,
327 ;; more portable argument access macros are also provided (see below).
328
329 ;; <advised-docstring> is an optional, special documentation string which will
330 ;; be expanded into a proper documentation string upon call of `documentation'.
331
332 ;; (interactive ...) is an optional interactive form either taken from the
333 ;; original function or from a before/around/after advice. For advised
334 ;; interactive subrs that do not have an interactive form specified in any
335 ;; advice we have to use (interactive) and then call the subr interactively
336 ;; if the advised function was called interactively, because the
337 ;; interactive specification of subrs is not accessible. This is the only
338 ;; case where changing the values of arguments will not have an affect
339 ;; because they will be reset by the interactive specification of the subr.
340 ;; If this is a problem one can always specify an interactive form in a
341 ;; before/around/after advice to gain control over argument values that
342 ;; were supplied interactively.
343 ;;
344 ;; Then the body forms of the various advices in the various classes of advice
345 ;; are assembled in order. The forms of around advice L are normally part of
346 ;; one of the forms of around advice L-1. An around advice can specify where
347 ;; the forms of the wrapped or surrounded forms should go with the special
348 ;; keyword `ad-do-it', which will be substituted with a `progn' containing the
349 ;; forms of the surrounded code.
350
351 ;; The innermost part of the around advice onion is
352 ;; <apply original definition to <arglist>>
353 ;; whose form depends on the type of the original function. The variable
354 ;; `ad-return-value' will be set to its result. This variable is visible to
355 ;; all pieces of advice which can access and modify it before it gets returned.
356 ;;
357 ;; The semantic structure of advised functions that contain protected pieces
358 ;; of advice is the same. The only difference is that `unwind-protect' forms
359 ;; make sure that the protected advice gets executed even if some previous
360 ;; piece of advice had an error or a non-local exit. If any around advice is
361 ;; protected then the whole around advice onion will be protected.
362
363 ;; @@ Argument access in advised functions:
364 ;; ========================================
365 ;; As already mentioned, the simplest way to access the arguments of an
366 ;; advised function in the body of an advice is to refer to them by name. To
367 ;; do that, the advice programmer needs to know either the names of the
368 ;; argument variables of the original function, or the names used in the
369 ;; argument list redefinition given in a piece of advice. While this simple
370 ;; method might be sufficient in many cases, it has the disadvantage that it
371 ;; is not very portable because it hardcodes the argument names into the
372 ;; advice. If the definition of the original function changes the advice
373 ;; might break even though the code might still be correct. Situations like
374 ;; that arise, for example, if one advises a subr like `eval-region' which
375 ;; gets redefined in a non-advice style into a function by the edebug
376 ;; package. If the advice assumes `eval-region' to be a subr it might break
377 ;; once edebug is loaded. Similar situations arise when one wants to use the
378 ;; same piece of advice across different versions of Emacs.
379
380 ;; As a solution to that advice provides argument list access macros that get
381 ;; translated into the proper access forms at activation time, i.e., when the
382 ;; advised definition gets constructed. Access macros access actual arguments
383 ;; by position regardless of how these actual argument get distributed onto
384 ;; the argument variables of a function. The rational behind this is that in
385 ;; Emacs Lisp the semantics of an argument is strictly determined by its
386 ;; position (there are no keyword arguments).
387
388 ;; Suppose the function `foo' is defined as
389 ;;
390 ;; (defun foo (x y &optional z &rest r) ....)
391 ;;
392 ;; and is then called with
393 ;;
394 ;; (foo 0 1 2 3 4 5 6)
395
396 ;; which means that X=0, Y=1, Z=2 and R=(3 4 5 6). The assumption is that
397 ;; the semantics of an actual argument is determined by its position. It is
398 ;; this semantics that has to be known by the advice programmer. Then s/he
399 ;; can access these arguments in a piece of advice with some of the
400 ;; following macros (the arrows indicate what value they will return):
401
402 ;; (ad-get-arg 0) -> 0
403 ;; (ad-get-arg 1) -> 1
404 ;; (ad-get-arg 2) -> 2
405 ;; (ad-get-arg 3) -> 3
406 ;; (ad-get-args 2) -> (2 3 4 5 6)
407 ;; (ad-get-args 4) -> (4 5 6)
408
409 ;; `(ad-get-arg <position>)' will return the actual argument that was supplied
410 ;; at <position>, `(ad-get-args <position>)' will return the list of actual
411 ;; arguments supplied starting at <position>. Note that these macros can be
412 ;; used without any knowledge about the form of the actual argument list of
413 ;; the original function.
414
415 ;; Similarly, `(ad-set-arg <position> <value-form>)' can be used to set the
416 ;; value of the actual argument at <position> to <value-form>. For example,
417 ;;
418 ;; (ad-set-arg 5 "five")
419 ;;
420 ;; will have the effect that R=(3 4 "five" 6) once the original function is
421 ;; called. `(ad-set-args <position> <value-list-form>)' can be used to set
422 ;; the list of actual arguments starting at <position> to <value-list-form>.
423 ;; For example,
424 ;;
425 ;; (ad-set-args 0 '(5 4 3 2 1 0))
426 ;;
427 ;; will have the effect that X=5, Y=4, Z=3 and R=(2 1 0) once the original
428 ;; function is called.
429
430 ;; All these access macros are text macros rather than real Lisp macros. When
431 ;; the advised definition gets constructed they get replaced with actual access
432 ;; forms depending on the argument list of the advised function, i.e., after
433 ;; that argument access is in most cases as efficient as using the argument
434 ;; variable names directly.
435
436 ;; @@@ Accessing argument bindings of arbitrary functions:
437 ;; =======================================================
438 ;; Some functions (such as `trace-function' defined in trace.el) need a
439 ;; method of accessing the names and bindings of the arguments of an
440 ;; arbitrary advised function. To do that within an advice one can use the
441 ;; special keyword `ad-arg-bindings' which is a text macro that will be
442 ;; substituted with a form that will evaluate to a list of binding
443 ;; specifications, one for every argument variable. These binding
444 ;; specifications can then be examined in the body of the advice. For
445 ;; example, somewhere in an advice we could do this:
446 ;;
447 ;; (let* ((bindings ad-arg-bindings)
448 ;; (firstarg (car bindings))
449 ;; (secondarg (car (cdr bindings))))
450 ;; ;; Print info about first argument
451 ;; (print (format "%s=%s (%s)"
452 ;; (ad-arg-binding-field firstarg 'name)
453 ;; (ad-arg-binding-field firstarg 'value)
454 ;; (ad-arg-binding-field firstarg 'type)))
455 ;; ....)
456 ;;
457 ;; The `type' of an argument is either `required', `optional' or `rest'.
458 ;; Wherever `ad-arg-bindings' appears a form will be inserted that evaluates
459 ;; to the list of bindings, hence, in order to avoid multiple unnecessary
460 ;; evaluations one should always bind it to some variable.
461
462 ;; @@@ Argument list mapping:
463 ;; ==========================
464 ;; Because `defadvice' allows the specification of the argument list
465 ;; of the advised function we need a mapping mechanism that maps this
466 ;; argument list onto that of the original function. Hence SYM and
467 ;; NEWDEF have to be properly mapped onto the &rest variable when the
468 ;; original definition is called. Advice automatically takes care of
469 ;; that mapping, hence, the advice programmer can specify an argument
470 ;; list without having to know about the exact structure of the
471 ;; original argument list as long as the new argument list takes a
472 ;; compatible number/magnitude of actual arguments.
473
474 ;; @@ Activation and deactivation:
475 ;; ===============================
476 ;; The definition of an advised function does not change until all its advice
477 ;; gets actually activated. Activation can either happen with the `activate'
478 ;; flag specified in the `defadvice', with an explicit call or interactive
479 ;; invocation of `ad-activate', or if forward advice is enabled (i.e., the
480 ;; value of `ad-activate-on-definition' is t) at the time an already advised
481 ;; function gets defined.
482
483 ;; When a function gets first activated its original definition gets saved,
484 ;; all defined and enabled pieces of advice will get combined with the
485 ;; original definition, the resulting definition might get compiled depending
486 ;; on some conditions described below, and then the function will get
487 ;; redefined with the advised definition. This also means that undefined
488 ;; functions cannot get activated even though they might be already advised.
489
490 ;; The advised definition will get compiled either if `ad-activate' was called
491 ;; interactively with a prefix argument, or called explicitly with its second
492 ;; argument as t, or, if `ad-default-compilation-action' justifies it according
493 ;; to the current system state. If the advised definition was
494 ;; constructed during "preactivation" (see below) then that definition will
495 ;; be already compiled because it was constructed during byte-compilation of
496 ;; the file that contained the `defadvice' with the `preactivate' flag.
497
498 ;; `ad-deactivate' can be used to back-define an advised function to its
499 ;; original definition. It can be called interactively or directly. Because
500 ;; `ad-activate' caches the advised definition the function can be
501 ;; reactivated via `ad-activate' with only minor overhead (it is checked
502 ;; whether the current advice state is consistent with the cached
503 ;; definition, see the section on caching below).
504
505 ;; `ad-activate-regexp' and `ad-deactivate-regexp' can be used to de/activate
506 ;; all currently advised function that have a piece of advice with a name that
507 ;; contains a match for a regular expression. These functions can be used to
508 ;; de/activate sets of functions depending on certain advice naming
509 ;; conventions.
510
511 ;; Finally, `ad-activate-all' and `ad-deactivate-all' can be used to
512 ;; de/activate all currently advised functions. These are useful to
513 ;; (temporarily) return to an un/advised state.
514
515 ;; @@@ Reasons for the separation of advice definition and activation:
516 ;; ===================================================================
517 ;; As already mentioned, advising happens in two stages:
518
519 ;; 1) definition of various pieces of advice
520 ;; 2) activation of all advice currently defined and enabled
521
522 ;; The advantage of this is that various pieces of advice can be defined
523 ;; before they get combined into an advised definition which avoids
524 ;; unnecessary constructions of intermediate advised definitions. The more
525 ;; important advantage is that it allows the implementation of forward advice.
526 ;; Advice information for a certain function accumulates as the value of the
527 ;; `advice-info' property of the function symbol. This accumulation is
528 ;; completely independent of the fact that that function might not yet be
529 ;; defined. The special forms `defun' and `defmacro' have been advised to
530 ;; check whether the function/macro they defined had advice information
531 ;; associated with it. If so and forward advice is enabled, the original
532 ;; definition will be saved, and then the advice will be activated.
533
534 ;; @@ Enabling/disabling pieces or sets of advice:
535 ;; ===============================================
536 ;; A major motivation for the development of this advice package was to bring
537 ;; a little bit more structure into the function overloading chaos in Emacs
538 ;; Lisp. Many packages achieve some of their functionality by adding a little
539 ;; bit (or a lot) to the standard functionality of some Emacs Lisp function.
540 ;; ange-ftp is a very popular package that achieves its magic by overloading
541 ;; most Emacs Lisp functions that deal with files. A popular function that's
542 ;; overloaded by many packages is `expand-file-name'. The situation that one
543 ;; function is multiply overloaded can arise easily.
544
545 ;; Once in a while it would be desirable to be able to disable some/all
546 ;; overloads of a particular package while keeping all the rest. Ideally -
547 ;; at least in my opinion - these overloads would all be done with advice,
548 ;; I know I am dreaming right now... In that ideal case the enable/disable
549 ;; mechanism of advice could be used to achieve just that.
550
551 ;; Every piece of advice is associated with an enablement flag. When the
552 ;; advised definition of a particular function gets constructed (e.g., during
553 ;; activation) only the currently enabled pieces of advice will be considered.
554 ;; This mechanism allows one to have different "views" of an advised function
555 ;; dependent on what pieces of advice are currently enabled.
556
557 ;; Another motivation for this mechanism is that it allows one to define a
558 ;; piece of advice for some function yet keep it dormant until a certain
559 ;; condition is met. Until then activation of the function will not make use
560 ;; of that piece of advice. Once the condition is met the advice can be
561 ;; enabled and a reactivation of the function will add its functionality as
562 ;; part of the new advised definition. For example, the advices of `defun'
563 ;; etc. used by advice itself will stay disabled until `ad-start-advice' is
564 ;; called and some variables have the proper values. Hence, if somebody
565 ;; else advised these functions too and activates them the advices defined
566 ;; by advice will get used only if they are intended to be used.
567
568 ;; The main interface to this mechanism are the interactive functions
569 ;; `ad-enable-advice' and `ad-disable-advice'. For example, the following
570 ;; would disable a particular advice of the function `foo':
571 ;;
572 ;; (ad-disable-advice 'foo 'before 'my-advice)
573 ;;
574 ;; This call by itself only changes the flag, to get the proper effect in
575 ;; the advised definition too one has to activate `foo' with
576 ;;
577 ;; (ad-activate 'foo)
578 ;;
579 ;; or interactively. To disable whole sets of advices one can use a regular
580 ;; expression mechanism. For example, let us assume that ange-ftp actually
581 ;; used advice to overload all its functions, and that it used the
582 ;; "ange-ftp-" prefix for all its advice names, then we could temporarily
583 ;; disable all its advices with
584 ;;
585 ;; (ad-disable-regexp "^ange-ftp-")
586 ;;
587 ;; and the following call would put that actually into effect:
588 ;;
589 ;; (ad-activate-regexp "^ange-ftp-")
590 ;;
591 ;; A safer way would have been to use
592 ;;
593 ;; (ad-update-regexp "^ange-ftp-")
594 ;;
595 ;; instead which would have only reactivated currently actively advised
596 ;; functions, but not functions that were currently inactive. All these
597 ;; functions can also be called interactively.
598
599 ;; A certain piece of advice is considered a match if its name contains a
600 ;; match for the regular expression. To enable ange-ftp again we would use
601 ;; `ad-enable-regexp' and then activate or update again.
602
603 ;; @@ Forward advice, automatic advice activation:
604 ;; ===============================================
605 ;; Because most Emacs Lisp packages are loaded on demand via an autoload
606 ;; mechanism it is essential to be able to "forward advise" functions.
607 ;; Otherwise, proper advice definition and activation would make it necessary
608 ;; to preload every file that defines a certain function before it can be
609 ;; advised, which would partly defeat the purpose of the advice mechanism.
610
611 ;; In the following, "forward advice" always implies its automatic activation
612 ;; once a function gets defined, and not just the accumulation of advice
613 ;; information for a possibly undefined function.
614
615 ;; Advice implements forward advice mainly via the following: 1) Separation
616 ;; of advice definition and activation that makes it possible to accumulate
617 ;; advice information without having the original function already defined,
618 ;; 2) special versions of the built-in functions `fset/defalias' which check
619 ;; for advice information whenever they define a function. If advice
620 ;; information was found then the advice will immediately get activated when
621 ;; the function gets defined.
622
623 ;; Automatic advice activation means, that whenever a function gets defined
624 ;; with either `defun', `defmacro', `fset' or by loading a byte-compiled
625 ;; file, and the function has some advice-info stored with it then that
626 ;; advice will get activated right away.
627
628 ;; @@@ Enabling automatic advice activation:
629 ;; =========================================
630 ;; Automatic advice activation is enabled by default. It can be disabled with
631 ;; `M-x ad-stop-advice' and enabled again with `M-x ad-start-advice'.
632
633 ;; @@ Caching of advised definitions:
634 ;; ==================================
635 ;; After an advised definition got constructed it gets cached as part of the
636 ;; advised function's advice-info so it can be reused, for example, after an
637 ;; intermediate deactivation. Because the advice-info of a function might
638 ;; change between the time of caching and reuse a cached definition gets
639 ;; a cache-id associated with it so it can be verified whether the cached
640 ;; definition is still valid (the main application of this is preactivation
641 ;; - see below).
642
643 ;; When an advised function gets activated and a verifiable cached definition
644 ;; is available, then that definition will be used instead of creating a new
645 ;; advised definition from scratch. If you want to make sure that a new
646 ;; definition gets constructed then you should use `ad-clear-cache' before you
647 ;; activate the advised function.
648
649 ;; @@ Preactivation:
650 ;; =================
651 ;; Constructing an advised definition is moderately expensive. In a situation
652 ;; where one package defines a lot of advised functions it might be
653 ;; prohibitively expensive to do all the advised definition construction at
654 ;; runtime. Preactivation is a mechanism that allows compile-time construction
655 ;; of compiled advised definitions that can be activated cheaply during
656 ;; runtime. Preactivation uses the caching mechanism to do that. Here's how it
657 ;; works:
658
659 ;; When the byte-compiler compiles a `defadvice' that has the `preactivate'
660 ;; flag specified, it uses the current original definition of the advised
661 ;; function plus the advice specified in this `defadvice' (even if it is
662 ;; specified as disabled) and all other currently enabled pieces of advice to
663 ;; construct an advised definition and an identifying cache-id and makes them
664 ;; part of the `defadvice' expansion which will then be compiled by the
665 ;; byte-compiler.
666 ;; When the file with the compiled, preactivating `defadvice' gets loaded the
667 ;; precompiled advised definition will be cached on the advised function's
668 ;; advice-info. When it gets activated (can be immediately on execution of the
669 ;; `defadvice' or any time later) the cache-id gets checked against the
670 ;; current state of advice and if it is verified the precompiled definition
671 ;; will be used directly (the verification is pretty cheap). If it couldn't get
672 ;; verified a new advised definition for that function will be built from
673 ;; scratch, hence, the efficiency added by the preactivation mechanism does
674 ;; not at all impair the flexibility of the advice mechanism.
675
676 ;; MORAL: In order get all the efficiency out of preactivation the advice
677 ;; state of an advised function at the time the file with the
678 ;; preactivating `defadvice' gets byte-compiled should be exactly
679 ;; the same as it will be when the advice of that function gets
680 ;; actually activated. If it is not there is a high chance that the
681 ;; cache-id will not match and hence a new advised definition will
682 ;; have to be constructed at runtime.
683
684 ;; Preactivation and forward advice do not contradict each other. It is
685 ;; perfectly ok to load a file with a preactivating `defadvice' before the
686 ;; original definition of the advised function is available. The constructed
687 ;; advised definition will be used once the original function gets defined and
688 ;; its advice gets activated. The only constraint is that at the time the
689 ;; file with the preactivating `defadvice' got compiled the original function
690 ;; definition was available.
691
692 ;; TIPS: Here are some indications that a preactivation did not work the way
693 ;; you intended it to work:
694 ;; - Activation of the advised function takes longer than usual/expected
695 ;; - The byte-compiler gets loaded while an advised function gets
696 ;; activated
697 ;; - `byte-compile' is part of the `features' variable even though you
698 ;; did not use the byte-compiler
699 ;; Right now advice does not provide an elegant way to find out whether
700 ;; and why a preactivation failed. What you can do is to trace the
701 ;; function `ad-cache-id-verification-code' (with the function
702 ;; `trace-function-background' defined in my trace.el package) before
703 ;; any of your advised functions get activated. After they got
704 ;; activated check whether all calls to `ad-cache-id-verification-code'
705 ;; returned `verified' as a result. Other values indicate why the
706 ;; verification failed which should give you enough information to
707 ;; fix your preactivation/compile/load/activation sequence.
708
709 ;; IMPORTANT: There is one case (that I am aware of) that can make
710 ;; preactivation fail, i.e., a preconstructed advised definition that does
711 ;; NOT match the current state of advice gets used nevertheless. That case
712 ;; arises if one package defines a certain piece of advice which gets used
713 ;; during preactivation, and another package incompatibly redefines that
714 ;; very advice (i.e., same function/class/name), and it is the second advice
715 ;; that is available when the preconstructed definition gets activated, and
716 ;; that was the only definition of that advice so far (`ad-add-advice'
717 ;; catches advice redefinitions and clears the cache in such a case).
718 ;; Catching that would make the cache verification too expensive.
719
720 ;; MORAL-II: Redefining somebody else's advice is BAAAAD (to speak with
721 ;; George Walker Bush), and why would you redefine your own advice anyway?
722 ;; Advice is a mechanism to facilitate function redefinition, not advice
723 ;; redefinition (wait until I write Meta-Advice :-). If you really have
724 ;; to undo somebody else's advice try to write a "neutralizing" advice.
725
726 ;; @@ Advising macros and special forms and other dangerous things:
727 ;; ================================================================
728 ;; Look at the corresponding tutorial sections for more information on
729 ;; these topics. Here it suffices to point out that the special treatment
730 ;; of macros and special forms by the byte-compiler can lead to problems
731 ;; when they get advised. Macros can create problems because they get
732 ;; expanded at compile time, hence, they might not have all the necessary
733 ;; runtime support and such advice cannot be de/activated or changed as
734 ;; it is possible for functions. Special forms create problems because they
735 ;; have to be advised "into" macros, i.e., an advised special form is a
736 ;; implemented as a macro, hence, in most cases the byte-compiler will
737 ;; not recognize it as a special form anymore which can lead to very strange
738 ;; results.
739 ;;
740 ;; MORAL: - Only advise macros or special forms when you are absolutely sure
741 ;; what you are doing.
742 ;; - As a safety measure, always do `ad-deactivate-all' before you
743 ;; byte-compile a file to make sure that even if some inconsiderate
744 ;; person advised some special forms you'll get proper compilation
745 ;; results. After compilation do `ad-activate-all' to get back to
746 ;; the previous state.
747
748 ;; @@ Adding a piece of advice with `ad-add-advice':
749 ;; =================================================
750 ;; The non-interactive function `ad-add-advice' can be used to add a piece of
751 ;; advice to some function without using `defadvice'. This is useful if advice
752 ;; has to be added somewhere by a function (also look at `ad-make-advice').
753
754 ;; @@ Activation/deactivation advices, file load hooks:
755 ;; ====================================================
756 ;; There are two special classes of advice called `activation' and
757 ;; `deactivation'. The body forms of these advices are not included into the
758 ;; advised definition of a function, rather they are assembled into a hook
759 ;; form which will be evaluated whenever the advice-info of the advised
760 ;; function gets activated or deactivated. One application of this mechanism
761 ;; is to define file load hooks for files that do not provide such hooks.
762 ;; For example, suppose you want to print a message whenever `file-x' gets
763 ;; loaded, and suppose the last function defined in `file-x' is
764 ;; `file-x-last-fn'. Then we can define the following advice:
765 ;;
766 ;; (defadvice file-x-last-fn (activation file-x-load-hook)
767 ;; "Executed whenever file-x is loaded"
768 ;; (if load-in-progress (message "Loaded file-x")))
769 ;;
770 ;; This will constitute a forward advice for function `file-x-last-fn' which
771 ;; will get activated when `file-x' is loaded (only if forward advice is
772 ;; enabled of course). Because there are no "real" pieces of advice
773 ;; available for it, its definition will not be changed, but the activation
774 ;; advice will be run during its activation which is equivalent to having a
775 ;; file load hook for `file-x'.
776
777 ;; @@ Summary of main advice concepts:
778 ;; ===================================
779 ;; - Definition:
780 ;; A piece of advice gets defined with `defadvice' and added to the
781 ;; `advice-info' property of a function.
782 ;; - Enablement:
783 ;; Every piece of advice has an enablement flag associated with it. Only
784 ;; enabled advices are considered during construction of an advised
785 ;; definition.
786 ;; - Activation:
787 ;; Redefine an advised function with its advised definition. Constructs
788 ;; an advised definition from scratch if no verifiable cached advised
789 ;; definition is available and caches it.
790 ;; - Deactivation:
791 ;; Back-define an advised function to its original definition.
792 ;; - Update:
793 ;; Reactivate an advised function but only if its advice is currently
794 ;; active. This can be used to bring all currently advised function up
795 ;; to date with the current state of advice without also activating
796 ;; currently inactive functions.
797 ;; - Caching:
798 ;; Is the saving of an advised definition and an identifying cache-id so
799 ;; it can be reused, for example, for activation after deactivation.
800 ;; - Preactivation:
801 ;; Is the construction of an advised definition according to the current
802 ;; state of advice during byte-compilation of a file with a preactivating
803 ;; `defadvice'. That advised definition can then rather cheaply be used
804 ;; during activation without having to construct an advised definition
805 ;; from scratch at runtime.
806
807 ;; @@ Summary of interactive advice manipulation functions:
808 ;; ========================================================
809 ;; The following interactive functions can be used to manipulate the state
810 ;; of advised functions (all of them support completion on function names,
811 ;; advice classes and advice names):
812
813 ;; - ad-activate to activate the advice of a FUNCTION
814 ;; - ad-deactivate to deactivate the advice of a FUNCTION
815 ;; - ad-update to activate the advice of a FUNCTION unless it was not
816 ;; yet activated or is currently inactive.
817 ;; - ad-unadvise deactivates a FUNCTION and removes all of its advice
818 ;; information, hence, it cannot be activated again
819 ;; - ad-recover tries to redefine a FUNCTION to its original definition and
820 ;; discards all advice information (a low-level `ad-unadvise').
821 ;; Use only in emergencies.
822
823 ;; - ad-remove-advice removes a particular piece of advice of a FUNCTION.
824 ;; You still have to do call `ad-activate' or `ad-update' to
825 ;; activate the new state of advice.
826 ;; - ad-enable-advice enables a particular piece of advice of a FUNCTION.
827 ;; - ad-disable-advice disables a particular piece of advice of a FUNCTION.
828 ;; - ad-enable-regexp maps over all currently advised functions and enables
829 ;; every advice whose name contains a match for a regular
830 ;; expression.
831 ;; - ad-disable-regexp disables matching advices.
832
833 ;; - ad-activate-regexp activates all advised function with a matching advice
834 ;; - ad-deactivate-regexp deactivates all advised function with matching advice
835 ;; - ad-update-regexp updates all advised function with a matching advice
836 ;; - ad-activate-all activates all advised functions
837 ;; - ad-deactivate-all deactivates all advised functions
838 ;; - ad-update-all updates all advised functions
839 ;; - ad-unadvise-all unadvises all advised functions
840 ;; - ad-recover-all recovers all advised functions
841
842 ;; - ad-compile byte-compiles a function/macro if it is compilable.
843
844 ;; @@ Summary of forms with special meanings when used within an advice:
845 ;; =====================================================================
846 ;; ad-return-value name of the return value variable (get/settable)
847 ;; (ad-get-arg <pos>), (ad-get-args <pos>),
848 ;; (ad-set-arg <pos> <value>), (ad-set-args <pos> <value-list>)
849 ;; argument access text macros to get/set the values of
850 ;; actual arguments at a certain position
851 ;; ad-arg-bindings text macro that returns the actual names, values
852 ;; and types of the arguments as a list of bindings. The
853 ;; order of the bindings corresponds to the order of the
854 ;; arguments. The individual fields of every binding (name,
855 ;; value and type) can be accessed with the function
856 ;; `ad-arg-binding-field' (see example above).
857 ;; ad-do-it text macro that identifies the place where the original
858 ;; or wrapped definition should go in an around advice
859
860
861 ;; @ Foo games: An advice tutorial
862 ;; ===============================
863 ;; The following tutorial was created in Emacs 18.59. Left-justified
864 ;; s-expressions are input forms followed by one or more result forms.
865 ;; First we have to start the advice magic:
866 ;;
867 ;; (ad-start-advice)
868 ;; nil
869 ;;
870 ;; We start by defining an innocent looking function `foo' that simply
871 ;; adds 1 to its argument X:
872 ;;
873 ;; (defun foo (x)
874 ;; "Add 1 to X."
875 ;; (1+ x))
876 ;; foo
877 ;;
878 ;; (foo 3)
879 ;; 4
880 ;;
881 ;; @@ Defining a simple piece of advice:
882 ;; =====================================
883 ;; Now let's define the first piece of advice for `foo'. To do that we
884 ;; use the macro `defadvice' which takes a function name, a list of advice
885 ;; specifiers and a list of body forms as arguments. The first element of
886 ;; the advice specifiers is the class of the advice, the second is its name,
887 ;; the third its position and the rest are some flags. The class of our
888 ;; first advice is `before', its name is `fg-add2', its position among the
889 ;; currently defined before advices (none so far) is `first', and the advice
890 ;; will be `activate'ed immediately. Advice names are global symbols, hence,
891 ;; the name space conventions used for function names should be applied. All
892 ;; advice names in this tutorial will be prefixed with `fg' for `Foo Games'
893 ;; (because everybody has the right to be inconsistent all the function names
894 ;; used in this tutorial do NOT follow this convention).
895 ;;
896 ;; In the body of an advice we can refer to the argument variables of the
897 ;; original function by name. Here we add 1 to X so the effect of calling
898 ;; `foo' will be to actually add 2. All of the advice definitions below only
899 ;; have one body form for simplicity, but there is no restriction to that
900 ;; extent. Every piece of advice can have a documentation string which will
901 ;; be combined with the documentation of the original function.
902 ;;
903 ;; (defadvice foo (before fg-add2 first activate)
904 ;; "Add 2 to X."
905 ;; (setq x (1+ x)))
906 ;; foo
907 ;;
908 ;; (foo 3)
909 ;; 5
910 ;;
911 ;; @@ Specifying the position of an advice:
912 ;; ========================================
913 ;; Now we define the second before advice which will cancel the effect of
914 ;; the previous advice. This time we specify the position as 0 which is
915 ;; equivalent to `first'. A number can be used to specify the zero-based
916 ;; position of an advice among the list of advices in the same class. This
917 ;; time we already have one before advice hence the position specification
918 ;; actually has an effect. So, after the following definition the position
919 ;; of the previous advice will be 1 even though we specified it with `first'
920 ;; above, the reason for this is that the position argument is relative to
921 ;; the currently defined pieces of advice which by now has changed.
922 ;;
923 ;; (defadvice foo (before fg-cancel-add2 0 activate)
924 ;; "Again only add 1 to X."
925 ;; (setq x (1- x)))
926 ;; foo
927 ;;
928 ;; (foo 3)
929 ;; 4
930 ;;
931 ;; @@ Redefining a piece of advice:
932 ;; ================================
933 ;; Now we define an advice with the same class and same name but with a
934 ;; different position. Defining an advice in a class in which an advice with
935 ;; that name already exists is interpreted as a redefinition of that
936 ;; particular advice, in which case the position argument will be ignored
937 ;; and the previous position of the redefined piece of advice is used.
938 ;; Advice flags can be specified with non-ambiguous initial substrings, hence,
939 ;; from now on we'll use `act' instead of the verbose `activate'.
940 ;;
941 ;; (defadvice foo (before fg-cancel-add2 last act)
942 ;; "Again only add 1 to X."
943 ;; (setq x (1- x)))
944 ;; foo
945 ;;
946 ;; @@ Assembly of advised documentation:
947 ;; =====================================
948 ;; The documentation strings of the various pieces of advice are assembled
949 ;; in order which shows that advice `fg-cancel-add2' is still the first
950 ;; `before' advice even though we specified position `last' above:
951 ;;
952 ;; (documentation 'foo)
953 ;; "Add 1 to X.
954 ;;
955 ;; This function is advised with the following advice(s):
956 ;;
957 ;; fg-cancel-add2 (before):
958 ;; Again only add 1 to X.
959 ;;
960 ;; fg-add2 (before):
961 ;; Add 2 to X."
962 ;;
963 ;; @@ Advising interactive behavior:
964 ;; =================================
965 ;; We can make a function interactive (or change its interactive behavior)
966 ;; by specifying an interactive form in one of the before or around
967 ;; advices (there could also be body forms in this advice). The particular
968 ;; definition always assigns 5 as an argument to X which gives us 6 as a
969 ;; result when we call foo interactively:
970 ;;
971 ;; (defadvice foo (before fg-inter last act)
972 ;; "Use 5 as argument when called interactively."
973 ;; (interactive (list 5)))
974 ;; foo
975 ;;
976 ;; (call-interactively 'foo)
977 ;; 6
978 ;;
979 ;; If more than one advice have an interactive declaration, then the one of
980 ;; the advice with the smallest position will be used (before advices go
981 ;; before around and after advices), hence, the declaration below does
982 ;; not have any effect:
983 ;;
984 ;; (defadvice foo (before fg-inter2 last act)
985 ;; (interactive (list 6)))
986 ;; foo
987 ;;
988 ;; (call-interactively 'foo)
989 ;; 6
990 ;;
991 ;; Let's have a look at what the definition of `foo' looks like now
992 ;; (indentation added by hand for legibility):
993 ;;
994 ;; (symbol-function 'foo)
995 ;; (lambda (x)
996 ;; "$ad-doc: foo$"
997 ;; (interactive (list 5))
998 ;; (let (ad-return-value)
999 ;; (setq x (1- x))
1000 ;; (setq x (1+ x))
1001 ;; (setq ad-return-value (ad-Orig-foo x))
1002 ;; ad-return-value))
1003 ;;
1004 ;; @@ Around advices:
1005 ;; ==================
1006 ;; Now we'll try some `around' advices. An around advice is a wrapper around
1007 ;; the original definition. It can shadow or establish bindings for the
1008 ;; original definition, and it can look at and manipulate the value returned
1009 ;; by the original function. The position of the special keyword `ad-do-it'
1010 ;; specifies where the code of the original function will be executed. The
1011 ;; keyword can appear multiple times which will result in multiple calls of
1012 ;; the original function in the resulting advised code. Note, that if we don't
1013 ;; specify a position argument (i.e., `first', `last' or a number), then
1014 ;; `first' (or 0) is the default):
1015 ;;
1016 ;; (defadvice foo (around fg-times-2 act)
1017 ;; "First double X."
1018 ;; (let ((x (* x 2)))
1019 ;; ad-do-it))
1020 ;; foo
1021 ;;
1022 ;; (foo 3)
1023 ;; 7
1024 ;;
1025 ;; Around advices are assembled like onion skins where the around advice
1026 ;; with position 0 is the outermost skin and the advice at the last position
1027 ;; is the innermost skin which is directly wrapped around the call of the
1028 ;; original definition of the function. Hence, after the next `defadvice' we
1029 ;; will first multiply X by 2 then add 1 and then call the original
1030 ;; definition (i.e., add 1 again):
1031 ;;
1032 ;; (defadvice foo (around fg-add-1 last act)
1033 ;; "Add 1 to X."
1034 ;; (let ((x (1+ x)))
1035 ;; ad-do-it))
1036 ;; foo
1037 ;;
1038 ;; (foo 3)
1039 ;; 8
1040 ;;
1041 ;; Again, let's see what the definition of `foo' looks like so far:
1042 ;;
1043 ;; (symbol-function 'foo)
1044 ;; (lambda (x)
1045 ;; "$ad-doc: foo$"
1046 ;; (interactive (list 5))
1047 ;; (let (ad-return-value)
1048 ;; (setq x (1- x))
1049 ;; (setq x (1+ x))
1050 ;; (let ((x (* x 2)))
1051 ;; (let ((x (1+ x)))
1052 ;; (setq ad-return-value (ad-Orig-foo x))))
1053 ;; ad-return-value))
1054 ;;
1055 ;; @@ Controlling advice activation:
1056 ;; =================================
1057 ;; In every `defadvice' so far we have used the flag `activate' to activate
1058 ;; the advice immediately after its definition, and that's what we want in
1059 ;; most cases. However, if we define multiple pieces of advice for a single
1060 ;; function then activating every advice immediately is inefficient. A
1061 ;; better way to do this is to only activate the last defined advice.
1062 ;; For example:
1063 ;;
1064 ;; (defadvice foo (after fg-times-x)
1065 ;; "Multiply the result with X."
1066 ;; (setq ad-return-value (* ad-return-value x)))
1067 ;; foo
1068 ;;
1069 ;; This still yields the same result as before:
1070 ;; (foo 3)
1071 ;; 8
1072 ;;
1073 ;; Now we define another advice and activate which will also activate the
1074 ;; previous advice `fg-times-x'. Note the use of the special variable
1075 ;; `ad-return-value' in the body of the advice which is set to the result of
1076 ;; the original function. If we change its value then the value returned by
1077 ;; the advised function will be changed accordingly:
1078 ;;
1079 ;; (defadvice foo (after fg-times-x-again act)
1080 ;; "Again multiply the result with X."
1081 ;; (setq ad-return-value (* ad-return-value x)))
1082 ;; foo
1083 ;;
1084 ;; Now the advices have an effect:
1085 ;;
1086 ;; (foo 3)
1087 ;; 72
1088 ;;
1089 ;; @@ Protecting advice execution:
1090 ;; ===============================
1091 ;; Once in a while we define an advice to perform some cleanup action,
1092 ;; for example:
1093 ;;
1094 ;; (defadvice foo (after fg-cleanup last act)
1095 ;; "Do some cleanup."
1096 ;; (print "Let's clean up now!"))
1097 ;; foo
1098 ;;
1099 ;; However, in case of an error the cleanup won't be performed:
1100 ;;
1101 ;; (condition-case error
1102 ;; (foo t)
1103 ;; (error 'error-in-foo))
1104 ;; error-in-foo
1105 ;;
1106 ;; To make sure a certain piece of advice gets executed even if some error or
1107 ;; non-local exit occurred in any preceding code, we can protect it by using
1108 ;; the `protect' keyword. (if any of the around advices is protected then the
1109 ;; whole around advice onion will be protected):
1110 ;;
1111 ;; (defadvice foo (after fg-cleanup prot act)
1112 ;; "Do some protected cleanup."
1113 ;; (print "Let's clean up now!"))
1114 ;; foo
1115 ;;
1116 ;; Now the cleanup form will be executed even in case of an error:
1117 ;;
1118 ;; (condition-case error
1119 ;; (foo t)
1120 ;; (error 'error-in-foo))
1121 ;; "Let's clean up now!"
1122 ;; error-in-foo
1123 ;;
1124 ;; Again, let's see what `foo' looks like:
1125 ;;
1126 ;; (symbol-function 'foo)
1127 ;; (lambda (x)
1128 ;; "$ad-doc: foo$"
1129 ;; (interactive (list 5))
1130 ;; (let (ad-return-value)
1131 ;; (unwind-protect
1132 ;; (progn (setq x (1- x))
1133 ;; (setq x (1+ x))
1134 ;; (let ((x (* x 2)))
1135 ;; (let ((x (1+ x)))
1136 ;; (setq ad-return-value (ad-Orig-foo x))))
1137 ;; (setq ad-return-value (* ad-return-value x))
1138 ;; (setq ad-return-value (* ad-return-value x)))
1139 ;; (print "Let's clean up now!"))
1140 ;; ad-return-value))
1141 ;;
1142 ;; @@ Compilation of advised definitions:
1143 ;; ======================================
1144 ;; Finally, we can specify the `compile' keyword in a `defadvice' to say
1145 ;; that we want the resulting advised function to be byte-compiled
1146 ;; (`compile' will be ignored unless we also specified `activate'):
1147 ;;
1148 ;; (defadvice foo (after fg-cleanup prot act comp)
1149 ;; "Do some protected cleanup."
1150 ;; (print "Let's clean up now!"))
1151 ;; foo
1152 ;;
1153 ;; Now `foo' is byte-compiled:
1154 ;;
1155 ;; (symbol-function 'foo)
1156 ;; (lambda (x)
1157 ;; "$ad-doc: foo$"
1158 ;; (interactive (byte-code "....." [5] 1))
1159 ;; (byte-code "....." [ad-return-value x nil ((byte-code "....." [print "Let's clean up now!"] 2)) * 2 ad-Orig-foo] 6))
1160 ;;
1161 ;; (foo 3)
1162 ;; "Let's clean up now!"
1163 ;; 72
1164 ;;
1165 ;; @@ Enabling and disabling pieces of advice:
1166 ;; ===========================================
1167 ;; Once in a while it is desirable to temporarily disable a piece of advice
1168 ;; so that it won't be considered during activation, for example, if two
1169 ;; different packages advise the same function and one wants to temporarily
1170 ;; neutralize the effect of the advice of one of the packages.
1171 ;;
1172 ;; The following disables the after advice `fg-times-x' in the function `foo'.
1173 ;; All that does is to change a flag for this particular advice. All the
1174 ;; other information defining it will be left unchanged (e.g., its relative
1175 ;; position in this advice class, etc.).
1176 ;;
1177 ;; (ad-disable-advice 'foo 'after 'fg-times-x)
1178 ;; nil
1179 ;;
1180 ;; For this to have an effect we have to activate `foo':
1181 ;;
1182 ;; (ad-activate 'foo)
1183 ;; foo
1184 ;;
1185 ;; (foo 3)
1186 ;; "Let's clean up now!"
1187 ;; 24
1188 ;;
1189 ;; If we want to disable all multiplication advices in `foo' we can use a
1190 ;; regular expression that matches the names of such advices. Actually, any
1191 ;; advice name that contains a match for the regular expression will be
1192 ;; called a match. A special advice class `any' can be used to consider
1193 ;; all advice classes:
1194 ;;
1195 ;; (ad-disable-advice 'foo 'any "^fg-.*times")
1196 ;; nil
1197 ;;
1198 ;; (ad-activate 'foo)
1199 ;; foo
1200 ;;
1201 ;; (foo 3)
1202 ;; "Let's clean up now!"
1203 ;; 5
1204 ;;
1205 ;; To enable the disabled advice we could use either `ad-enable-advice'
1206 ;; similar to `ad-disable-advice', or as an alternative `ad-enable-regexp'
1207 ;; which will enable matching advices in ALL currently advised functions.
1208 ;; Hence, this can be used to dis/enable advices made by a particular
1209 ;; package to a set of functions as long as that package obeys standard
1210 ;; advice name conventions. We prefixed all advice names with `fg-', hence
1211 ;; the following will do the trick (`ad-enable-regexp' returns the number
1212 ;; of matched advices):
1213 ;;
1214 ;; (ad-enable-regexp "^fg-")
1215 ;; 9
1216 ;;
1217 ;; The following will activate all currently active advised functions that
1218 ;; contain some advice matched by the regular expression. This is a save
1219 ;; way to update the activation of advised functions whose advice changed
1220 ;; in some way or other without accidentally also activating currently
1221 ;; inactive functions:
1222 ;;
1223 ;; (ad-update-regexp "^fg-")
1224 ;; nil
1225 ;;
1226 ;; (foo 3)
1227 ;; "Let's clean up now!"
1228 ;; 72
1229 ;;
1230 ;; Another use for the dis/enablement mechanism is to define a piece of advice
1231 ;; and keep it "dormant" until a particular condition is satisfied, i.e., until
1232 ;; then the advice will not be used during activation. The `disable' flag lets
1233 ;; one do that with `defadvice':
1234 ;;
1235 ;; (defadvice foo (before fg-1-more dis)
1236 ;; "Add yet 1 more."
1237 ;; (setq x (1+ x)))
1238 ;; foo
1239 ;;
1240 ;; (ad-activate 'foo)
1241 ;; foo
1242 ;;
1243 ;; (foo 3)
1244 ;; "Let's clean up now!"
1245 ;; 72
1246 ;;
1247 ;; (ad-enable-advice 'foo 'before 'fg-1-more)
1248 ;; nil
1249 ;;
1250 ;; (ad-activate 'foo)
1251 ;; foo
1252 ;;
1253 ;; (foo 3)
1254 ;; "Let's clean up now!"
1255 ;; 160
1256 ;;
1257 ;; @@ Caching:
1258 ;; ===========
1259 ;; Advised definitions get cached to allow efficient activation/deactivation
1260 ;; without having to reconstruct them if nothing in the advice-info of a
1261 ;; function has changed. The following idiom can be used to temporarily
1262 ;; deactivate functions that have a piece of advice defined by a certain
1263 ;; package (we save the old definition to check out caching):
1264 ;;
1265 ;; (setq old-definition (symbol-function 'foo))
1266 ;; (lambda (x) ....)
1267 ;;
1268 ;; (ad-deactivate-regexp "^fg-")
1269 ;; nil
1270 ;;
1271 ;; (foo 3)
1272 ;; 4
1273 ;;
1274 ;; (ad-activate-regexp "^fg-")
1275 ;; nil
1276 ;;
1277 ;; (eq old-definition (symbol-function 'foo))
1278 ;; t
1279 ;;
1280 ;; (foo 3)
1281 ;; "Let's clean up now!"
1282 ;; 160
1283 ;;
1284 ;; @@ Forward advice:
1285 ;; ==================
1286 ;; To enable automatic activation of forward advice we first have to set
1287 ;; `ad-activate-on-definition' to t and restart advice:
1288 ;;
1289 ;; (setq ad-activate-on-definition t)
1290 ;; t
1291 ;;
1292 ;; (ad-start-advice)
1293 ;; (ad-activate-defined-function)
1294 ;;
1295 ;; Let's define a piece of advice for an undefined function:
1296 ;;
1297 ;; (defadvice bar (before fg-sub-1-more act)
1298 ;; "Subtract one more from X."
1299 ;; (setq x (1- x)))
1300 ;; bar
1301 ;;
1302 ;; `bar' is not yet defined:
1303 ;; (fboundp 'bar)
1304 ;; nil
1305 ;;
1306 ;; Now we define it and the forward advice will get activated (only because
1307 ;; `ad-activate-on-definition' was t when we started advice above with
1308 ;; `ad-start-advice'):
1309 ;;
1310 ;; (defun bar (x)
1311 ;; "Subtract 1 from X."
1312 ;; (1- x))
1313 ;; bar
1314 ;;
1315 ;; (bar 4)
1316 ;; 2
1317 ;;
1318 ;; Redefinition will activate any available advice if the value of
1319 ;; `ad-redefinition-action' is either `warn', `accept' or `discard':
1320 ;;
1321 ;; (defun bar (x)
1322 ;; "Subtract 2 from X."
1323 ;; (- x 2))
1324 ;; bar
1325 ;;
1326 ;; (bar 4)
1327 ;; 1
1328 ;;
1329 ;; @@ Preactivation:
1330 ;; =================
1331 ;; Constructing advised definitions is moderately expensive, hence, it is
1332 ;; desirable to have a way to construct them at byte-compile time.
1333 ;; Preactivation is a mechanism that allows one to do that.
1334 ;;
1335 ;; (defun fie (x)
1336 ;; "Multiply X by 2."
1337 ;; (* x 2))
1338 ;; fie
1339 ;;
1340 ;; (defadvice fie (before fg-times-4 preact)
1341 ;; "Multiply X by 4."
1342 ;; (setq x (* x 2)))
1343 ;; fie
1344 ;;
1345 ;; This advice did not affect `fie'...
1346 ;;
1347 ;; (fie 2)
1348 ;; 4
1349 ;;
1350 ;; ...but it constructed a cached definition that will be used once `fie' gets
1351 ;; activated as long as its current advice state is the same as it was during
1352 ;; preactivation:
1353 ;;
1354 ;; (setq cached-definition (ad-get-cache-definition 'fie))
1355 ;; (lambda (x) ....)
1356 ;;
1357 ;; (ad-activate 'fie)
1358 ;; fie
1359 ;;
1360 ;; (eq cached-definition (symbol-function 'fie))
1361 ;; t
1362 ;;
1363 ;; (fie 2)
1364 ;; 8
1365 ;;
1366 ;; If you put a preactivating `defadvice' into a Lisp file that gets byte-
1367 ;; compiled then the constructed advised definition will get compiled by
1368 ;; the byte-compiler. For that to occur in a v18 Emacs you had to put the
1369 ;; `defadvice' inside a `defun' because the v18 compiler did not compile
1370 ;; top-level forms other than `defun' or `defmacro', for example,
1371 ;;
1372 ;; (defun fg-defadvice-fum ()
1373 ;; (defadvice fum (before fg-times-4 preact act)
1374 ;; "Multiply X by 4."
1375 ;; (setq x (* x 2))))
1376 ;; fg-defadvice-fum
1377 ;;
1378 ;; So far, no `defadvice' for `fum' got executed, but when we compile
1379 ;; `fg-defadvice-fum' the `defadvice' will be expanded by the byte compiler.
1380 ;; In order for preactivation to be effective we have to have a proper
1381 ;; definition of `fum' around at preactivation time, hence, we define it now:
1382 ;;
1383 ;; (defun fum (x)
1384 ;; "Multiply X by 2."
1385 ;; (* x 2))
1386 ;; fum
1387 ;;
1388 ;; Now we compile the defining function which will construct an advised
1389 ;; definition during expansion of the `defadvice', compile it and store it
1390 ;; as part of the compiled `fg-defadvice-fum':
1391 ;;
1392 ;; (ad-compile-function 'fg-defadvice-fum)
1393 ;; (lambda nil (byte-code ...))
1394 ;;
1395 ;; `fum' is still completely unaffected:
1396 ;;
1397 ;; (fum 2)
1398 ;; 4
1399 ;;
1400 ;; (ad-get-advice-info 'fum)
1401 ;; nil
1402 ;;
1403 ;; (fg-defadvice-fum)
1404 ;; fum
1405 ;;
1406 ;; Now the advised version of `fum' is compiled because the compiled definition
1407 ;; constructed during preactivation was used, even though we did not specify
1408 ;; the `compile' flag:
1409 ;;
1410 ;; (symbol-function 'fum)
1411 ;; (lambda (x)
1412 ;; "$ad-doc: fum$"
1413 ;; (byte-code "....." [ad-return-value x nil * 2 ad-Orig-fum] 4))
1414 ;;
1415 ;; (fum 2)
1416 ;; 8
1417 ;;
1418 ;; A preactivated definition will only be used if it matches the current
1419 ;; function definition and advice information. If it does not match it
1420 ;; will simply be discarded and a new advised definition will be constructed
1421 ;; from scratch. For example, let's first remove all advice-info for `fum':
1422 ;;
1423 ;; (ad-unadvise 'fum)
1424 ;; (("fie") ("bar") ("foo") ...)
1425 ;;
1426 ;; And now define a new piece of advice:
1427 ;;
1428 ;; (defadvice fum (before fg-interactive act)
1429 ;; "Make fum interactive."
1430 ;; (interactive "nEnter x: "))
1431 ;; fum
1432 ;;
1433 ;; When we now try to use a preactivation it will not be used because the
1434 ;; current advice state is different from the one at preactivation time. This
1435 ;; is no tragedy, everything will work as expected just not as efficient,
1436 ;; because a new advised definition has to be constructed from scratch:
1437 ;;
1438 ;; (fg-defadvice-fum)
1439 ;; fum
1440 ;;
1441 ;; A new uncompiled advised definition got constructed:
1442 ;;
1443 ;; (ad-compiled-p (symbol-function 'fum))
1444 ;; nil
1445 ;;
1446 ;; (fum 2)
1447 ;; 8
1448 ;;
1449 ;; MORAL: To get all the efficiency out of preactivation the function
1450 ;; definition and advice state at preactivation time must be the same as the
1451 ;; state at activation time. Preactivation does work with forward advice, all
1452 ;; that's necessary is that the definition of the forward advised function is
1453 ;; available when the `defadvice' with the preactivation gets compiled.
1454 ;;
1455 ;; @@ Portable argument access:
1456 ;; ============================
1457 ;; So far, we always used the actual argument variable names to access an
1458 ;; argument in a piece of advice. For many advice applications this is
1459 ;; perfectly ok and keeps advices simple. However, it decreases portability
1460 ;; of advices because it assumes specific argument variable names. For example,
1461 ;; if one advises a subr such as `eval-region' which then gets redefined by
1462 ;; some package (e.g., edebug) into a function with different argument names,
1463 ;; then a piece of advice written for `eval-region' that was written with
1464 ;; the subr arguments in mind will break.
1465 ;;
1466 ;; Argument access text macros allow one to access arguments of an advised
1467 ;; function in a portable way without having to worry about all these
1468 ;; possibilities. These macros will be translated into the proper access forms
1469 ;; at activation time, hence, argument access will be as efficient as if
1470 ;; the arguments had been used directly in the definition of the advice.
1471 ;;
1472 ;; (defun fuu (x y z)
1473 ;; "Add 3 numbers."
1474 ;; (+ x y z))
1475 ;; fuu
1476 ;;
1477 ;; (fuu 1 1 1)
1478 ;; 3
1479 ;;
1480 ;; Argument access macros specify actual arguments at a certain position.
1481 ;; Position 0 access the first actual argument, position 1 the second etc.
1482 ;; For example, the following advice adds 1 to each of the 3 arguments:
1483 ;;
1484 ;; (defadvice fuu (before fg-add-1-to-all act)
1485 ;; "Adds 1 to all arguments."
1486 ;; (ad-set-arg 0 (1+ (ad-get-arg 0)))
1487 ;; (ad-set-arg 1 (1+ (ad-get-arg 1)))
1488 ;; (ad-set-arg 2 (1+ (ad-get-arg 2))))
1489 ;; fuu
1490 ;;
1491 ;; (fuu 1 1 1)
1492 ;; 6
1493 ;;
1494 ;; Now suppose somebody redefines `fuu' with a rest argument. Our advice
1495 ;; will still work because we used access macros (note, that automatic
1496 ;; advice activation is still in effect, hence, the redefinition of `fuu'
1497 ;; will automatically activate all its advice):
1498 ;;
1499 ;; (defun fuu (&rest numbers)
1500 ;; "Add NUMBERS."
1501 ;; (apply '+ numbers))
1502 ;; fuu
1503 ;;
1504 ;; (fuu 1 1 1)
1505 ;; 6
1506 ;;
1507 ;; (fuu 1 1 1 1 1 1)
1508 ;; 9
1509 ;;
1510 ;; What's important to notice is that argument access macros access actual
1511 ;; arguments regardless of how they got distributed onto argument variables.
1512 ;; In Emacs Lisp the semantics of an actual argument is determined purely
1513 ;; by position, hence, as long as nobody changes the semantics of what a
1514 ;; certain actual argument at a certain position means the access macros
1515 ;; will do the right thing.
1516 ;;
1517 ;; Because of &rest arguments we need a second kind of access macro that
1518 ;; can access all actual arguments starting from a certain position:
1519 ;;
1520 ;; (defadvice fuu (before fg-print-args act)
1521 ;; "Print all arguments."
1522 ;; (print (ad-get-args 0)))
1523 ;; fuu
1524 ;;
1525 ;; (fuu 1 2 3 4 5)
1526 ;; (1 2 3 4 5)
1527 ;; 18
1528 ;;
1529 ;; (defadvice fuu (before fg-set-args act)
1530 ;; "Swaps 2nd and 3rd arg and discards all the rest."
1531 ;; (ad-set-args 1 (list (ad-get-arg 2) (ad-get-arg 1))))
1532 ;; fuu
1533 ;;
1534 ;; (fuu 1 2 3 4 4 4 4 4 4)
1535 ;; (1 3 2)
1536 ;; 9
1537 ;;
1538 ;; (defun fuu (x y z)
1539 ;; "Add 3 numbers."
1540 ;; (+ x y z))
1541 ;;
1542 ;; (fuu 1 2 3)
1543 ;; (1 3 2)
1544 ;; 9
1545 ;;
1546 ;; @@ Defining the argument list of an advised function:
1547 ;; =====================================================
1548 ;; Once in a while it might be desirable to advise a function and additionally
1549 ;; give it an extra argument that controls the advised code, for example, one
1550 ;; might want to make an interactive function sensitive to a prefix argument.
1551 ;; For such cases `defadvice' allows the specification of an argument list
1552 ;; for the advised function. Similar to the redefinition of interactive
1553 ;; behavior, the first argument list specification found in the list of before/
1554 ;; around/after advices will be used. Of course, the specified argument list
1555 ;; should be downward compatible with the original argument list, otherwise
1556 ;; functions that call the advised function with the original argument list
1557 ;; in mind will break.
1558 ;;
1559 ;; (defun fii (x)
1560 ;; "Add 1 to X."
1561 ;; (1+ x))
1562 ;; fii
1563 ;;
1564 ;; Now we advise `fii' to use an optional second argument that controls the
1565 ;; amount of incrementing. A list following the (optional) position
1566 ;; argument of the advice will be interpreted as an argument list
1567 ;; specification. This means you cannot specify an empty argument list, and
1568 ;; why would you want to anyway?
1569 ;;
1570 ;; (defadvice fii (before fg-inc-x (x &optional incr) act)
1571 ;; "Increment X by INCR (default is 1)."
1572 ;; (setq x (+ x (1- (or incr 1)))))
1573 ;; fii
1574 ;;
1575 ;; (fii 3)
1576 ;; 4
1577 ;;
1578 ;; (fii 3 2)
1579 ;; 5
1580 ;;
1581 ;; @@ Advising interactive subrs:
1582 ;; ==============================
1583 ;; For the most part there is no difference between advising functions and
1584 ;; advising subrs. There is one situation though where one might have to write
1585 ;; slightly different advice code for subrs than for functions. This case
1586 ;; arises when one wants to access subr arguments in a before/around advice
1587 ;; when the arguments were determined by an interactive call to the subr.
1588 ;; Advice cannot determine what `interactive' form determines the interactive
1589 ;; behavior of the subr, hence, when it calls the original definition in an
1590 ;; interactive subr invocation it has to use `call-interactively' to generate
1591 ;; the proper interactive behavior. Thus up to that call the arguments of the
1592 ;; interactive subr will be nil. For example, the following advice for
1593 ;; `kill-buffer' will not work in an interactive invocation...
1594 ;;
1595 ;; (defadvice kill-buffer (before fg-kill-buffer-hook first act preact comp)
1596 ;; (my-before-kill-buffer-hook (ad-get-arg 0)))
1597 ;; kill-buffer
1598 ;;
1599 ;; ...because the buffer argument will be nil in that case. The way out of
1600 ;; this dilemma is to provide an `interactive' specification that mirrors
1601 ;; the interactive behavior of the unadvised subr, for example, the following
1602 ;; will do the right thing even when `kill-buffer' is called interactively:
1603 ;;
1604 ;; (defadvice kill-buffer (before fg-kill-buffer-hook first act preact comp)
1605 ;; (interactive "bKill buffer: ")
1606 ;; (my-before-kill-buffer-hook (ad-get-arg 0)))
1607 ;; kill-buffer
1608 ;;
1609 ;; @@ Advising macros:
1610 ;; ===================
1611 ;; Advising macros is slightly different because there are two significant
1612 ;; time points in the invocation of a macro: Expansion and evaluation time.
1613 ;; For an advised macro instead of evaluating the original definition we
1614 ;; use `macroexpand', that is, changing argument values and binding
1615 ;; environments by pieces of advice has an affect during macro expansion
1616 ;; but not necessarily during evaluation. In particular, any side effects
1617 ;; of pieces of advice will occur during macro expansion. To also affect
1618 ;; the behavior during evaluation time one has to change the value of
1619 ;; `ad-return-value' in a piece of after advice. For example:
1620 ;;
1621 ;; (defmacro foom (x)
1622 ;; (` (list (, x))))
1623 ;; foom
1624 ;;
1625 ;; (foom '(a))
1626 ;; ((a))
1627 ;;
1628 ;; (defadvice foom (before fg-print-x act)
1629 ;; "Print the value of X."
1630 ;; (print x))
1631 ;; foom
1632 ;;
1633 ;; The following works as expected because evaluation immediately follows
1634 ;; macro expansion:
1635 ;;
1636 ;; (foom '(a))
1637 ;; (quote (a))
1638 ;; ((a))
1639 ;;
1640 ;; However, the printing happens during expansion (or byte-compile) time:
1641 ;;
1642 ;; (macroexpand '(foom '(a)))
1643 ;; (quote (a))
1644 ;; (list (quote (a)))
1645 ;;
1646 ;; If we want it to happen during evaluation time we have to do the
1647 ;; following (first remove the old advice):
1648 ;;
1649 ;; (ad-remove-advice 'foom 'before 'fg-print-x)
1650 ;; nil
1651 ;;
1652 ;; (defadvice foom (after fg-print-x act)
1653 ;; "Print the value of X."
1654 ;; (setq ad-return-value
1655 ;; (` (progn (print (, x))
1656 ;; (, ad-return-value)))))
1657 ;; foom
1658 ;;
1659 ;; (macroexpand '(foom '(a)))
1660 ;; (progn (print (quote (a))) (list (quote (a))))
1661 ;;
1662 ;; (foom '(a))
1663 ;; (a)
1664 ;; ((a))
1665 ;;
1666 ;; While this method might seem somewhat cumbersome, it is very general
1667 ;; because it allows one to influence macro expansion as well as evaluation.
1668 ;; In general, advising macros should be a rather rare activity anyway, in
1669 ;; particular, because compile-time macro expansion takes away a lot of the
1670 ;; flexibility and effectiveness of the advice mechanism. Macros that were
1671 ;; compile-time expanded before the advice was activated will of course never
1672 ;; exhibit the advised behavior.
1673 ;;
1674 ;; @@ Advising special forms:
1675 ;; ==========================
1676 ;; Now for something that should be even more rare than advising macros:
1677 ;; Advising special forms. Because special forms are irregular in their
1678 ;; argument evaluation behavior (e.g., `setq' evaluates the second but not
1679 ;; the first argument) they have to be advised into macros. A dangerous
1680 ;; consequence of this is that the byte-compiler will not recognize them
1681 ;; as special forms anymore (well, in most cases) and use their expansion
1682 ;; rather than the proper byte-code. Also, because the original definition
1683 ;; of a special form cannot be `funcall'ed, `eval' has to be used instead
1684 ;; which is less efficient.
1685 ;;
1686 ;; MORAL: Do not advise special forms unless you are completely sure about
1687 ;; what you are doing (some of the forward advice behavior is
1688 ;; implemented via advice of the special forms `defun' and `defmacro').
1689 ;; As a safety measure one should always do `ad-deactivate-all' before
1690 ;; one byte-compiles a file to avoid any interference of advised
1691 ;; special forms.
1692 ;;
1693 ;; Apart from the safety concerns advising special forms is not any different
1694 ;; from advising plain functions or subrs.
1695
1696
1697 ;;; Code:
1698
1699 ;; @ Advice implementation:
1700 ;; ========================
1701
1702 ;; @@ Compilation idiosyncrasies:
1703 ;; ==============================
1704
1705 ;; `defadvice' expansion needs quite a few advice functions and variables,
1706 ;; hence, I need to preload the file before it can be compiled. To avoid
1707 ;; interference of bogus compiled files I always preload the source file:
1708 (provide 'advice-preload)
1709 ;; During a normal load this is a noop:
1710 (require 'advice-preload "advice.el")
1711 (require 'macroexp)
1712 ;; At run-time also, since ad-do-advised-functions returns code that uses it.
1713 (require 'cl-lib)
1714
1715 ;; @@ Variable definitions:
1716 ;; ========================
1717
1718 (defgroup advice nil
1719 "An overloading mechanism for Emacs Lisp functions."
1720 :prefix "ad-"
1721 :link '(custom-manual "(elisp)Advising Functions")
1722 :group 'lisp)
1723
1724 (defconst ad-version "2.14")
1725
1726 ;;;###autoload
1727 (defcustom ad-redefinition-action 'warn
1728 "Defines what to do with redefinitions during Advice de/activation.
1729 Redefinition occurs if a previously activated function that already has an
1730 original definition associated with it gets redefined and then de/activated.
1731 In such a case we can either accept the current definition as the new
1732 original definition, discard the current definition and replace it with the
1733 old original, or keep it and raise an error. The values `accept', `discard',
1734 `error' or `warn' govern what will be done. `warn' is just like `accept' but
1735 it additionally prints a warning message. All other values will be
1736 interpreted as `error'."
1737 :type '(choice (const accept) (const discard) (const warn)
1738 (other :tag "error" error))
1739 :group 'advice)
1740
1741 ;;;###autoload
1742 (defcustom ad-default-compilation-action 'maybe
1743 "Defines whether to compile advised definitions during activation.
1744 A value of `always' will result in unconditional compilation, `never' will
1745 always avoid compilation, `maybe' will compile if the byte-compiler is already
1746 loaded, and `like-original' will compile if the original definition of the
1747 advised function is compiled or a built-in function. Every other value will
1748 be interpreted as `maybe'. This variable will only be considered if the
1749 COMPILE argument of `ad-activate' was supplied as nil."
1750 :type '(choice (const always) (const never) (const like-original)
1751 (other :tag "maybe" maybe))
1752 :group 'advice)
1753
1754
1755
1756 ;; @@ Some utilities:
1757 ;; ==================
1758
1759 ;; We don't want the local arguments to interfere with anything
1760 ;; referenced in the supplied functions => the cryptic casing:
1761 (defun ad-substitute-tree (sUbTrEe-TeSt fUnCtIoN tReE)
1762 "Substitute qualifying subTREEs with result of FUNCTION(subTREE).
1763 Only proper subtrees are considered, for example, if TREE is (1 (2 (3)) 4)
1764 then the subtrees will be 1 (2 (3)) 2 (3) 3 4, dotted structures are
1765 allowed too. Once a qualifying subtree has been found its subtrees will
1766 not be considered anymore. (ad-substitute-tree 'atom 'identity tree)
1767 generates a copy of TREE."
1768 (cond ((consp tReE)
1769 (cons (if (funcall sUbTrEe-TeSt (car tReE))
1770 (funcall fUnCtIoN (car tReE))
1771 (if (consp (car tReE))
1772 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN (car tReE))
1773 (car tReE)))
1774 (ad-substitute-tree sUbTrEe-TeSt fUnCtIoN (cdr tReE))))
1775 ((funcall sUbTrEe-TeSt tReE)
1776 (funcall fUnCtIoN tReE))
1777 (t tReE)))
1778
1779 ;; @@ Advice info access fns:
1780 ;; ==========================
1781
1782 ;; Advice information for a particular function is stored on the
1783 ;; advice-info property of the function symbol. It is stored as an
1784 ;; alist of the following format:
1785 ;;
1786 ;; ((active . t/nil)
1787 ;; (before adv1 adv2 ...)
1788 ;; (around adv1 adv2 ...)
1789 ;; (after adv1 adv2 ...)
1790 ;; (activation adv1 adv2 ...)
1791 ;; (deactivation adv1 adv2 ...)
1792 ;; (origname . <symbol fbound to origdef>)
1793 ;; (cache . (<advised-definition> . <id>)))
1794
1795 ;; List of currently advised though not necessarily activated functions
1796 ;; (this list is maintained as a completion table):
1797 (defvar ad-advised-functions nil)
1798
1799 (defmacro ad-pushnew-advised-function (function)
1800 "Add FUNCTION to `ad-advised-functions' unless its already there."
1801 `(if (not (assoc (symbol-name ,function) ad-advised-functions))
1802 (setq ad-advised-functions
1803 (cons (list (symbol-name ,function))
1804 ad-advised-functions))))
1805
1806 (defmacro ad-pop-advised-function (function)
1807 "Remove FUNCTION from `ad-advised-functions'."
1808 `(setq ad-advised-functions
1809 (delq (assoc (symbol-name ,function) ad-advised-functions)
1810 ad-advised-functions)))
1811
1812 (defmacro ad-do-advised-functions (varform &rest body)
1813 "`dolist'-style iterator that maps over advised functions.
1814 \(ad-do-advised-functions (VAR)
1815 BODY-FORM...)
1816 On each iteration VAR will be bound to the name of an advised function
1817 \(a symbol)."
1818 (declare (indent 1))
1819 `(cl-dolist (,(car varform) ad-advised-functions)
1820 (setq ,(car varform) (intern (car ,(car varform))))
1821 ,@body))
1822
1823 (defun ad-get-advice-info (function)
1824 (get function 'ad-advice-info))
1825
1826 (defmacro ad-get-advice-info-macro (function)
1827 `(get ,function 'ad-advice-info))
1828
1829 (defsubst ad-set-advice-info (function advice-info)
1830 (cond
1831 (advice-info
1832 (add-function :around (get function 'defalias-fset-function)
1833 #'ad--defalias-fset))
1834 ((get function 'defalias-fset-function)
1835 (remove-function (get function 'defalias-fset-function)
1836 #'ad--defalias-fset)))
1837 (put function 'ad-advice-info advice-info))
1838
1839 (defmacro ad-copy-advice-info (function)
1840 `(copy-tree (get ,function 'ad-advice-info)))
1841
1842 (defmacro ad-is-advised (function)
1843 "Return non-nil if FUNCTION has any advice info associated with it.
1844 This does not mean that the advice is also active."
1845 `(ad-get-advice-info-macro ,function))
1846
1847 (defun ad-initialize-advice-info (function)
1848 "Initialize the advice info for FUNCTION.
1849 Assumes that FUNCTION has not yet been advised."
1850 (ad-pushnew-advised-function function)
1851 (ad-set-advice-info function (list (cons 'active nil))))
1852
1853 (defmacro ad-get-advice-info-field (function field)
1854 "Retrieve the value of the advice info FIELD of FUNCTION."
1855 `(cdr (assq ,field (ad-get-advice-info-macro ,function))))
1856
1857 (defun ad-set-advice-info-field (function field value)
1858 "Destructively modify VALUE of the advice info FIELD of FUNCTION."
1859 (and (ad-is-advised function)
1860 (cond ((assq field (ad-get-advice-info-macro function))
1861 ;; A field with that name is already present:
1862 (rplacd (assq field (ad-get-advice-info-macro function)) value))
1863 (t;; otherwise, create a new field with that name:
1864 (nconc (ad-get-advice-info-macro function)
1865 (list (cons field value)))))))
1866
1867 ;; Don't make this a macro so we can use it as a predicate:
1868 (defun ad-is-active (function)
1869 "Return non-nil if FUNCTION is advised and activated."
1870 (ad-get-advice-info-field function 'active))
1871
1872
1873 ;; @@ Access fns for single pieces of advice and related predicates:
1874 ;; =================================================================
1875
1876 (defun ad-make-advice (name protect enable definition)
1877 "Constructs single piece of advice to be stored in some advice-info.
1878 NAME should be a non-nil symbol, PROTECT and ENABLE should each be
1879 either t or nil, and DEFINITION should be a list of the form
1880 `(advice lambda ARGLIST [DOCSTRING] [INTERACTIVE-FORM] BODY...)'."
1881 (list name protect enable definition))
1882
1883 ;; ad-find-advice uses the alist structure directly ->
1884 ;; change if this data structure changes!!
1885 (defmacro ad-advice-name (advice)
1886 (list 'car advice))
1887 (defmacro ad-advice-protected (advice)
1888 (list 'nth 1 advice))
1889 (defmacro ad-advice-enabled (advice)
1890 (list 'nth 2 advice))
1891 (defmacro ad-advice-definition (advice)
1892 (list 'nth 3 advice))
1893
1894 (defun ad-advice-set-enabled (advice flag)
1895 (rplaca (cdr (cdr advice)) flag))
1896
1897 (defun ad-class-p (thing)
1898 (memq thing ad-advice-classes))
1899 (defun ad-name-p (thing)
1900 (and thing (symbolp thing)))
1901 (defun ad-position-p (thing)
1902 (or (natnump thing)
1903 (memq thing '(first last))))
1904
1905
1906 ;; @@ Advice access functions:
1907 ;; ===========================
1908
1909 ;; List of defined advice classes:
1910 (defvar ad-advice-classes '(before around after activation deactivation))
1911
1912 (defun ad-has-enabled-advice (function class)
1913 "True if at least one of FUNCTION's advices in CLASS is enabled."
1914 (cl-dolist (advice (ad-get-advice-info-field function class))
1915 (if (ad-advice-enabled advice) (cl-return t))))
1916
1917 (defun ad-has-redefining-advice (function)
1918 "True if FUNCTION's advice info defines at least 1 redefining advice.
1919 Redefining advices affect the construction of an advised definition."
1920 (and (ad-is-advised function)
1921 (or (ad-has-enabled-advice function 'before)
1922 (ad-has-enabled-advice function 'around)
1923 (ad-has-enabled-advice function 'after))))
1924
1925 (defun ad-has-any-advice (function)
1926 "True if the advice info of FUNCTION defines at least one advice."
1927 (and (ad-is-advised function)
1928 (cl-dolist (class ad-advice-classes)
1929 (if (ad-get-advice-info-field function class)
1930 (cl-return t)))))
1931
1932 (defun ad-get-enabled-advices (function class)
1933 "Return the list of enabled advices of FUNCTION in CLASS."
1934 (let (enabled-advices)
1935 (dolist (advice (ad-get-advice-info-field function class))
1936 (if (ad-advice-enabled advice)
1937 (push advice enabled-advices)))
1938 (reverse enabled-advices)))
1939
1940
1941 ;; @@ Dealing with automatic advice activation via `fset/defalias':
1942 ;; ================================================================
1943
1944 ;; Automatic activation happens when a function gets defined via `defalias',
1945 ;; which calls the `defalias-fset-function' (which we set to
1946 ;; `ad--defalias-fset') instead of `fset', if non-nil.
1947
1948 ;; Whether advised definitions created by automatic activations will be
1949 ;; compiled depends on the value of `ad-default-compilation-action'.
1950
1951 ;; Since calling `ad-activate-internal' in the built-in definition of `fset' can
1952 ;; create major disasters we have to be a bit careful. One precaution is
1953 ;; to provide a dummy definition for `ad-activate-internal' which can be used to
1954 ;; turn off automatic advice activation (e.g., when `ad-stop-advice' or
1955 ;; `ad-recover-normality' are called). Another is to avoid recursive calls
1956 ;; to `ad-activate' by using `ad-with-auto-activation-disabled' where
1957 ;; appropriate, especially in a safe version of `fset'.
1958
1959 (defun ad--defalias-fset (fsetfun function definition)
1960 (funcall (or fsetfun #'fset) function definition)
1961 (ad-activate-internal function nil))
1962
1963 ;; For now define `ad-activate-internal' to the dummy definition:
1964 (defun ad-activate-internal (_function &optional _compile)
1965 "Automatic advice activation is disabled. `ad-start-advice' enables it."
1966 nil)
1967
1968 ;; This is just a copy of the above:
1969 (defun ad-activate-internal-off (_function &optional _compile)
1970 "Automatic advice activation is disabled. `ad-start-advice' enables it."
1971 nil)
1972
1973 ;; This will be t for top-level calls to `ad-activate-internal-on':
1974 (defvar ad-activate-on-top-level t)
1975
1976 (defmacro ad-with-auto-activation-disabled (&rest body)
1977 `(let ((ad-activate-on-top-level nil))
1978 ,@body))
1979
1980 ;; @@ Access functions for original definitions:
1981 ;; ============================================
1982 ;; The advice-info of an advised function contains its `origname' which is
1983 ;; a symbol that is fbound to the original definition available at the first
1984 ;; proper activation of the function after a valid re/definition. If the
1985 ;; original was defined via fcell indirection then `origname' will be defined
1986 ;; just so. Hence, to get hold of the actual original definition of a function
1987 ;; we need to use `ad-real-orig-definition'.
1988
1989 (defun ad-make-origname (function)
1990 "Make name to be used to call the original FUNCTION."
1991 (intern (format "ad-Orig-%s" function)))
1992
1993 (defmacro ad-get-orig-definition (function)
1994 `(let ((origname (ad-get-advice-info-field ,function 'origname)))
1995 (if (fboundp origname)
1996 (symbol-function origname))))
1997
1998 (defmacro ad-set-orig-definition (function definition)
1999 `(fset (ad-get-advice-info-field ,function 'origname) ,definition))
2000
2001 (defmacro ad-clear-orig-definition (function)
2002 `(fmakunbound (ad-get-advice-info-field ,function 'origname)))
2003
2004
2005 ;; @@ Interactive input functions:
2006 ;; ===============================
2007
2008 (declare-function 'function-called-at-point "help")
2009
2010 (defun ad-read-advised-function (&optional prompt predicate default)
2011 "Read name of advised function with completion from the minibuffer.
2012 An optional PROMPT will be used to prompt for the function. PREDICATE
2013 plays the same role as for `try-completion' (which see). DEFAULT will
2014 be returned on empty input (defaults to the first advised function or
2015 function at point for which PREDICATE returns non-nil)."
2016 (if (null ad-advised-functions)
2017 (error "ad-read-advised-function: There are no advised functions"))
2018 (setq default
2019 (or default
2020 ;; Prefer func name at point, if it's an advised function etc.
2021 (let ((function (progn
2022 (require 'help)
2023 (function-called-at-point))))
2024 (and function
2025 (assoc (symbol-name function) ad-advised-functions)
2026 (or (null predicate)
2027 (funcall predicate function))
2028 function))
2029 (cl-block nil
2030 (ad-do-advised-functions (function)
2031 (if (or (null predicate)
2032 (funcall predicate function))
2033 (cl-return function))))
2034 (error "ad-read-advised-function: %s"
2035 "There are no qualifying advised functions")))
2036 (let* ((function
2037 (completing-read
2038 (format "%s (default %s): " (or prompt "Function") default)
2039 ad-advised-functions
2040 (if predicate
2041 (lambda (function)
2042 (funcall predicate (intern (car function)))))
2043 t)))
2044 (if (equal function "")
2045 (if (ad-is-advised default)
2046 default
2047 (error "ad-read-advised-function: `%s' is not advised" default))
2048 (intern function))))
2049
2050 (defvar ad-advice-class-completion-table
2051 (mapcar (lambda (class) (list (symbol-name class)))
2052 ad-advice-classes))
2053
2054 (defun ad-read-advice-class (function &optional prompt default)
2055 "Read a valid advice class with completion from the minibuffer.
2056 An optional PROMPT will be used to prompt for the class. DEFAULT will
2057 be returned on empty input (defaults to the first non-empty advice
2058 class of FUNCTION)."
2059 (setq default
2060 (or default
2061 (cl-dolist (class ad-advice-classes)
2062 (if (ad-get-advice-info-field function class)
2063 (cl-return class)))
2064 (error "ad-read-advice-class: `%s' has no advices" function)))
2065 (let ((class (completing-read
2066 (format "%s (default %s): " (or prompt "Class") default)
2067 ad-advice-class-completion-table nil t)))
2068 (if (equal class "")
2069 default
2070 (intern class))))
2071
2072 (defun ad-read-advice-name (function class &optional prompt)
2073 "Read name of existing advice of CLASS for FUNCTION with completion.
2074 An optional PROMPT is used to prompt for the name."
2075 (let* ((name-completion-table
2076 (mapcar (function (lambda (advice)
2077 (list (symbol-name (ad-advice-name advice)))))
2078 (ad-get-advice-info-field function class)))
2079 (default
2080 (if (null name-completion-table)
2081 (error "ad-read-advice-name: `%s' has no %s advice"
2082 function class)
2083 (car (car name-completion-table))))
2084 (prompt (format "%s (default %s): " (or prompt "Name") default))
2085 (name (completing-read prompt name-completion-table nil t)))
2086 (if (equal name "")
2087 (intern default)
2088 (intern name))))
2089
2090 (defun ad-read-advice-specification (&optional prompt)
2091 "Read a complete function/class/name specification from minibuffer.
2092 The list of read symbols will be returned. The optional PROMPT will
2093 be used to prompt for the function."
2094 (let* ((function (ad-read-advised-function prompt))
2095 (class (ad-read-advice-class function))
2096 (name (ad-read-advice-name function class)))
2097 (list function class name)))
2098
2099 ;; Use previous regexp as a default:
2100 (defvar ad-last-regexp "")
2101
2102 (defun ad-read-regexp (&optional prompt)
2103 "Read a regular expression from the minibuffer."
2104 (let ((regexp (read-from-minibuffer
2105 (concat (or prompt "Regular expression")
2106 (if (equal ad-last-regexp "") ": "
2107 (format " (default %s): " ad-last-regexp))))))
2108 (setq ad-last-regexp
2109 (if (equal regexp "") ad-last-regexp regexp))))
2110
2111
2112 ;; @@ Finding, enabling, adding and removing pieces of advice:
2113 ;; ===========================================================
2114
2115 (defmacro ad-find-advice (function class name)
2116 "Find the first advice of FUNCTION in CLASS with NAME."
2117 `(assq ,name (ad-get-advice-info-field ,function ,class)))
2118
2119 (defun ad-advice-position (function class name)
2120 "Return position of first advice of FUNCTION in CLASS with NAME."
2121 (let* ((found-advice (ad-find-advice function class name))
2122 (advices (ad-get-advice-info-field function class)))
2123 (if found-advice
2124 (- (length advices) (length (memq found-advice advices))))))
2125
2126 (defun ad-find-some-advice (function class name)
2127 "Find the first of FUNCTION's advices in CLASS matching NAME.
2128 NAME can be a symbol or a regular expression matching part of an advice name.
2129 If CLASS is `any' all valid advice classes will be checked."
2130 (if (ad-is-advised function)
2131 (let (found-advice)
2132 (cl-dolist (advice-class ad-advice-classes)
2133 (if (or (eq class 'any) (eq advice-class class))
2134 (setq found-advice
2135 (cl-dolist (advice (ad-get-advice-info-field
2136 function advice-class))
2137 (if (or (and (stringp name)
2138 (string-match
2139 name (symbol-name
2140 (ad-advice-name advice))))
2141 (eq name (ad-advice-name advice)))
2142 (cl-return advice)))))
2143 (if found-advice (cl-return found-advice))))))
2144
2145 (defun ad-enable-advice-internal (function class name flag)
2146 "Set enable FLAG of FUNCTION's advices in CLASS matching NAME.
2147 If NAME is a string rather than a symbol then it's interpreted as a regular
2148 expression and all advices whose name contain a match for it will be
2149 affected. If CLASS is `any' advices in all valid advice classes will be
2150 considered. The number of changed advices will be returned (or nil if
2151 FUNCTION was not advised)."
2152 (if (ad-is-advised function)
2153 (let ((matched-advices 0))
2154 (dolist (advice-class ad-advice-classes)
2155 (if (or (eq class 'any) (eq advice-class class))
2156 (dolist (advice (ad-get-advice-info-field
2157 function advice-class))
2158 (cond ((or (and (stringp name)
2159 (string-match
2160 name (symbol-name (ad-advice-name advice))))
2161 (eq name (ad-advice-name advice)))
2162 (setq matched-advices (1+ matched-advices))
2163 (ad-advice-set-enabled advice flag))))))
2164 matched-advices)))
2165
2166 ;;;###autoload
2167 (defun ad-enable-advice (function class name)
2168 "Enables the advice of FUNCTION with CLASS and NAME."
2169 (interactive (ad-read-advice-specification "Enable advice of"))
2170 (if (ad-is-advised function)
2171 (if (eq (ad-enable-advice-internal function class name t) 0)
2172 (error "ad-enable-advice: `%s' has no %s advice matching `%s'"
2173 function class name))
2174 (error "ad-enable-advice: `%s' is not advised" function)))
2175
2176 ;;;###autoload
2177 (defun ad-disable-advice (function class name)
2178 "Disable the advice of FUNCTION with CLASS and NAME."
2179 (interactive (ad-read-advice-specification "Disable advice of"))
2180 (if (ad-is-advised function)
2181 (if (eq (ad-enable-advice-internal function class name nil) 0)
2182 (error "ad-disable-advice: `%s' has no %s advice matching `%s'"
2183 function class name))
2184 (error "ad-disable-advice: `%s' is not advised" function)))
2185
2186 (defun ad-enable-regexp-internal (regexp class flag)
2187 "Set enable FLAGs of all CLASS advices whose name contains a REGEXP match.
2188 If CLASS is `any' all valid advice classes are considered. The number of
2189 affected advices will be returned."
2190 (let ((matched-advices 0))
2191 (ad-do-advised-functions (advised-function)
2192 (setq matched-advices
2193 (+ matched-advices
2194 (or (ad-enable-advice-internal
2195 advised-function class regexp flag)
2196 0))))
2197 matched-advices))
2198
2199 (defun ad-enable-regexp (regexp)
2200 "Enables all advices with names that contain a match for REGEXP.
2201 All currently advised functions will be considered."
2202 (interactive
2203 (list (ad-read-regexp "Enable advices via regexp")))
2204 (let ((matched-advices (ad-enable-regexp-internal regexp 'any t)))
2205 (if (called-interactively-p 'interactive)
2206 (message "%d matching advices enabled" matched-advices))
2207 matched-advices))
2208
2209 (defun ad-disable-regexp (regexp)
2210 "Disable all advices with names that contain a match for REGEXP.
2211 All currently advised functions will be considered."
2212 (interactive
2213 (list (ad-read-regexp "Disable advices via regexp")))
2214 (let ((matched-advices (ad-enable-regexp-internal regexp 'any nil)))
2215 (if (called-interactively-p 'interactive)
2216 (message "%d matching advices disabled" matched-advices))
2217 matched-advices))
2218
2219 (defun ad-remove-advice (function class name)
2220 "Remove FUNCTION's advice with NAME from its advices in CLASS.
2221 If such an advice was found it will be removed from the list of advices
2222 in that CLASS."
2223 (interactive (ad-read-advice-specification "Remove advice of"))
2224 (if (ad-is-advised function)
2225 (let ((advice-to-remove (ad-find-advice function class name)))
2226 (if advice-to-remove
2227 (ad-set-advice-info-field
2228 function class
2229 (delq advice-to-remove (ad-get-advice-info-field function class)))
2230 (error "ad-remove-advice: `%s' has no %s advice `%s'"
2231 function class name)))
2232 (error "ad-remove-advice: `%s' is not advised" function)))
2233
2234 ;;;###autoload
2235 (defun ad-add-advice (function advice class position)
2236 "Add a piece of ADVICE to FUNCTION's list of advices in CLASS.
2237
2238 ADVICE has the form (NAME PROTECTED ENABLED DEFINITION), where
2239 NAME is the advice name; PROTECTED is a flag specifying whether
2240 to protect against non-local exits; ENABLED is a flag specifying
2241 whether to initially enable the advice; and DEFINITION has the
2242 form (advice . LAMBDA), where LAMBDA is a lambda expression.
2243
2244 If FUNCTION already has a piece of advice with the same name,
2245 then POSITION is ignored, and the old advice is overwritten with
2246 the new one.
2247
2248 If FUNCTION already has one or more pieces of advice of the
2249 specified CLASS, then POSITION determines where the new piece
2250 goes. POSITION can either be `first', `last' or a number (where
2251 0 corresponds to `first', and numbers outside the valid range are
2252 mapped to the closest extremal position).
2253
2254 If FUNCTION was not advised already, its advice info will be
2255 initialized. Redefining a piece of advice whose name is part of
2256 the cache-id will clear the cache.
2257
2258 See Info node `(elisp)Computed Advice' for detailed documentation."
2259 (cond ((not (ad-is-advised function))
2260 (ad-initialize-advice-info function)
2261 (ad-set-advice-info-field
2262 function 'origname (ad-make-origname function))))
2263 (let* ((previous-position
2264 (ad-advice-position function class (ad-advice-name advice)))
2265 (advices (ad-get-advice-info-field function class))
2266 ;; Determine a numerical position for the new advice:
2267 (position (cond (previous-position)
2268 ((eq position 'first) 0)
2269 ((eq position 'last) (length advices))
2270 ((numberp position)
2271 (max 0 (min position (length advices))))
2272 (t 0))))
2273 ;; Check whether we have to clear the cache:
2274 (if (memq (ad-advice-name advice) (ad-get-cache-class-id function class))
2275 (ad-clear-cache function))
2276 (if previous-position
2277 (setcar (nthcdr position advices) advice)
2278 (if (= position 0)
2279 (ad-set-advice-info-field function class (cons advice advices))
2280 (setcdr (nthcdr (1- position) advices)
2281 (cons advice (nthcdr position advices)))))))
2282
2283
2284 ;; @@ Accessing and manipulating function definitions:
2285 ;; ===================================================
2286
2287 (defmacro ad-macrofy (definition)
2288 "Take a lambda function DEFINITION and make a macro out of it."
2289 `(cons 'macro ,definition))
2290
2291 (defmacro ad-lambdafy (definition)
2292 "Take a macro function DEFINITION and make a lambda out of it."
2293 `(cdr ,definition))
2294
2295 (defmacro ad-subr-p (definition)
2296 ;;"non-nil if DEFINITION is a subr."
2297 (list 'subrp definition))
2298
2299 (defmacro ad-macro-p (definition)
2300 ;;"non-nil if DEFINITION is a macro."
2301 `(eq (car-safe ,definition) 'macro))
2302
2303 (defmacro ad-lambda-p (definition)
2304 ;;"non-nil if DEFINITION is a lambda expression."
2305 `(eq (car-safe ,definition) 'lambda))
2306
2307 ;; see ad-make-advice for the format of advice definitions:
2308 (defmacro ad-advice-p (definition)
2309 ;;"non-nil if DEFINITION is a piece of advice."
2310 `(eq (car-safe ,definition) 'advice))
2311
2312 (defmacro ad-compiled-p (definition)
2313 "Return non-nil if DEFINITION is a compiled byte-code object."
2314 `(or (byte-code-function-p ,definition)
2315 (and (ad-macro-p ,definition)
2316 (byte-code-function-p (ad-lambdafy ,definition)))))
2317
2318 (defmacro ad-compiled-code (compiled-definition)
2319 "Return the byte-code object of a COMPILED-DEFINITION."
2320 `(if (ad-macro-p ,compiled-definition)
2321 (ad-lambdafy ,compiled-definition)
2322 ,compiled-definition))
2323
2324 (defun ad-lambda-expression (definition)
2325 "Return the lambda expression of a function/macro/advice DEFINITION."
2326 (cond ((ad-lambda-p definition)
2327 definition)
2328 ((ad-macro-p definition)
2329 (ad-lambdafy definition))
2330 ((ad-advice-p definition)
2331 (cdr definition))
2332 (t nil)))
2333
2334 (defun ad-arglist (definition)
2335 "Return the argument list of DEFINITION."
2336 (require 'help-fns)
2337 (help-function-arglist
2338 (if (or (ad-macro-p definition) (ad-advice-p definition))
2339 (cdr definition)
2340 definition)
2341 'preserve-names))
2342
2343 (defun ad-docstring (definition)
2344 "Return the unexpanded docstring of DEFINITION."
2345 (let ((docstring
2346 (if (ad-compiled-p definition)
2347 (documentation definition t)
2348 (car (cdr (cdr (ad-lambda-expression definition)))))))
2349 (if (or (stringp docstring)
2350 (natnump docstring))
2351 docstring)))
2352
2353 (defun ad-interactive-form (definition)
2354 "Return the interactive form of DEFINITION.
2355 Like `interactive-form', but also works on pieces of advice."
2356 (interactive-form
2357 (if (ad-advice-p definition)
2358 (ad-lambda-expression definition)
2359 definition)))
2360
2361 (defun ad-body-forms (definition)
2362 "Return the list of body forms of DEFINITION."
2363 (cond ((ad-compiled-p definition)
2364 nil)
2365 ((consp definition)
2366 (nthcdr (+ (if (ad-docstring definition) 1 0)
2367 (if (ad-interactive-form definition) 1 0))
2368 (cdr (cdr (ad-lambda-expression definition)))))))
2369
2370 (defun ad-make-advised-definition-docstring (_function)
2371 "Make an identifying docstring for the advised definition of FUNCTION.
2372 Put function name into the documentation string so we can infer
2373 the name of the advised function from the docstring. This is needed
2374 to generate a proper advised docstring even if we are just given a
2375 definition (see the code for `documentation')."
2376 (eval-when-compile
2377 (propertize "Advice doc string" 'dynamic-docstring-function
2378 #'ad--make-advised-docstring)))
2379
2380 (defun ad-advised-definition-p (definition)
2381 "Return non-nil if DEFINITION was generated from advice information."
2382 (if (or (ad-lambda-p definition)
2383 (ad-macro-p definition)
2384 (ad-compiled-p definition))
2385 (let ((docstring (ad-docstring definition)))
2386 (and (stringp docstring)
2387 (get-text-property 0 'dynamic-docstring-function docstring)))))
2388
2389 (defun ad-definition-type (definition)
2390 "Return symbol that describes the type of DEFINITION."
2391 (cond
2392 ((ad-macro-p definition) 'macro)
2393 ((ad-subr-p definition)
2394 (if (special-form-p definition)
2395 'special-form
2396 'subr))
2397 ((or (ad-lambda-p definition)
2398 (ad-compiled-p definition))
2399 'function)
2400 ((ad-advice-p definition) 'advice)))
2401
2402 (defun ad-has-proper-definition (function)
2403 "True if FUNCTION is a symbol with a proper definition.
2404 For that it has to be fbound with a non-autoload definition."
2405 (and (symbolp function)
2406 (fboundp function)
2407 (not (autoloadp (symbol-function function)))))
2408
2409 ;; The following two are necessary for the sake of packages such as
2410 ;; ange-ftp which redefine functions via fcell indirection:
2411 (defun ad-real-definition (function)
2412 "Find FUNCTION's definition at the end of function cell indirection."
2413 (if (ad-has-proper-definition function)
2414 (let ((definition (symbol-function function)))
2415 (if (symbolp definition)
2416 (ad-real-definition definition)
2417 definition))))
2418
2419 (defun ad-real-orig-definition (function)
2420 "Find FUNCTION's real original definition starting from its `origname'."
2421 (if (ad-is-advised function)
2422 (ad-real-definition (ad-get-advice-info-field function 'origname))))
2423
2424 (defun ad-is-compilable (function)
2425 "True if FUNCTION has an interpreted definition that can be compiled."
2426 (and (ad-has-proper-definition function)
2427 (or (ad-lambda-p (symbol-function function))
2428 (ad-macro-p (symbol-function function)))
2429 (not (ad-compiled-p (symbol-function function)))))
2430
2431 (defvar warning-suppress-types) ;From warnings.el.
2432 (defun ad-compile-function (function)
2433 "Byte-compiles FUNCTION (or macro) if it is not yet compiled."
2434 (interactive "aByte-compile function: ")
2435 (if (ad-is-compilable function)
2436 ;; Need to turn off auto-activation
2437 ;; because `byte-compile' uses `fset':
2438 (ad-with-auto-activation-disabled
2439 (require 'bytecomp)
2440 (require 'warnings) ;To define warning-suppress-types
2441 ;before we let-bind it.
2442 (let ((symbol (make-symbol "advice-compilation"))
2443 (byte-compile-warnings byte-compile-warnings)
2444 ;; Don't pop up windows showing byte-compiler warnings.
2445 (warning-suppress-types '((bytecomp))))
2446 (if (featurep 'cl)
2447 (byte-compile-disable-warning 'cl-functions))
2448 (fset symbol (symbol-function function))
2449 (byte-compile symbol)
2450 (fset function (symbol-function symbol))))))
2451
2452 ;; @@@ Accessing argument lists:
2453 ;; =============================
2454
2455 (defun ad-parse-arglist (arglist)
2456 "Parse ARGLIST into its required, optional and rest parameters.
2457 A three-element list is returned, where the 1st element is the list of
2458 required arguments, the 2nd is the list of optional arguments, and the 3rd
2459 is the name of an optional rest parameter (or nil)."
2460 (let (required optional rest)
2461 (setq rest (car (cdr (memq '&rest arglist))))
2462 (if rest (setq arglist (reverse (cdr (memq '&rest (reverse arglist))))))
2463 (setq optional (cdr (memq '&optional arglist)))
2464 (if optional
2465 (setq required (reverse (cdr (memq '&optional (reverse arglist)))))
2466 (setq required arglist))
2467 (list required optional rest)))
2468
2469 (defun ad-retrieve-args-form (arglist)
2470 "Generate a form which evaluates into names/values/types of ARGLIST.
2471 When the form gets evaluated within a function with that argument list
2472 it will result in a list with one entry for each argument, where the
2473 first element of each entry is the name of the argument, the second
2474 element is its actual current value, and the third element is either
2475 `required', `optional' or `rest' depending on the type of the argument."
2476 (let* ((parsed-arglist (ad-parse-arglist arglist))
2477 (rest (nth 2 parsed-arglist)))
2478 `(list
2479 ,@(mapcar (function
2480 (lambda (req)
2481 `(list ',req ,req 'required)))
2482 (nth 0 parsed-arglist))
2483 ,@(mapcar (function
2484 (lambda (opt)
2485 `(list ',opt ,opt 'optional)))
2486 (nth 1 parsed-arglist))
2487 ,@(if rest (list `(list ',rest ,rest 'rest))))))
2488
2489 (defun ad-arg-binding-field (binding field)
2490 (cond ((eq field 'name) (car binding))
2491 ((eq field 'value) (car (cdr binding)))
2492 ((eq field 'type) (car (cdr (cdr binding))))))
2493
2494 (defun ad-list-access (position list)
2495 (cond ((= position 0) list)
2496 ((= position 1) (list 'cdr list))
2497 (t (list 'nthcdr position list))))
2498
2499 (defun ad-element-access (position list)
2500 (cond ((= position 0) (list 'car list))
2501 ((= position 1) `(car (cdr ,list)))
2502 (t (list 'nth position list))))
2503
2504 (defun ad-access-argument (arglist index)
2505 "Tell how to access ARGLIST's actual argument at position INDEX.
2506 For a required/optional arg it simply returns it, if a rest argument has
2507 to be accessed, it returns a list with the index and name."
2508 (let* ((parsed-arglist (ad-parse-arglist arglist))
2509 (reqopt-args (append (nth 0 parsed-arglist)
2510 (nth 1 parsed-arglist)))
2511 (rest-arg (nth 2 parsed-arglist)))
2512 (cond ((< index (length reqopt-args))
2513 (nth index reqopt-args))
2514 (rest-arg
2515 (list (- index (length reqopt-args)) rest-arg)))))
2516
2517 (defun ad-get-argument (arglist index)
2518 "Return form to access ARGLIST's actual argument at position INDEX.
2519 INDEX counts from zero."
2520 (let ((argument-access (ad-access-argument arglist index)))
2521 (cond ((consp argument-access)
2522 (ad-element-access
2523 (car argument-access) (car (cdr argument-access))))
2524 (argument-access))))
2525
2526 (defun ad-set-argument (arglist index value-form)
2527 "Return form to set ARGLIST's actual arg at INDEX to VALUE-FORM.
2528 INDEX counts from zero."
2529 (let ((argument-access (ad-access-argument arglist index)))
2530 (cond ((consp argument-access)
2531 ;; should this check whether there actually is something to set?
2532 `(setcar ,(ad-list-access
2533 (car argument-access) (car (cdr argument-access)))
2534 ,value-form))
2535 (argument-access
2536 `(setq ,argument-access ,value-form))
2537 (t (error "ad-set-argument: No argument at position %d of `%s'"
2538 index arglist)))))
2539
2540 (defun ad-get-arguments (arglist index)
2541 "Return form to access all actual arguments starting at position INDEX."
2542 (let* ((parsed-arglist (ad-parse-arglist arglist))
2543 (reqopt-args (append (nth 0 parsed-arglist)
2544 (nth 1 parsed-arglist)))
2545 (rest-arg (nth 2 parsed-arglist))
2546 args-form)
2547 (if (< index (length reqopt-args))
2548 (setq args-form `(list ,@(nthcdr index reqopt-args))))
2549 (if rest-arg
2550 (if args-form
2551 (setq args-form `(nconc ,args-form ,rest-arg))
2552 (setq args-form (ad-list-access (- index (length reqopt-args))
2553 rest-arg))))
2554 args-form))
2555
2556 (defun ad-set-arguments (arglist index values-form)
2557 "Make form to assign elements of VALUES-FORM as actual ARGLIST args.
2558 The assignment starts at position INDEX."
2559 (let ((values-index 0)
2560 argument-access set-forms)
2561 (while (setq argument-access (ad-access-argument arglist index))
2562 (push (if (symbolp argument-access)
2563 (ad-set-argument
2564 arglist index
2565 (ad-element-access values-index 'ad-vAlUeS))
2566 (setq arglist nil) ;; Terminate loop.
2567 (if (= (car argument-access) 0)
2568 `(setq
2569 ,(car (cdr argument-access))
2570 ,(ad-list-access values-index 'ad-vAlUeS))
2571 `(setcdr
2572 ,(ad-list-access (1- (car argument-access))
2573 (car (cdr argument-access)))
2574 ,(ad-list-access values-index 'ad-vAlUeS))))
2575 set-forms)
2576 (setq index (1+ index))
2577 (setq values-index (1+ values-index)))
2578 (if (null set-forms)
2579 (error "ad-set-arguments: No argument at position %d of `%s'"
2580 index arglist)
2581 (if (= (length set-forms) 1)
2582 ;; For exactly one set-form we can use values-form directly,...
2583 (ad-substitute-tree
2584 (lambda (form) (eq form 'ad-vAlUeS))
2585 (lambda (_form) values-form)
2586 (car set-forms))
2587 ;; ...if we have more we have to bind it to a variable:
2588 `(let ((ad-vAlUeS ,values-form))
2589 ,@(reverse set-forms)
2590 ;; work around the old backquote bug:
2591 ,'ad-vAlUeS)))))
2592
2593 (defun ad-insert-argument-access-forms (definition arglist)
2594 "Expands arg-access text macros in DEFINITION according to ARGLIST."
2595 (ad-substitute-tree
2596 (function
2597 (lambda (form)
2598 (or (eq form 'ad-arg-bindings)
2599 (and (memq (car-safe form)
2600 '(ad-get-arg ad-get-args ad-set-arg ad-set-args))
2601 (integerp (car-safe (cdr form)))))))
2602 (function
2603 (lambda (form)
2604 (if (eq form 'ad-arg-bindings)
2605 (ad-retrieve-args-form arglist)
2606 (let ((accessor (car form))
2607 (index (car (cdr form)))
2608 (val (car (cdr (ad-insert-argument-access-forms
2609 (cdr form) arglist)))))
2610 (cond ((eq accessor 'ad-get-arg)
2611 (ad-get-argument arglist index))
2612 ((eq accessor 'ad-set-arg)
2613 (ad-set-argument arglist index val))
2614 ((eq accessor 'ad-get-args)
2615 (ad-get-arguments arglist index))
2616 ((eq accessor 'ad-set-args)
2617 (ad-set-arguments arglist index val)))))))
2618 definition))
2619
2620 ;; @@@ Mapping argument lists:
2621 ;; ===========================
2622 ;; Here is the problem:
2623 ;; Suppose function foo was called with (foo 1 2 3 4 5), and foo has the
2624 ;; argument list (x y &rest z), and we want to call the function bar which
2625 ;; has argument list (a &rest b) with a combination of x, y and z so that
2626 ;; the effect is just as if we had called (bar 1 2 3 4 5) directly.
2627 ;; The mapping should work for any two argument lists.
2628
2629 (defun ad-map-arglists (source-arglist target-arglist)
2630 "Make `funcall/apply' form to map SOURCE-ARGLIST to TARGET-ARGLIST.
2631 The arguments supplied to TARGET-ARGLIST will be taken from SOURCE-ARGLIST just
2632 as if they had been supplied to a function with TARGET-ARGLIST directly.
2633 Excess source arguments will be neglected, missing source arguments will be
2634 supplied as nil. Returns a `funcall' or `apply' form with the second element
2635 being `function' which has to be replaced by an actual function argument.
2636 Example: `(ad-map-arglists '(a &rest args) '(w x y z))' will return
2637 `(funcall function a (car args) (car (cdr args)) (nth 2 args))'."
2638 (let* ((parsed-source-arglist (ad-parse-arglist source-arglist))
2639 (source-reqopt-args (append (nth 0 parsed-source-arglist)
2640 (nth 1 parsed-source-arglist)))
2641 (source-rest-arg (nth 2 parsed-source-arglist))
2642 (parsed-target-arglist (ad-parse-arglist target-arglist))
2643 (target-reqopt-args (append (nth 0 parsed-target-arglist)
2644 (nth 1 parsed-target-arglist)))
2645 (target-rest-arg (nth 2 parsed-target-arglist))
2646 (need-apply (and source-rest-arg target-rest-arg))
2647 (target-arg-index -1))
2648 ;; This produces ``error-proof'' target function calls with the exception
2649 ;; of a case like (&rest a) mapped onto (x &rest y) where the actual args
2650 ;; supplied to A might not be enough to supply the required target arg X
2651 (append (list (if need-apply 'apply 'funcall) 'function)
2652 (cond (need-apply
2653 ;; `apply' can take care of that directly:
2654 (append source-reqopt-args (list source-rest-arg)))
2655 (t (mapcar (lambda (_arg)
2656 (setq target-arg-index (1+ target-arg-index))
2657 (ad-get-argument
2658 source-arglist target-arg-index))
2659 (append target-reqopt-args
2660 (and target-rest-arg
2661 ;; If we have a rest arg gobble up
2662 ;; remaining source args:
2663 (nthcdr (length target-reqopt-args)
2664 source-reqopt-args)))))))))
2665
2666 (defun ad-make-mapped-call (source-arglist target-arglist target-function)
2667 "Make form to call TARGET-FUNCTION with args from SOURCE-ARGLIST."
2668 (let ((mapped-form (ad-map-arglists source-arglist target-arglist)))
2669 (if (eq (car mapped-form) 'funcall)
2670 (cons target-function (cdr (cdr mapped-form)))
2671 (prog1 mapped-form
2672 (setcar (cdr mapped-form) (list 'quote target-function))))))
2673
2674 ;; @@@ Making an advised documentation string:
2675 ;; ===========================================
2676 ;; New policy: The documentation string for an advised function will be built
2677 ;; at the time the advised `documentation' function is called. This has the
2678 ;; following advantages:
2679 ;; 1) command-key substitutions will automatically be correct
2680 ;; 2) No wasted string space due to big advised docstrings in caches or
2681 ;; compiled files that contain preactivations
2682 ;; The overall overhead for this should be negligible because people normally
2683 ;; don't lookup documentation for the same function over and over again.
2684
2685 (defun ad-make-single-advice-docstring (advice class &optional style)
2686 (let ((advice-docstring (ad-docstring (ad-advice-definition advice))))
2687 (cond ((eq style 'plain)
2688 advice-docstring)
2689 (t (if advice-docstring
2690 (format "%s-advice `%s':\n%s"
2691 (capitalize (symbol-name class))
2692 (ad-advice-name advice)
2693 advice-docstring)
2694 (format "%s-advice `%s'."
2695 (capitalize (symbol-name class))
2696 (ad-advice-name advice)))))))
2697
2698 (require 'help-fns) ;For help-split-fundoc and help-add-fundoc-usage.
2699
2700 (defun ad-make-advised-docstring (function &optional style)
2701 (let* ((origdef (ad-real-orig-definition function))
2702 (origdoc
2703 ;; Retrieve raw doc, key substitution will be taken care of later:
2704 (documentation origdef t)))
2705 (ad--make-advised-docstring origdoc function style)))
2706
2707 (defun ad--make-advised-docstring (origdoc function &optional style)
2708 "Construct a documentation string for the advised FUNCTION.
2709 It concatenates the original documentation with the documentation
2710 strings of the individual pieces of advice which will be formatted
2711 according to STYLE. STYLE can be `plain', everything else
2712 will be interpreted as `default'. The order of the advice documentation
2713 strings corresponds to before/around/after and the individual ordering
2714 in any of these classes."
2715 (let* ((origdef (ad-real-orig-definition function))
2716 (origtype (symbol-name (ad-definition-type origdef)))
2717 (usage (help-split-fundoc origdoc function))
2718 paragraphs advice-docstring)
2719 (setq usage (if (null usage) t (setq origdoc (cdr usage)) (car usage)))
2720 (if origdoc (setq paragraphs (list origdoc)))
2721 (unless (eq style 'plain)
2722 (push (concat "This " origtype " is advised.") paragraphs))
2723 (dolist (class ad-advice-classes)
2724 (dolist (advice (ad-get-enabled-advices function class))
2725 (setq advice-docstring
2726 (ad-make-single-advice-docstring advice class style))
2727 (if advice-docstring
2728 (push advice-docstring paragraphs))))
2729 (setq origdoc (if paragraphs
2730 (propertize
2731 ;; separate paragraphs with blank lines:
2732 (mapconcat 'identity (nreverse paragraphs) "\n\n")
2733 ;; FIXME: what is this for?
2734 'dynamic-docstring-function
2735 #'ad--make-advised-docstring)))
2736 (help-add-fundoc-usage origdoc usage)))
2737
2738 (defun ad-make-plain-docstring (function)
2739 (ad-make-advised-docstring function 'plain))
2740
2741 ;; @@@ Accessing overriding arglists and interactive forms:
2742 ;; ========================================================
2743
2744 (defun ad-advised-arglist (function)
2745 "Find first defined arglist in FUNCTION's redefining advices."
2746 (cl-dolist (advice (append (ad-get-enabled-advices function 'before)
2747 (ad-get-enabled-advices function 'around)
2748 (ad-get-enabled-advices function 'after)))
2749 (let ((arglist (ad-arglist (ad-advice-definition advice))))
2750 (if arglist
2751 ;; We found the first one, use it:
2752 (cl-return arglist)))))
2753
2754 (defun ad-advised-interactive-form (function)
2755 "Find first interactive form in FUNCTION's redefining advices."
2756 (cl-dolist (advice (append (ad-get-enabled-advices function 'before)
2757 (ad-get-enabled-advices function 'around)
2758 (ad-get-enabled-advices function 'after)))
2759 (let ((interactive-form
2760 (ad-interactive-form (ad-advice-definition advice))))
2761 (if interactive-form
2762 ;; We found the first one, use it:
2763 (cl-return interactive-form)))))
2764
2765 ;; @@@ Putting it all together:
2766 ;; ============================
2767
2768 (defun ad-make-advised-definition (function)
2769 "Generate an advised definition of FUNCTION from its advice info."
2770 (if (and (ad-is-advised function)
2771 (ad-has-redefining-advice function))
2772 (let* ((origdef (ad-real-orig-definition function))
2773 (origname (ad-get-advice-info-field function 'origname))
2774 (orig-interactive-p (commandp origdef))
2775 (orig-subr-p (ad-subr-p origdef))
2776 (orig-special-form-p (special-form-p origdef))
2777 (orig-macro-p (ad-macro-p origdef))
2778 ;; Construct the individual pieces that we need for assembly:
2779 (orig-arglist (ad-arglist origdef))
2780 (advised-arglist (or (ad-advised-arglist function)
2781 orig-arglist))
2782 (advised-interactive-form (ad-advised-interactive-form function))
2783 (interactive-form
2784 (cond (orig-macro-p nil)
2785 (advised-interactive-form)
2786 ((interactive-form origdef)
2787 (interactive-form
2788 (if (and (symbolp function) (get function 'elp-info))
2789 (aref (get function 'elp-info) 2)
2790 origdef)))))
2791 (orig-form
2792 (cond ((or orig-special-form-p orig-macro-p)
2793 ;; Special forms and macros will be advised into macros.
2794 ;; The trick is to construct an expansion for the advised
2795 ;; macro that does the correct thing when it gets eval'ed.
2796 ;; For macros we'll just use the expansion of the original
2797 ;; macro and return that. This way compiled advised macros
2798 ;; will be expanded into something useful. Note that after
2799 ;; advices have full control over whether they want to
2800 ;; evaluate the expansion (the value of `ad-return-value')
2801 ;; at macro expansion time or not. For special forms there
2802 ;; is no solution that interacts reasonably with the
2803 ;; compiler, hence we just evaluate the original at macro
2804 ;; expansion time and return the result. The moral of that
2805 ;; is that one should always deactivate advised special
2806 ;; forms before one byte-compiles a file.
2807 `(,(if orig-macro-p 'macroexpand 'eval)
2808 (cons ',origname
2809 ,(ad-get-arguments advised-arglist 0))))
2810 ((and orig-subr-p
2811 orig-interactive-p
2812 (not interactive-form)
2813 (not advised-interactive-form))
2814 ;; Check whether we were called interactively
2815 ;; in order to do proper prompting:
2816 `(if (called-interactively-p 'any)
2817 (call-interactively ',origname)
2818 ,(ad-make-mapped-call advised-arglist
2819 orig-arglist
2820 origname)))
2821 ;; And now for normal functions and non-interactive subrs
2822 ;; (or subrs whose interactive behavior was advised):
2823 (t (ad-make-mapped-call
2824 advised-arglist orig-arglist origname)))))
2825
2826 ;; Finally, build the sucker:
2827 (ad-assemble-advised-definition
2828 (cond (orig-macro-p 'macro)
2829 (orig-special-form-p 'special-form)
2830 (t 'function))
2831 advised-arglist
2832 (ad-make-advised-definition-docstring function)
2833 interactive-form
2834 orig-form
2835 (ad-get-enabled-advices function 'before)
2836 (ad-get-enabled-advices function 'around)
2837 (ad-get-enabled-advices function 'after)))))
2838
2839 (defun ad-assemble-advised-definition
2840 (type args docstring interactive orig &optional befores arounds afters)
2841
2842 "Assembles an original and its advices into an advised function.
2843 It constructs a function or macro definition according to TYPE which has to
2844 be either `macro', `function' or `special-form'. ARGS is the argument list
2845 that has to be used, DOCSTRING if non-nil defines the documentation of the
2846 definition, INTERACTIVE if non-nil is the interactive form to be used,
2847 ORIG is a form that calls the body of the original unadvised function,
2848 and BEFORES, AROUNDS and AFTERS are the lists of advices with which ORIG
2849 should be modified. The assembled function will be returned."
2850 ;; The ad-do-it call should always have the right number of arguments,
2851 ;; but the compiler might signal a bogus warning because it checks the call
2852 ;; against the advertised calling convention.
2853 (let ((around-form `(setq ad-return-value (with-no-warnings ,orig)))
2854 before-forms around-form-protected after-forms definition)
2855 (dolist (advice befores)
2856 (cond ((and (ad-advice-protected advice)
2857 before-forms)
2858 (setq before-forms
2859 `((unwind-protect
2860 ,(macroexp-progn before-forms)
2861 ,@(ad-body-forms
2862 (ad-advice-definition advice))))))
2863 (t (setq before-forms
2864 (append before-forms
2865 (ad-body-forms (ad-advice-definition advice)))))))
2866
2867 (dolist (advice (reverse arounds))
2868 ;; If any of the around advices is protected then we
2869 ;; protect the complete around advice onion:
2870 (if (ad-advice-protected advice)
2871 (setq around-form-protected t))
2872 (setq around-form
2873 (ad-substitute-tree
2874 (lambda (form) (eq form 'ad-do-it))
2875 (lambda (_form) around-form)
2876 (macroexp-progn (ad-body-forms (ad-advice-definition advice))))))
2877
2878 (setq after-forms
2879 (if (and around-form-protected before-forms)
2880 `((unwind-protect
2881 ,(macroexp-progn before-forms)
2882 ,around-form))
2883 (append before-forms (list around-form))))
2884 (dolist (advice afters)
2885 (cond ((and (ad-advice-protected advice)
2886 after-forms)
2887 (setq after-forms
2888 `((unwind-protect
2889 ,(macroexp-progn after-forms)
2890 ,@(ad-body-forms
2891 (ad-advice-definition advice))))))
2892 (t (setq after-forms
2893 (append after-forms
2894 (ad-body-forms (ad-advice-definition advice)))))))
2895
2896 (setq definition
2897 `(,@(if (memq type '(macro special-form)) '(macro))
2898 lambda
2899 ,args
2900 ,@(if docstring (list docstring))
2901 ,@(if interactive (list interactive))
2902 (let (ad-return-value)
2903 ,@after-forms
2904 ,(if (eq type 'special-form)
2905 '(list 'quote ad-return-value)
2906 'ad-return-value))))
2907
2908 (ad-insert-argument-access-forms definition args)))
2909
2910 ;; This is needed for activation/deactivation hooks:
2911 (defun ad-make-hook-form (function hook-name)
2912 "Make hook-form from FUNCTION's advice bodies in class HOOK-NAME."
2913 (let ((hook-forms
2914 (mapcar (function (lambda (advice)
2915 (ad-body-forms (ad-advice-definition advice))))
2916 (ad-get-enabled-advices function hook-name))))
2917 (if hook-forms
2918 (macroexp-progn (apply 'append hook-forms)))))
2919
2920
2921 ;; @@ Caching:
2922 ;; ===========
2923 ;; Generating an advised definition of a function is moderately expensive,
2924 ;; hence, it makes sense to cache it so we can reuse it in appropriate
2925 ;; circumstances. Of course, it only makes sense to reuse a cached
2926 ;; definition if the current advice and function definition state is the
2927 ;; same as it was at the time when the cached definition was generated.
2928 ;; For that purpose we associate every cache with an id so we can verify
2929 ;; if it is still valid at a certain point in time. This id mechanism
2930 ;; makes it possible to preactivate advised functions, write the compiled
2931 ;; advised definitions to a file and reuse them during the actual
2932 ;; activation without having to risk that the resulting definition will be
2933 ;; incorrect, well, almost.
2934 ;;
2935 ;; A cache id is a list with six elements:
2936 ;; 1) the list of names of enabled before advices
2937 ;; 2) the list of names of enabled around advices
2938 ;; 3) the list of names of enabled after advices
2939 ;; 4) the type of the original function (macro, subr, etc.)
2940 ;; 5) the arglist of the original definition (or t if it was equal to the
2941 ;; arglist of the cached definition)
2942 ;; 6) t if the interactive form of the original definition was equal to the
2943 ;; interactive form of the cached definition
2944 ;;
2945 ;; Here's how a cache can get invalidated or be incorrect:
2946 ;; A) a piece of advice used in the cache gets redefined
2947 ;; B) the current list of enabled advices is different from the ones used
2948 ;; for the cache
2949 ;; C) the type of the original function changed, e.g., a function became a
2950 ;; macro, or a subr became a function
2951 ;; D) the arglist of the original function changed
2952 ;; E) the interactive form of the original function changed
2953 ;; F) a piece of advice used in the cache got redefined before the
2954 ;; defadvice with the cached definition got loaded: This is a PROBLEM!
2955 ;;
2956 ;; Cases A and B are the normal ones. A is taken care of by `ad-add-advice'
2957 ;; which clears the cache in such a case, B is easily checked during
2958 ;; verification at activation time.
2959 ;;
2960 ;; Cases C, D and E have to be considered if one is slightly paranoid, i.e.,
2961 ;; if one considers the case that the original function could be different
2962 ;; from the one available at caching time (e.g., for forward advice of
2963 ;; functions that get redefined by some packages - such as `eval-region' gets
2964 ;; redefined by edebug). All these cases can be easily checked during
2965 ;; verification. Element 4 of the id lets one check case C, element 5 takes
2966 ;; care of case D (using t in the equality case saves some space, because the
2967 ;; arglist can be recovered at validation time from the cached definition),
2968 ;; and element 6 takes care of case E which is only a problem if the original
2969 ;; was actually a function whose interactive form was not overridden by a
2970 ;; piece of advice.
2971 ;;
2972 ;; Case F is the only one which will lead to an incorrect advised function.
2973 ;; There is no way to avoid this without storing the complete advice definition
2974 ;; in the cache-id which is not feasible.
2975 ;;
2976 ;; The cache-id of a typical advised function with one piece of advice and
2977 ;; no arglist redefinition takes 7 conses which is a small price to pay for
2978 ;; the added efficiency. The validation itself is also pretty cheap, certainly
2979 ;; a lot cheaper than reconstructing an advised definition.
2980
2981 (defmacro ad-get-cache-definition (function)
2982 `(car (ad-get-advice-info-field ,function 'cache)))
2983
2984 (defmacro ad-get-cache-id (function)
2985 `(cdr (ad-get-advice-info-field ,function 'cache)))
2986
2987 (defmacro ad-set-cache (function definition id)
2988 `(ad-set-advice-info-field
2989 ,function 'cache (cons ,definition ,id)))
2990
2991 (defun ad-clear-cache (function)
2992 "Clears a previously cached advised definition of FUNCTION.
2993 Clear the cache if you want to force `ad-activate' to construct a new
2994 advised definition from scratch."
2995 (interactive
2996 (list (ad-read-advised-function "Clear cached definition of")))
2997 (ad-set-advice-info-field function 'cache nil))
2998
2999 (defun ad-make-cache-id (function)
3000 "Generate an identifying image of the current advices of FUNCTION."
3001 (let ((original-definition (ad-real-orig-definition function))
3002 (cached-definition (ad-get-cache-definition function)))
3003 (list (mapcar (function (lambda (advice) (ad-advice-name advice)))
3004 (ad-get-enabled-advices function 'before))
3005 (mapcar (function (lambda (advice) (ad-advice-name advice)))
3006 (ad-get-enabled-advices function 'around))
3007 (mapcar (function (lambda (advice) (ad-advice-name advice)))
3008 (ad-get-enabled-advices function 'after))
3009 (ad-definition-type original-definition)
3010 (if (equal (ad-arglist original-definition)
3011 (ad-arglist cached-definition))
3012 t
3013 (ad-arglist original-definition))
3014 (if (eq (ad-definition-type original-definition) 'function)
3015 (equal (interactive-form original-definition)
3016 (interactive-form cached-definition))))))
3017
3018 (defun ad-get-cache-class-id (function class)
3019 "Return the part of FUNCTION's cache id that identifies CLASS."
3020 (let ((cache-id (ad-get-cache-id function)))
3021 (if (eq class 'before)
3022 (car cache-id)
3023 (if (eq class 'around)
3024 (nth 1 cache-id)
3025 (nth 2 cache-id)))))
3026
3027 (defun ad-verify-cache-class-id (cache-class-id advices)
3028 (cl-dolist (advice advices (null cache-class-id))
3029 (if (ad-advice-enabled advice)
3030 (if (eq (car cache-class-id) (ad-advice-name advice))
3031 (setq cache-class-id (cdr cache-class-id))
3032 (cl-return nil)))))
3033
3034 ;; There should be a way to monitor if and why a cache verification failed
3035 ;; in order to determine whether a certain preactivation could be used or
3036 ;; not. Right now the only way to find out is to trace
3037 ;; `ad-cache-id-verification-code'. The code it returns indicates where the
3038 ;; verification failed. Tracing `ad-verify-cache-class-id' might provide
3039 ;; some additional useful information.
3040
3041 (defun ad-cache-id-verification-code (function)
3042 (let ((cache-id (ad-get-cache-id function))
3043 (code 'before-advice-mismatch))
3044 (and (ad-verify-cache-class-id
3045 (car cache-id) (ad-get-advice-info-field function 'before))
3046 (setq code 'around-advice-mismatch)
3047 (ad-verify-cache-class-id
3048 (nth 1 cache-id) (ad-get-advice-info-field function 'around))
3049 (setq code 'after-advice-mismatch)
3050 (ad-verify-cache-class-id
3051 (nth 2 cache-id) (ad-get-advice-info-field function 'after))
3052 (setq code 'definition-type-mismatch)
3053 (let ((original-definition (ad-real-orig-definition function))
3054 (cached-definition (ad-get-cache-definition function)))
3055 (and (eq (nth 3 cache-id) (ad-definition-type original-definition))
3056 (setq code 'arglist-mismatch)
3057 (equal (if (eq (nth 4 cache-id) t)
3058 (ad-arglist original-definition)
3059 (nth 4 cache-id) )
3060 (ad-arglist cached-definition))
3061 (setq code 'interactive-form-mismatch)
3062 (or (null (nth 5 cache-id))
3063 (equal (interactive-form original-definition)
3064 (interactive-form cached-definition)))
3065 (setq code 'verified))))
3066 code))
3067
3068 (defun ad-verify-cache-id (function)
3069 "True if FUNCTION's cache-id is compatible with its current advices."
3070 (eq (ad-cache-id-verification-code function) 'verified))
3071
3072
3073 ;; @@ Preactivation:
3074 ;; =================
3075 ;; Preactivation can be used to generate compiled advised definitions
3076 ;; at compile time without having to give up the dynamic runtime flexibility
3077 ;; of the advice mechanism. Preactivation is a special feature of `defadvice',
3078 ;; it involves the following steps:
3079 ;; - remembering the function's current state (definition and advice-info)
3080 ;; - advising it with the defined piece of advice
3081 ;; - clearing its cache
3082 ;; - generating an interpreted advised definition by activating it, this will
3083 ;; make use of all its current active advice and its current definition
3084 ;; - saving the so generated cached definition and id
3085 ;; - resetting the function's advice and definition state to what it was
3086 ;; before the preactivation
3087 ;; - Returning the saved definition and its id to be used in the expansion of
3088 ;; `defadvice' to assign it as an initial cache, hence it will be compiled
3089 ;; at time the `defadvice' gets compiled.
3090 ;; Naturally, for preactivation to be effective it has to be applied/compiled
3091 ;; at the right time, i.e., when the current state of advices and function
3092 ;; definition exactly reflects the state at activation time. Should that not
3093 ;; be the case, the precompiled definition will just be discarded and a new
3094 ;; advised definition will be generated.
3095
3096 (defun ad-preactivate-advice (function advice class position)
3097 "Preactivate FUNCTION and returns the constructed cache."
3098 (let* ((function-defined-p (fboundp function))
3099 (old-definition
3100 (if function-defined-p
3101 (symbol-function function)))
3102 (old-advice-info (ad-copy-advice-info function))
3103 (ad-advised-functions ad-advised-functions))
3104 (unwind-protect
3105 (progn
3106 (ad-add-advice function advice class position)
3107 (ad-enable-advice function class (ad-advice-name advice))
3108 (ad-clear-cache function)
3109 (ad-activate function -1)
3110 (if (and (ad-is-active function)
3111 (ad-get-cache-definition function))
3112 (list (ad-get-cache-definition function)
3113 (ad-get-cache-id function))))
3114 (ad-set-advice-info function old-advice-info)
3115 ;; Don't `fset' function to nil if it was previously unbound:
3116 (if function-defined-p
3117 (fset function old-definition)
3118 (fmakunbound function)))))
3119
3120
3121 ;; @@ Activation and definition handling:
3122 ;; ======================================
3123
3124 (defun ad-should-compile (function compile)
3125 "Return non-nil if the advised FUNCTION should be compiled.
3126 If COMPILE is non-nil and not a negative number then it returns t.
3127 If COMPILE is a negative number then it returns nil.
3128 If COMPILE is nil then the result depends on the value of
3129 `ad-default-compilation-action' (which see)."
3130 (if (integerp compile)
3131 (>= compile 0)
3132 (if compile
3133 compile
3134 (cond ((eq ad-default-compilation-action 'never)
3135 nil)
3136 ((eq ad-default-compilation-action 'always)
3137 t)
3138 ((eq ad-default-compilation-action 'like-original)
3139 (or (ad-subr-p (ad-get-orig-definition function))
3140 (ad-compiled-p (ad-get-orig-definition function))))
3141 ;; everything else means `maybe':
3142 (t (featurep 'byte-compile))))))
3143
3144 (defun ad-activate-advised-definition (function compile)
3145 "Redefine FUNCTION with its advised definition from cache or scratch.
3146 The resulting FUNCTION will be compiled if `ad-should-compile' returns t.
3147 The current definition and its cache-id will be put into the cache."
3148 (let ((verified-cached-definition
3149 (if (ad-verify-cache-id function)
3150 (ad-get-cache-definition function))))
3151 (fset function
3152 (or verified-cached-definition
3153 (ad-make-advised-definition function)))
3154 (if (ad-should-compile function compile)
3155 (ad-compile-function function))
3156 (if verified-cached-definition
3157 (if (not (eq verified-cached-definition (symbol-function function)))
3158 ;; we must have compiled, cache the compiled definition:
3159 (ad-set-cache
3160 function (symbol-function function) (ad-get-cache-id function)))
3161 ;; We created a new advised definition, cache it with a proper id:
3162 (ad-clear-cache function)
3163 ;; ad-make-cache-id needs the new cached definition:
3164 (ad-set-cache function (symbol-function function) nil)
3165 (ad-set-cache
3166 function (symbol-function function) (ad-make-cache-id function)))))
3167
3168 (defun ad-handle-definition (function)
3169 "Handle re/definition of an advised FUNCTION during de/activation.
3170 If FUNCTION does not have an original definition associated with it and
3171 the current definition is usable, then it will be stored as FUNCTION's
3172 original definition. If no current definition is available (even in the
3173 case of undefinition) nothing will be done. In the case of redefinition
3174 the action taken depends on the value of `ad-redefinition-action' (which
3175 see). Redefinition occurs when FUNCTION already has an original definition
3176 associated with it but got redefined with a new definition and then
3177 de/activated. If you do not like the current redefinition action change
3178 the value of `ad-redefinition-action' and de/activate again."
3179 (let ((original-definition (ad-get-orig-definition function))
3180 (current-definition (if (ad-real-definition function)
3181 (symbol-function function))))
3182 (if original-definition
3183 (if current-definition
3184 (if (and (not (eq current-definition original-definition))
3185 ;; Redefinition with an advised definition from a
3186 ;; different function won't count as such:
3187 (not (ad-advised-definition-p current-definition)))
3188 ;; we have a redefinition:
3189 (if (not (memq ad-redefinition-action '(accept discard warn)))
3190 (error "ad-handle-definition (see its doc): `%s' %s"
3191 function "invalidly redefined")
3192 (if (eq ad-redefinition-action 'discard)
3193 (fset function original-definition)
3194 (ad-set-orig-definition function current-definition)
3195 (if (eq ad-redefinition-action 'warn)
3196 (message "ad-handle-definition: `%s' got redefined"
3197 function))))
3198 ;; either advised def or correct original is in place:
3199 nil)
3200 ;; we have an undefinition, ignore it:
3201 nil)
3202 (if current-definition
3203 ;; we have a first definition, save it as original:
3204 (ad-set-orig-definition function current-definition)
3205 ;; we don't have anything noteworthy:
3206 nil))))
3207
3208
3209 ;; @@ The top-level advice interface:
3210 ;; ==================================
3211
3212 ;;;###autoload
3213 (defun ad-activate (function &optional compile)
3214 "Activate all the advice information of an advised FUNCTION.
3215 If FUNCTION has a proper original definition then an advised
3216 definition will be generated from FUNCTION's advice info and the
3217 definition of FUNCTION will be replaced with it. If a previously
3218 cached advised definition was available, it will be used.
3219 The optional COMPILE argument determines whether the resulting function
3220 or a compilable cached definition will be compiled. If it is negative
3221 no compilation will be performed, if it is positive or otherwise non-nil
3222 the resulting function will be compiled, if it is nil the behavior depends
3223 on the value of `ad-default-compilation-action' (which see).
3224 Activation of an advised function that has an advice info but no actual
3225 pieces of advice is equivalent to a call to `ad-unadvise'. Activation of
3226 an advised function that has actual pieces of advice but none of them are
3227 enabled is equivalent to a call to `ad-deactivate'. The current advised
3228 definition will always be cached for later usage."
3229 (interactive
3230 (list (ad-read-advised-function "Activate advice of")
3231 current-prefix-arg))
3232 (if ad-activate-on-top-level
3233 ;; avoid recursive calls to `ad-activate':
3234 (ad-with-auto-activation-disabled
3235 (if (not (ad-is-advised function))
3236 (error "ad-activate: `%s' is not advised" function)
3237 (ad-handle-definition function)
3238 ;; Just return for forward advised and not yet defined functions:
3239 (if (ad-get-orig-definition function)
3240 (if (not (ad-has-any-advice function))
3241 (ad-unadvise function)
3242 ;; Otherwise activate the advice:
3243 (cond ((ad-has-redefining-advice function)
3244 (ad-activate-advised-definition function compile)
3245 (ad-set-advice-info-field function 'active t)
3246 (eval (ad-make-hook-form function 'activation))
3247 function)
3248 ;; Here we are if we have all disabled advices:
3249 (t (ad-deactivate function)))))))))
3250
3251 (defalias 'ad-activate-on 'ad-activate)
3252
3253 (defun ad-deactivate (function)
3254 "Deactivate the advice of an actively advised FUNCTION.
3255 If FUNCTION has a proper original definition, then the current
3256 definition of FUNCTION will be replaced with it. All the advice
3257 information will still be available so it can be activated again with
3258 a call to `ad-activate'."
3259 (interactive
3260 (list (ad-read-advised-function "Deactivate advice of" 'ad-is-active)))
3261 (if (not (ad-is-advised function))
3262 (error "ad-deactivate: `%s' is not advised" function)
3263 (cond ((ad-is-active function)
3264 (ad-handle-definition function)
3265 (if (not (ad-get-orig-definition function))
3266 (error "ad-deactivate: `%s' has no original definition"
3267 function)
3268 (fset function (ad-get-orig-definition function))
3269 (ad-set-advice-info-field function 'active nil)
3270 (eval (ad-make-hook-form function 'deactivation))
3271 function)))))
3272
3273 (defun ad-update (function &optional compile)
3274 "Update the advised definition of FUNCTION if its advice is active.
3275 See `ad-activate' for documentation on the optional COMPILE argument."
3276 (interactive
3277 (list (ad-read-advised-function
3278 "Update advised definition of" 'ad-is-active)))
3279 (if (ad-is-active function)
3280 (ad-activate function compile)))
3281
3282 (defun ad-unadvise (function)
3283 "Deactivate FUNCTION and then remove all its advice information.
3284 If FUNCTION was not advised this will be a noop."
3285 (interactive
3286 (list (ad-read-advised-function "Unadvise function")))
3287 (cond ((ad-is-advised function)
3288 (if (ad-is-active function)
3289 (ad-deactivate function))
3290 (ad-clear-orig-definition function)
3291 (ad-set-advice-info function nil)
3292 (ad-pop-advised-function function))))
3293
3294 (defun ad-recover (function)
3295 "Try to recover FUNCTION's original definition, and unadvise it.
3296 This is more low-level than `ad-unadvise' in that it does not do
3297 deactivation, which might run hooks and get into other trouble.
3298 Use in emergencies."
3299 ;; Use more primitive interactive behavior here: Accept any symbol that's
3300 ;; currently defined in obarray, not necessarily with a function definition:
3301 (interactive
3302 (list (intern
3303 (completing-read "Recover advised function: " obarray nil t))))
3304 (cond ((ad-is-advised function)
3305 (cond ((ad-get-orig-definition function)
3306 (fset function (ad-get-orig-definition function))
3307 (ad-clear-orig-definition function)))
3308 (ad-set-advice-info function nil)
3309 (ad-pop-advised-function function))))
3310
3311 (defun ad-activate-regexp (regexp &optional compile)
3312 "Activate functions with an advice name containing a REGEXP match.
3313 This activates the advice for each function
3314 that has at least one piece of advice whose name includes a match for REGEXP.
3315 See `ad-activate' for documentation on the optional COMPILE argument."
3316 (interactive
3317 (list (ad-read-regexp "Activate via advice regexp")
3318 current-prefix-arg))
3319 (ad-do-advised-functions (function)
3320 (if (ad-find-some-advice function 'any regexp)
3321 (ad-activate function compile))))
3322
3323 (defun ad-deactivate-regexp (regexp)
3324 "Deactivate functions with an advice name containing REGEXP match.
3325 This deactivates the advice for each function
3326 that has at least one piece of advice whose name includes a match for REGEXP."
3327 (interactive
3328 (list (ad-read-regexp "Deactivate via advice regexp")))
3329 (ad-do-advised-functions (function)
3330 (if (ad-find-some-advice function 'any regexp)
3331 (ad-deactivate function))))
3332
3333 (defun ad-update-regexp (regexp &optional compile)
3334 "Update functions with an advice name containing a REGEXP match.
3335 This reactivates the advice for each function
3336 that has at least one piece of advice whose name includes a match for REGEXP.
3337 See `ad-activate' for documentation on the optional COMPILE argument."
3338 (interactive
3339 (list (ad-read-regexp "Update via advice regexp")
3340 current-prefix-arg))
3341 (ad-do-advised-functions (function)
3342 (if (ad-find-some-advice function 'any regexp)
3343 (ad-update function compile))))
3344
3345 (defun ad-activate-all (&optional compile)
3346 "Activate all currently advised functions.
3347 See `ad-activate' for documentation on the optional COMPILE argument."
3348 (interactive "P")
3349 (ad-do-advised-functions (function)
3350 (ad-activate function compile)))
3351
3352 (defun ad-deactivate-all ()
3353 "Deactivate all currently advised functions."
3354 (interactive)
3355 (ad-do-advised-functions (function)
3356 (ad-deactivate function)))
3357
3358 (defun ad-update-all (&optional compile)
3359 "Update all currently advised functions.
3360 With prefix argument, COMPILE resulting advised definitions."
3361 (interactive "P")
3362 (ad-do-advised-functions (function)
3363 (ad-update function compile)))
3364
3365 (defun ad-unadvise-all ()
3366 "Unadvise all currently advised functions."
3367 (interactive)
3368 (ad-do-advised-functions (function)
3369 (ad-unadvise function)))
3370
3371 (defun ad-recover-all ()
3372 "Recover all currently advised functions. Use in emergencies.
3373 To recover a function means to try to find its original (pre-advice)
3374 definition, and delete all advice.
3375 This is more low-level than `ad-unadvise' in that it does not do
3376 deactivation, which might run hooks and get into other trouble."
3377 (interactive)
3378 (ad-do-advised-functions (function)
3379 (condition-case nil
3380 (ad-recover function)
3381 (error nil))))
3382
3383
3384 ;; Completion alist of valid `defadvice' flags
3385 (defvar ad-defadvice-flags
3386 '(("protect") ("disable") ("activate")
3387 ("compile") ("preactivate")))
3388
3389 ;;;###autoload
3390 (defmacro defadvice (function args &rest body)
3391 "Define a piece of advice for FUNCTION (a symbol).
3392 The syntax of `defadvice' is as follows:
3393
3394 \(defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3395 [DOCSTRING] [INTERACTIVE-FORM]
3396 BODY...)
3397
3398 FUNCTION ::= Name of the function to be advised.
3399 CLASS ::= `before' | `around' | `after' | `activation' | `deactivation'.
3400 NAME ::= Non-nil symbol that names this piece of advice.
3401 POSITION ::= `first' | `last' | NUMBER. Optional, defaults to `first',
3402 see also `ad-add-advice'.
3403 ARGLIST ::= An optional argument list to be used for the advised function
3404 instead of the argument list of the original. The first one found in
3405 before/around/after-advices will be used.
3406 FLAG ::= `protect'|`disable'|`activate'|`compile'|`preactivate'.
3407 All flags can be specified with unambiguous initial substrings.
3408 DOCSTRING ::= Optional documentation for this piece of advice.
3409 INTERACTIVE-FORM ::= Optional interactive form to be used for the advised
3410 function. The first one found in before/around/after-advices will be used.
3411 BODY ::= Any s-expression.
3412
3413 Semantics of the various flags:
3414 `protect': The piece of advice will be protected against non-local exits in
3415 any code that precedes it. If any around-advice of a function is protected
3416 then automatically all around-advices will be protected (the complete onion).
3417
3418 `activate': All advice of FUNCTION will be activated immediately if
3419 FUNCTION has been properly defined prior to this application of `defadvice'.
3420
3421 `compile': In conjunction with `activate' specifies that the resulting
3422 advised function should be compiled.
3423
3424 `disable': The defined advice will be disabled, hence, it will not be used
3425 during activation until somebody enables it.
3426
3427 `preactivate': Preactivates the advised FUNCTION at macro-expansion/compile
3428 time. This generates a compiled advised definition according to the current
3429 advice state that will be used during activation if appropriate. Only use
3430 this if the `defadvice' gets actually compiled.
3431
3432 See Info node `(elisp)Advising Functions' for comprehensive documentation.
3433 usage: (defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAG...)
3434 [DOCSTRING] [INTERACTIVE-FORM]
3435 BODY...)"
3436 (declare (doc-string 3)
3437 (debug (&define name ;; thing being advised.
3438 (name ;; class is [&or "before" "around" "after"
3439 ;; "activation" "deactivation"]
3440 name ;; name of advice
3441 &rest sexp ;; optional position and flags
3442 )
3443 [&optional stringp]
3444 [&optional ("interactive" interactive)]
3445 def-body)))
3446 (if (not (ad-name-p function))
3447 (error "defadvice: Invalid function name: %s" function))
3448 (let* ((class (car args))
3449 (name (if (not (ad-class-p class))
3450 (error "defadvice: Invalid advice class: %s" class)
3451 (nth 1 args)))
3452 (position (if (not (ad-name-p name))
3453 (error "defadvice: Invalid advice name: %s" name)
3454 (setq args (nthcdr 2 args))
3455 (if (ad-position-p (car args))
3456 (prog1 (car args)
3457 (setq args (cdr args))))))
3458 (arglist (if (listp (car args))
3459 (prog1 (car args)
3460 (setq args (cdr args)))))
3461 (flags
3462 (mapcar
3463 (function
3464 (lambda (flag)
3465 (let ((completion
3466 (try-completion (symbol-name flag) ad-defadvice-flags)))
3467 (cond ((eq completion t) flag)
3468 ((assoc completion ad-defadvice-flags)
3469 (intern completion))
3470 (t (error "defadvice: Invalid or ambiguous flag: %s"
3471 flag))))))
3472 args))
3473 (advice (ad-make-advice
3474 name (memq 'protect flags)
3475 (not (memq 'disable flags))
3476 `(advice lambda ,arglist ,@body)))
3477 (preactivation (if (memq 'preactivate flags)
3478 (ad-preactivate-advice
3479 function advice class position))))
3480 ;; Now for the things to be done at evaluation time:
3481 `(progn
3482 (ad-add-advice ',function ',advice ',class ',position)
3483 ,@(if preactivation
3484 `((ad-set-cache
3485 ',function
3486 ;; the function will get compiled:
3487 ,(cond ((ad-macro-p (car preactivation))
3488 `(ad-macrofy
3489 (function
3490 ,(ad-lambdafy
3491 (car preactivation)))))
3492 (t `(function
3493 ,(car preactivation))))
3494 ',(car (cdr preactivation)))))
3495 ,@(if (memq 'activate flags)
3496 `((ad-activate ',function
3497 ,(if (memq 'compile flags) t))))
3498 ',function)))
3499
3500
3501 ;; @@ Tools:
3502 ;; =========
3503
3504 (defmacro ad-with-originals (functions &rest body)
3505 "Binds FUNCTIONS to their original definitions and execute BODY.
3506 For any members of FUNCTIONS that are not currently advised the rebinding will
3507 be a noop. Any modifications done to the definitions of FUNCTIONS will be
3508 undone on exit of this macro."
3509 (declare (indent 1))
3510 (let* ((index -1)
3511 ;; Make let-variables to store current definitions:
3512 (current-bindings
3513 (mapcar (function
3514 (lambda (function)
3515 (setq index (1+ index))
3516 (list (intern (format "ad-oRiGdEf-%d" index))
3517 `(symbol-function ',function))))
3518 functions)))
3519 `(let ,current-bindings
3520 (unwind-protect
3521 (progn
3522 ,@(progn
3523 ;; Make forms to redefine functions to their
3524 ;; original definitions if they are advised:
3525 (setq index -1)
3526 (mapcar (lambda (function)
3527 (setq index (1+ index))
3528 `(fset ',function
3529 (or (ad-get-orig-definition ',function)
3530 ,(car (nth index current-bindings)))))
3531 functions))
3532 ,@body)
3533 ,@(progn
3534 ;; Make forms to back-define functions to the definitions
3535 ;; they had outside this macro call:
3536 (setq index -1)
3537 (mapcar (lambda (function)
3538 (setq index (1+ index))
3539 `(fset ',function
3540 ,(car (nth index current-bindings))))
3541 functions))))))
3542
3543
3544 ;; @@ Starting, stopping and recovering from the advice package magic:
3545 ;; ===================================================================
3546
3547 (defun ad-start-advice ()
3548 "Start the automatic advice handling magic."
3549 (interactive)
3550 ;; Advising `ad-activate-internal' means death!!
3551 (ad-set-advice-info 'ad-activate-internal nil)
3552 (fset 'ad-activate-internal 'ad-activate))
3553
3554 (defun ad-stop-advice ()
3555 "Stop the automatic advice handling magic.
3556 You should only need this in case of Advice-related emergencies."
3557 (interactive)
3558 ;; Advising `ad-activate-internal' means death!!
3559 (ad-set-advice-info 'ad-activate-internal nil)
3560 (fset 'ad-activate-internal 'ad-activate-internal-off))
3561
3562 (defun ad-recover-normality ()
3563 "Undo all advice related redefinitions and unadvises everything.
3564 Use only in REAL emergencies."
3565 (interactive)
3566 ;; Advising `ad-activate-internal' means death!!
3567 (ad-set-advice-info 'ad-activate-internal nil)
3568 (fset 'ad-activate-internal 'ad-activate-internal-off)
3569 (ad-recover-all)
3570 (ad-do-advised-functions (function)
3571 (message "Oops! Left over advised function %S" function)
3572 (ad-pop-advised-function function)))
3573
3574 (ad-start-advice)
3575
3576 (provide 'advice)
3577
3578 ;;; advice.el ends here