Elisp: Save narrow-to-region

By Xah Lee. Date: .

Emacs has a narrow-to-region command. It lets users make the buffor show only the selected region, as if the entire buffer is just that text. This is convenient when you want to do some editing only in this region. Alt+x widen will make buffer show whole buffer again.

The narrow-to-region is also super useful in elisp code. However, when you command is done, you should return to the narrow region state of the user before the command was called. Emacs lisp provides save-restriction for this purpose.

save-restriction(save-restriction &rest BODY) Execute BODY, saving and restoring user's narrow-to-region .

In elisp code, when you call narrow-to-region, you almost always want to wrap it with save-restriction, like this:

;; preserve user's narrow-to-region
;; useful when you want to narrow-to-region in your code to work in just that region
  (narrow-to-region pos1 pos2)
  ;; lisp code here

(info "(elisp) Positions")

If you have a question, put $5 at patreon and message me.
Or Buy Xah Emacs Tutorial
Or buy JavaScript in Depth

Emacs Tutorial

Emacs Init

Emacs Keys


ELisp Examples

ELisp Write Major Mode

Emacs Lisp


Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc