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