@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1998, 1999 Free Software Foundation, Inc.@c See the file elisp.texi for copying conditions.@setfilename ../info/advising@node Advising Functions, Debugging, Byte Compilation, Top@chapter Advising Emacs Lisp Functions@cindex advising functions The @dfn{advice} feature lets you add to the existing definition of afunction, by @dfn{advising the function}. This is a clean method for alibrary to customize functions defined by other parts of Emacs---cleanerthan redefining the whole function.@cindex piece of advice Each function can have multiple @dfn{pieces of advice}, separatelydefined. Each defined piece of advice can be @dfn{enabled} ordisabled explicitly. All the enabled pieces of advice for any givenfunction actually take effect when you @dfn{activate} advice for thatfunction, or when you define or redefine the function. Note thatenabling a piece of advice and activating advice for a functionare not the same thing. @strong{Usage Note:} Advice is useful for altering the behavior ofexisting calls to an existing function. If you want the new behaviorfor new calls, or for key bindings, it is cleaner to define a newfunction (or a new command) which uses the existing function.@menu* Simple Advice:: A simple example to explain the basics of advice.* Defining Advice:: Detailed description of @code{defadvice}.* Around-Advice:: Wrapping advice around a function's definition.* Computed Advice:: ...is to @code{defadvice} as @code{fset} is to @code{defun}.* Activation of Advice:: Advice doesn't do anything until you activate it.* Enabling Advice:: You can enable or disable each piece of advice.* Preactivation:: Preactivation is a way of speeding up the loading of compiled advice.* Argument Access in Advice:: How advice can access the function's arguments.* Advising Primitives:: Accessing arguments when advising a primitive.* Combined Definition:: How advice is implemented.@end menu@node Simple Advice@section A Simple Advice Example The command @code{next-line} moves point down vertically one or morelines; it is the standard binding of @kbd{C-n}. When used on the lastline of the buffer, this command inserts a newline to create a line tomove to if @code{next-line-add-newlines} is non-@code{nil} (its defaultis @code{nil}.) Suppose you wanted to add a similar feature to @code{previous-line},which would insert a new line at the beginning of the buffer for thecommand to move to. How could you do this? You could do it by redefining the whole function, but that is notmodular. The advice feature provides a cleaner alternative: you caneffectively add your code to the existing function definition, withoutactually changing or even seeing that definition. Here is how to dothis:@example(defadvice previous-line (before next-line-at-end (arg)) "Insert an empty line when moving up from the top line." (if (and next-line-add-newlines (= arg 1) (save-excursion (beginning-of-line) (bobp))) (progn (beginning-of-line) (newline))))@end example This expression defines a @dfn{piece of advice} for the function@code{previous-line}. This piece of advice is named@code{next-line-at-end}, and the symbol @code{before} says that it is@dfn{before-advice} which should run before the regular definition of@code{previous-line}. @code{(arg)} specifies how the advice code canrefer to the function's arguments. When this piece of advice runs, it creates an additional line, in thesituation where that is appropriate, but does not move point to thatline. This is the correct way to write the advice, because the normaldefinition will run afterward and will move back to the newly insertedline. Defining the advice doesn't immediately change the function@code{previous-line}. That happens when you @dfn{activate} the advice,like this:@example(ad-activate 'previous-line)@end example@noindentThis is what actually begins to use the advice that has been defined sofar for the function @code{previous-line}. Henceforth, whenever thatfunction is run, whether invoked by the user with @kbd{C-p} or@kbd{M-x}, or called from Lisp, it runs the advice first, and itsregular definition second. This example illustrates before-advice, which is one @dfn{class} ofadvice: it runs before the function's base definition. There are twoother advice classes: @dfn{after-advice}, which runs after the basedefinition, and @dfn{around-advice}, which lets you specify anexpression to wrap around the invocation of the base definition.@node Defining Advice@section Defining Advice@cindex defining advice@cindex advice, defining To define a piece of advice, use the macro @code{defadvice}. A callto @code{defadvice} has the following syntax, which is based on thesyntax of @code{defun} and @code{defmacro}, but adds more:@findex defadvice@example(defadvice @var{function} (@var{class} @var{name} @r{[}@var{position}@r{]} @r{[}@var{arglist}@r{]} @var{flags}...) @r{[}@var{documentation-string}@r{]} @r{[}@var{interactive-form}@r{]} @var{body-forms}...)@end example@noindentHere, @var{function} is the name of the function (or macro or specialform) to be advised. From now on, we will write just ``function'' whendescribing the entity being advised, but this always includes macros andspecial forms.@cindex class of advice@cindex before-advice@cindex after-advice@cindex around-advice@var{class} specifies the @dfn{class} of the advice---one of @code{before},@code{after}, or @code{around}. Before-advice runs before the functionitself; after-advice runs after the function itself; around-advice iswrapped around the execution of the function itself. After-advice andaround-advice can override the return value by setting@code{ad-return-value}.@defvar ad-return-valueWhile advice is executing, after the function's original definition hasbeen executed, this variable holds its return value, which willultimately be returned to the caller after finishing all the advice.After-advice and around-advice can arrange to return some other valueby storing it in this variable.@end defvarThe argument @var{name} is the name of the advice, a non-@code{nil}symbol. The advice name uniquely identifies one piece of advice, within allthe pieces of advice in a particular class for a particular@var{function}. The name allows you to refer to the piece ofadvice---to redefine it, or to enable or disable it.In place of the argument list in an ordinary definition, an advicedefinition calls for several different pieces of information.The optional @var{position} specifies where, in the current list ofadvice of the specified @var{class}, this new advice should be placed.It should be either @code{first}, @code{last} or a number that specifiesa zero-based position (@code{first} is equivalent to 0). If no positionis specified, the default is @code{first}. Position values outside therange of existing positions in this class are mapped to the beginning orthe end of the range, whichever is closer. The @var{position} value isignored when redefining an existing piece of advice.The optional @var{arglist} can be used to define the argument list forthe sake of advice. This becomes the argument list of the combineddefinition that is generated in order to run the advice (@pxref{CombinedDefinition}). Therefore, the advice expressions can use the argumentvariables in this list to access argument values.The argument list used in advice need not be the same as the argumentlist used in the original function, but must be compatible with it, sothat it can handle the ways the function is actually called. If twopieces of advice for a function both specify an argument list, they mustspecify the same argument list.@xref{Argument Access in Advice}, for more information about argumentlists and advice, and a more flexible way for advice to access thearguments.The remaining elements, @var{flags}, are symbols that specify furtherinformation about how to use this piece of advice. Here are the validsymbols and their meanings:@table @code@item activateActivate the advice for @var{function} now. Changes in a function'sadvice always take effect the next time you activate advice for thefunction; this flag says to do so, for @var{function}, immediately afterdefining this piece of advice.@cindex forward adviceThis flag has no immediate effect if @var{function} itself is not defined yet (asituation known as @dfn{forward advice}), because it is impossible toactivate an undefined function's advice. However, defining@var{function} will automatically activate its advice.@item protectProtect this piece of advice against non-local exits and errors inpreceding code and advice. Protecting advice places it as a cleanup inan @code{unwind-protect} form, so that it will execute even if theprevious code gets an error or uses @code{throw}. @xref{Cleanups}.@item compileCompile the combined definition that is used to run the advice. Thisflag is ignored unless @code{activate} is also specified.@xref{Combined Definition}.@item disableInitially disable this piece of advice, so that it will not be usedunless subsequently explicitly enabled. @xref{Enabling Advice}.@item preactivateActivate advice for @var{function} when this @code{defadvice} iscompiled or macroexpanded. This generates a compiled advised definitionaccording to the current advice state, which will be used duringactivation if appropriate. @xref{Preactivation}.This is useful only if this @code{defadvice} is byte-compiled.@end tableThe optional @var{documentation-string} serves to document this piece ofadvice. When advice is active for @var{function}, the documentation for@var{function} (as returned by @code{documentation}) combines thedocumentation strings of all the advice for @var{function} with thedocumentation string of its original function definition.The optional @var{interactive-form} form can be supplied to change theinteractive behavior of the original function. If more than one pieceof advice has an @var{interactive-form}, then the first one (the onewith the smallest position) found among all the advice takes precedence.The possibly empty list of @var{body-forms} specifies the body of theadvice. The body of an advice can access or change the arguments, thereturn value, the binding environment, and perform any other kind ofside effect.@strong{Warning:} When you advise a macro, keep in mind that macros areexpanded when a program is compiled, not when a compiled program is run.All subroutines used by the advice need to be available when the bytecompiler expands the macro.@deffn Command ad-unadvise functionThis command deletes the advice from @var{function}.@end deffn@deffn Command ad-unadvise-allThis command deletes all pieces of advice from all functions.@end deffn@node Around-Advice@section Around-Advice Around-advice lets you ``wrap'' a Lisp expression ``around'' theoriginal function definition. You specify where the original functiondefinition should go by means of the special symbol @code{ad-do-it}.Where this symbol occurs inside the around-advice body, it is replacedwith a @code{progn} containing the forms of the surrounded code. Hereis an example:@example(defadvice foo (around foo-around) "Ignore case in `foo'." (let ((case-fold-search t)) ad-do-it))@end example@noindentIts effect is to make sure that case is ignored insearches when the original definition of @code{foo} is run.@defvar ad-do-itThis is not really a variable, but it is somewhat used like onein around-advice. It specifies the place to run the function'soriginal definition and other ``earlier'' around-advice.@end defvarIf the around-advice does not use @code{ad-do-it}, then it does not runthe original function definition. This provides a way to override theoriginal definition completely. (It also overrides lower-positionedpieces of around-advice).If the around-advice uses @code{ad-do-it} more than once, the originaldefinition is run at each place. In this way, around-advice can executethe original definition (and lower-positioned pieces of around-advice)several times. Another way to do that is by using @code{ad-do-it}inside of a loop.@node Computed Advice@section Computed AdviceThe macro @code{defadvice} resembles @code{defun} in that the code forthe advice, and all other information about it, are explicitly stated inthe source code. You can also create advice whose details are computed,using the function @code{ad-add-advice}.@defun ad-add-advice function advice class positionCalling @code{ad-add-advice} adds @var{advice} as a piece of advice to@var{function} in class @var{class}. The argument @var{advice} hasthis form:@example(@var{name} @var{protected} @var{enabled} @var{definition})@end exampleHere @var{protected} and @var{enabled} are flags, and @var{definition}is the expression that says what the advice should do. If @var{enabled}is @code{nil}, this piece of advice is initially disabled(@pxref{Enabling Advice}).If @var{function} already has one or more pieces of advice in thespecified @var{class}, then @var{position} specifies where in the listto put the new piece of advice. The value of @var{position} can eitherbe @code{first}, @code{last}, or a number (counting from 0 at thebeginning of the list). Numbers outside the range are mapped to thebeginning or the end of the range, whichever is closer. The@var{position} value is ignored when redefining an existing piece ofadvice.If @var{function} already has a piece of @var{advice} with the samename, then the position argument is ignored and the old advice isreplaced with the new one.@end defun@node Activation of Advice@section Activation of Advice@cindex activating advice@cindex advice, activatingBy default, advice does not take effect when you define it---only whenyou @dfn{activate} advice for the function that was advised. Howeverthe advice will be automatically activated if the function is definedor redefined later. You can request the activation of advice for afunction when you define the advice, by specifying the @code{activate}flag in the @code{defadvice}. But normally you activate the advicefor a function by calling the function @code{ad-activate} or one ofthe other activation commands listed below.Separating the activation of advice from the act of defining it permitsyou to add several pieces of advice to one function efficiently, withoutredefining the function over and over as each advice is added. Moreimportantly, it permits defining advice for a function before thatfunction is actually defined.When a function's advice is first activated, the function's originaldefinition is saved, and all enabled pieces of advice for that functionare combined with the original definition to make a new definition.(Pieces of advice that are currently disabled are not used; see@ref{Enabling Advice}.) This definition is installed, and optionallybyte-compiled as well, depending on conditions described below.In all of the commands to activate advice, if @var{compile} is @code{t},the command also compiles the combined definition which implements theadvice.@deffn Command ad-activate function &optional compileThis command activates all the advice defined for @var{function}.@end deffnTo activate advice for a function whose advice is already active is nota no-op. It is a useful operation which puts into effect any changes inthat function's advice since the previous activation of advice for thatfunction.@deffn Command ad-deactivate functionThis command deactivates the advice for @var{function}.@cindex deactivating advice@cindex advice, deactivating@end deffn@deffn Command ad-update function &optional compileThis command activates the advice for @var{function}if its advice is already activated. This is usefulif you change the advice.@end deffn@deffn Command ad-activate-all &optional compileThis command activates the advice for all functions.@end deffn@deffn Command ad-deactivate-allThis command deactivates the advice for all functions.@end deffn@deffn Command ad-update-all &optional compileThis command activates the advice for all functionswhose advice is already activated. This is usefulif you change the advice of some functions.@end deffn@deffn Command ad-activate-regexp regexp &optional compileThis command activates all pieces of advice whose names match@var{regexp}. More precisely, it activates all advice for any functionwhich has at least one piece of advice that matches @var{regexp}.@end deffn@deffn Command ad-deactivate-regexp regexpThis command deactivates all pieces of advice whose names match@var{regexp}. More precisely, it deactivates all advice for anyfunction which has at least one piece of advice that matches@var{regexp}.@end deffn@deffn Command ad-update-regexp regexp &optional compileThis command activates pieces of advice whose names match @var{regexp},but only those for functions whose advice is already activated.@cindex reactivating adviceReactivating a function's advice is useful for putting into effect allthe changes that have been made in its advice (including enabling anddisabling specific pieces of advice; @pxref{Enabling Advice}) since thelast time it was activated.@end deffn@deffn Command ad-start-adviceTurn on automatic advice activation when a function is defined orredefined. This is the default mode.@end deffn@deffn Command ad-stop-adviceTurn off automatic advice activation when a function is defined orredefined.@end deffn@defopt ad-default-compilation-actionThis variable controls whether to compile the combined definitionthat results from activating advice for a function.A value of @code{always} specifies to compile unconditionally.A value of @code{nil} specifies never compile the advice.A value of @code{maybe} specifies to compile if the byte-compiler isalready loaded. A value of @code{like-original} specifies to compilethe advice if the original definition of the advised function iscompiled or a built-in function.This variable takes effect only if the @var{compile} argument of@code{ad-activate} (or any of the above functions) was supplied as@code{nil}. If that argument is non-@code{nil}, that meansto compile the advice regardless.@end defopt If the advised definition was constructed during ``preactivation''(@pxref{Preactivation}), then that definition must already be compiled,because it was constructed during byte-compilation of the file thatcontained the @code{defadvice} with the @code{preactivate} flag.@node Enabling Advice@section Enabling and Disabling Advice@cindex enabling advice@cindex advice, enabling and disabling@cindex disabling advice Each piece of advice has a flag that says whether it is enabled ornot. By enabling or disabling a piece of advice, you can turn it onand off without having to undefine and redefine it. For example, here ishow to disable a particular piece of advice named @code{my-advice} forthe function @code{foo}:@example(ad-disable-advice 'foo 'before 'my-advice)@end example This function by itself only changes the enable flag for a piece ofadvice. To make the change take effect in the advised definition, youmust activate the advice for @code{foo} again:@example(ad-activate 'foo)@end example@deffn Command ad-disable-advice function class nameThis command disables the piece of advice named @var{name} in class@var{class} on @var{function}.@end deffn@deffn Command ad-enable-advice function class nameThis command enables the piece of advice named @var{name} in class@var{class} on @var{function}.@end deffn You can also disable many pieces of advice at once, for variousfunctions, using a regular expression. As always, the changes take realeffect only when you next reactivate advice for the functions inquestion.@deffn Command ad-disable-regexp regexpThis command disables all pieces of advice whose names match@var{regexp}, in all classes, on all functions.@end deffn@deffn Command ad-enable-regexp regexpThis command enables all pieces of advice whose names match@var{regexp}, in all classes, on all functions.@end deffn@node Preactivation@section Preactivation@cindex preactivating advice@cindex advice, preactivating Constructing a combined definition to execute advice is moderatelyexpensive. When a library advises many functions, this can make loadingthe library slow. In that case, you can use @dfn{preactivation} toconstruct suitable combined definitions in advance. To use preactivation, specify the @code{preactivate} flag when youdefine the advice with @code{defadvice}. This @code{defadvice} callcreates a combined definition which embodies this piece of advice(whether enabled or not) plus any other currently enabled advice for thesame function, and the function's own definition. If the@code{defadvice} is compiled, that compiles the combined definitionalso. When the function's advice is subsequently activated, if the enabledadvice for the function matches what was used to make this combineddefinition, then the existing combined definition is used, thus avoidingthe need to construct one. Thus, preactivation never causes wrongresults---but it may fail to do any good, if the enabled advice at thetime of activation doesn't match what was used for preactivation. Here are some symptoms that can indicate that a preactivation did notwork properly, because of a mismatch.@itemize @bullet@itemActivation of the advisedfunction takes longer than usual.@itemThe byte-compiler getsloaded while an advised function gets activated.@item@code{byte-compile} is included in the value of @code{features} eventhough you did not ever explicitly use the byte-compiler.@end itemizeCompiled preactivated advice works properly even if the function itselfis not defined until later; however, the function needs to be definedwhen you @emph{compile} the preactivated advice.There is no elegant way to find out why preactivated advice is not beingused. What you can do is to trace the function@code{ad-cache-id-verification-code} (with the function@code{trace-function-background}) before the advised function's adviceis activated. After activation, check the value returned by@code{ad-cache-id-verification-code} for that function: @code{verified}means that the preactivated advice was used, while other values givesome information about why they were considered inappropriate. @strong{Warning:} There is one known case that can make preactivationfail, in that a preconstructed combined definition is used even thoughit fails to match the current state of advice. This can happen when twopackages define different pieces of advice with the same name, in thesame class, for the same function. But you should avoid that anyway.@node Argument Access in Advice@section Argument Access in Advice The simplest way to access the arguments of an advised function in thebody of a piece of advice is to use the same names that the functiondefinition uses. To do this, you need to know the names of the argumentvariables of the original function. While this simple method is sufficient in many cases, it has adisadvantage: it is not robust, because it hard-codes the argument namesinto the advice. If the definition of the original function changes,the advice might break. Another method is to specify an argument list in the advice itself.This avoids the need to know the original function definition's argumentnames, but it has a limitation: all the advice on any particularfunction must use the same argument list, because the argument listactually used for all the advice comes from the first piece of advicefor that function. A more robust method is to use macros that are translated into theproper access forms at activation time, i.e., when constructing theadvised definition. Access macros access actual arguments by positionregardless of how these actual arguments get distributed onto theargument variables of a function. This is robust because in Emacs Lispthe meaning of an argument is strictly determined by its position in theargument list.@defmac ad-get-arg positionThis returns the actual argument that was supplied at @var{position}.@end defmac@defmac ad-get-args positionThis returns the list of actual arguments supplied starting at@var{position}.@end defmac@defmac ad-set-arg position valueThis sets the value of the actual argument at @var{position} to@var{value}@end defmac@defmac ad-set-args position value-listThis sets the list of actual arguments starting at @var{position} to@var{value-list}.@end defmac Now an example. Suppose the function @code{foo} is defined as@example(defun foo (x y &optional z &rest r) ...)@end example@noindentand is then called with@example(foo 0 1 2 3 4 5 6)@end example@noindentwhich means that @var{x} is 0, @var{y} is 1, @var{z} is 2 and @var{r} is@code{(3 4 5 6)} within the body of @code{foo}. Here is what@code{ad-get-arg} and @code{ad-get-args} return in this case:@example(ad-get-arg 0) @result{} 0(ad-get-arg 1) @result{} 1(ad-get-arg 2) @result{} 2(ad-get-arg 3) @result{} 3(ad-get-args 2) @result{} (2 3 4 5 6)(ad-get-args 4) @result{} (4 5 6)@end example Setting arguments also makes sense in this example:@example(ad-set-arg 5 "five")@end example@noindenthas the effect of changing the sixth argument to @code{"five"}. If thishappens in advice executed before the body of @code{foo} is run, then@var{r} will be @code{(3 4 "five" 6)} within that body. Here is an example of setting a tail of the argument list:@example(ad-set-args 0 '(5 4 3 2 1 0))@end example@noindentIf this happens in advice executed before the body of @code{foo} is run,then within that body, @var{x} will be 5, @var{y} will be 4, @var{z}will be 3, and @var{r} will be @code{(2 1 0)} inside the body of@code{foo}. These argument constructs are not really implemented as Lisp macros.Instead they are implemented specially by the advice mechanism.@node Advising Primitives@section Advising Primitives Advising a primitive function (also called a ``subr'') is risky.Some primitive functions are used by the advice mechanism; advisingthem could cause an infinite recursion. Also, many primitivefunctions are called directly from C code. Calls to the primitivefrom Lisp code will take note of the advice, but calls from C codewill ignore the advice.When the advice facility constructs the combined definition, it needsto know the argument list of the original function. This is notalways possible for primitive functions. When advice cannot determinethe argument list, it uses @code{(&rest ad-subr-args)}, which alwaysworks but is inefficient because it constructs a list of the argumentvalues. You can use @code{ad-define-subr-args} to declare the properargument names for a primitive function:@defun ad-define-subr-args function arglistThis function specifies that @var{arglist} should be used as theargument list for function @var{function}.@end defunFor example,@example(ad-define-subr-args 'fset '(sym newdef))@end example@noindentspecifies the argument list for the function @code{fset}.@node Combined Definition@section The Combined Definition Suppose that a function has @var{n} pieces of before-advice(numbered from 0 through @var{n}@minus{}1), @var{m} pieces ofaround-advice and @var{k} pieces of after-advice. Assuming no pieceof advice is protected, the combined definition produced to implementthe advice for a function looks like this:@example(lambda @var{arglist} @r{[} @r{[}@var{advised-docstring}@r{]} @r{[}(interactive ...)@r{]} @r{]} (let (ad-return-value) @r{before-0-body-form}... .... @r{before-@var{n}@minus{}1-body-form}... @r{around-0-body-form}... @r{around-1-body-form}... .... @r{around-@var{m}@minus{}1-body-form}... (setq ad-return-value @r{apply original definition to @var{arglist}}) @r{end-of-around-@var{m}@minus{}1-body-form}... .... @r{end-of-around-1-body-form}... @r{end-of-around-0-body-form}... @r{after-0-body-form}... .... @r{after-@var{k}@minus{}1-body-form}... ad-return-value))@end exampleMacros are redefined as macros, which means adding @code{macro} tothe beginning of the combined definition.The interactive form is present if the original function or some pieceof advice specifies one. When an interactive primitive function isadvised, advice uses a special method: it calls the primitive with@code{call-interactively} so that it will read its own arguments.In this case, the advice cannot access the arguments.The body forms of the various advice in each class are assembledaccording to their specified order. The forms of around-advice @var{l}are included in one of the forms of around-advice @var{l} @minus{} 1.The innermost part of the around advice onion is@displayapply original definition to @var{arglist}@end display@noindentwhose form depends on the type of the original function. The variable@code{ad-return-value} is set to whatever this returns. The variable isvisible to all pieces of advice, which can access and modify it beforeit is actually returned from the advised function.The semantic structure of advised functions that contain protectedpieces of advice is the same. The only difference is that@code{unwind-protect} forms ensure that the protected advice getsexecuted even if some previous piece of advice had an error or anon-local exit. If any around-advice is protected, then the wholearound-advice onion is protected as a result.@ignore arch-tag: 80c135c2-f1c3-4f8d-aa85-f8d8770d307f@end ignore