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