GNU Info

Info Node: (elisp)Excursions

(elisp)Excursions


Next: Narrowing Prev: Motion Up: Positions
Enter node , (file) or (file)node

Excursions
==========

   It is often useful to move point "temporarily" within a localized
portion of the program, or to switch buffers temporarily.  This is
called an "excursion", and it is done with the `save-excursion' special
form.  This construct initially remembers the identity of the current
buffer, and its values of point and the mark, and restores them after
the completion of the excursion.

   The forms for saving and restoring the configuration of windows are
described elsewhere (see Note: Window Configurations, and Note: Frame
Configurations).

 - Special Form: save-excursion forms...
     The `save-excursion' special form saves the identity of the current
     buffer and the values of point and the mark in it, evaluates
     FORMS, and finally restores the buffer and its saved values of
     point and the mark.  All three saved values are restored even in
     case of an abnormal exit via `throw' or error (Note: Nonlocal
     Exits).

     The `save-excursion' special form is the standard way to switch
     buffers or move point within one part of a program and avoid
     affecting the rest of the program.  It is used more than 4000
     times in the Lisp sources of Emacs.

     `save-excursion' does not save the values of point and the mark for
     other buffers, so changes in other buffers remain in effect after
     `save-excursion' exits.

     Likewise, `save-excursion' does not restore window-buffer
     correspondences altered by functions such as `switch-to-buffer'.
     One way to restore these correspondences, and the selected window,
     is to use `save-window-excursion' inside `save-excursion' (Note:
     Window Configurations).

     The value returned by `save-excursion' is the result of the last of
     FORMS, or `nil' if no FORMS are given.

          (save-excursion FORMS)
          ==
          (let ((old-buf (current-buffer))
                (old-pnt (point-marker))
                (old-mark (copy-marker (mark-marker))))
            (unwind-protect
                (progn FORMS)
              (set-buffer old-buf)
              (goto-char old-pnt)
              (set-marker (mark-marker) old-mark)))

   *Warning:* Ordinary insertion of text adjacent to the saved point
value relocates the saved value, just as it relocates all markers.
Therefore, when the saved point value is restored, it normally comes
before the inserted text.

   Although `save-excursion' saves the location of the mark, it does
not prevent functions which modify the buffer from setting
`deactivate-mark', and thus causing the deactivation of the mark after
the command finishes.  Note: The Mark.


automatically generated by info2www version 1.2.2.9