Next: , Previous: , Up: Positions   [Contents][Index]


41.3 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 saves the current buffer and its values of point and the mark so they can be restored after the completion of the excursion.

The forms for saving and restoring the configuration of windows are described elsewhere (see Window Configurations and see 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 (see 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 500 times in the Lisp sources of SXEmacs.

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 (see 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)))
Special Form: save-current-buffer forms…

This special form is similar to save-excursion but it only saves and restores the current buffer. Beginning with XEmacs 20.3, save-current-buffer is a primitive.

Special Form: with-current-buffer buffer forms…

This special form evaluates forms with buffer as the current buffer. It returns the value of the last form.

Special Form: with-temp-file filename forms…

This special form creates a new buffer, evaluates forms there, and writes the buffer to filename. It returns the value of the last form evaluated.

Special Form: save-selected-window forms…

This special form is similar to save-excursion but it saves and restores the selected window and nothing else.


Next: , Previous: , Up: Positions   [Contents][Index]