Next: , Previous: Narrowing advantages, Up: Narrowing & Widening

6.1 The save-restriction Special Form

In Emacs Lisp, you can use the save-restriction special form to keep track of whatever narrowing is in effect, if any. When the Lisp interpreter meets with save-restriction, it executes the code in the body of the save-restriction expression, and then undoes any changes to narrowing that the code caused. If, for example, the buffer is narrowed and the code that follows save-restriction gets rid of the narrowing, save-restriction returns the buffer to its narrowed region afterwards. In the what-line command, any narrowing the buffer may have is undone by the widen command that immediately follows the save-restriction command. Any original narrowing is restored just before the completion of the function.

The template for a save-restriction expression is simple:

     (save-restriction
       body... )

The body of the save-restriction is one or more expressions that will be evaluated in sequence by the Lisp interpreter.

Finally, a point to note: when you use both save-excursion and save-restriction, one right after the other, you should use save-excursion outermost. If you write them in reverse order, you may fail to record narrowing in the buffer to which Emacs switches after calling save-excursion. Thus, when written together, save-excursion and save-restriction should be written like this:

     (save-excursion
       (save-restriction
         body...))

In other circumstances, when not written together, the save-excursion and save-restriction special forms must be written in the order appropriate to the function.

For example,

       (save-restriction
         (widen)
         (save-excursion
         body...))