The Emacs defadvice Macro

Evgkeni Sampelnikof has posted a nice introduction to defadvice. Emacs is all about having it your way and making it easy to do so. Very often it's convenient to change the behavior of a built in command and since Emacs has no secrets we can always plunk a copy of the command's source code into our .emacs file and modify it to produce the desired behavior. Unfortunately, that strategy produces a maintenance problem and adds to the clutter of your (probably overly cluttered) .emacs file.

In many situations, a better way is to use the defadvice macro. It allows you to perform some action before and/or after the command is executed. See Sampelnikof's post for the details. An excellent example of when you might want to use defadvice was given by Magnar Sveen in his What the .emacs.d!? post about restoring the screen configuration after a call to Magit. That's a tremendously useful modification to the magit code and I can't imagine any magit user not wanting it. Happily, it trivial to implement with defadvice.

This entry was posted in Programming and tagged . Bookmark the permalink.
  • Phil

    FYI there's also an alternative 'lightweight' advice library in the works in Emacs' trunk, which will enable you to jump to the advice definition with find-function (due to the advice being implemented as functions).

    Being able to see that a function was advised, yet not be able to trivially find the code, always seemed like a notable failing of the system (albeit not too bad, as advice would typically have been introduced by yourself, so you'd have a pretty good idea where to grep for it).

    You can take a look at the new library here: