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