[[zh:Advice-zh]]
Advice is how you modify existing functions in your configuration.
Using advice should be you last resort.
Please check whether there are any hooks or options to achieve what you want to do before using advice.
See [[AdviceVsHooks|advice vs. hooks]] to learn more.

Here's an example:

{{{
(advice-add 'rcirc-handler-NICK :before #'rcirc-color--handler-NICK)
(defun rcirc-color--handler-NICK (_process sender args _text)
  "Update colors in `rcirc-color-mapping'."
  (let* ((old-nick (rcirc-user-nick sender))
         (cell (gethash old-nick rcirc-color-mapping))
         (new-nick (car args)))
    ;; don't delete the old mapping
    (when cell
      (puthash new-nick cell rcirc-color-mapping))))
}}}

We have an existing function ##rcirc-handler-NICK## and we want to add some colour handling to it.
Note how we prefix the arguments we're not going to use with an underscore.

There are various places where advice can happen:

##:before## (as in the example above) is just that: it happens before the original function is called.

##:after## happens after the original function is called.

##:override## happens instead of the original function being called.

##:around## is special: it happens instead of the original function being called but you get the old function definition in an extra argument so you can still run the old code, if you need to.

See [[Manual:Advice combinators]] for more info.

-----
=== Another simple example using nadvice advice-add ===

This is a near-minimal example of using ##advice-add## to change the behaviour of a function. This code advises ##display-buffer## to first delete all windows but the active window, thus resulting in two windows only being shown:

{{{
(advice-add 
   'display-buffer    ; function to be advised
   :before            ; advice runs first
   (lambda (&rest r) (delete-other-windows)) ; advising function, this must have the same argument list as the main function, in this case all absorbed into a list "r"
   '((name . "test"))) ; convenient name for identifying or removing this advice later
}}}

And this removes the advice:
{{{
(advice-remove 'display-buffer "test")
}}}


----
CategoryCode
