[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

17.1 A Simple Advice Example

The command next-line moves point down vertically one or more lines; it is the standard binding of C-n. When used on the last line of the buffer, this command inserts a newline to create a line to move to if next-line-add-newlines is non-nil (its default is nil.)

Suppose you wanted to add a similar feature to previous-line, which would insert a new line at the beginning of the buffer for the command to move to. How could you do this?

You could do it by redefining the whole function, but that is not modular. The advice feature provides a cleaner alternative: you can effectively add your code to the existing function definition, without actually changing or even seeing that definition. Here is how to do this:

 
(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))))

This expression defines a piece of advice for the function previous-line. This piece of advice is named next-line-at-end, and the symbol before says that it is before-advice which should run before the regular definition of previous-line. (arg) specifies how the advice code can refer to the function's arguments.

When this piece of advice runs, it creates an additional line, in the situation where that is appropriate, but does not move point to that line. This is the correct way to write the advice, because the normal definition will run afterward and will move back to the newly inserted line.

Defining the advice doesn't immediately change the function previous-line. That happens when you activate the advice, like this:

 
(ad-activate 'previous-line)

This is what actually begins to use the advice that has been defined so far for the function previous-line. Henceforth, whenever that function is run, whether invoked by the user with C-p or M-x, or called from Lisp, it runs the advice first, and its regular definition second.

This example illustrates before-advice, which is one class of advice: it runs before the function's base definition. There are two other advice classes: after-advice, which runs after the base definition, and around-advice, which lets you specify an expression to wrap around the invocation of the base definition.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on May 2, 2002 using texi2html