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