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