Getting into the Straights in Emacs with Narrowing

Topic: Narrowing

Narrowing defined

When you "narrow" you focus on what matters to you in a buffer.

You get Emacs to show you only what you need to see. This portion is called the accessible portion.

To get out of narrowing one widens the buffer again.

When working with narrowing the part of the buffer you have hidden is still there, you just cannot see it or effect it.

The narrowing command is disabled by default because it "confuses" new users. When you run it for the first time you have to give Emacs permission. Choose !

Use cases

Useful for large files when you want to focus your work on a set of lines, a paragraph or a function.

E.g. You want to focus on lines 20 through 30. Narrowing avoids clutter in the buffer.

It can also be used to limit the range of operation for a find/replace command or a macro.

With find and replace one can use a region focus a command, but narrowing allows a more persistent focus and with it one is less inclined to make mistakes.

It is also useful for commands that only operate on entire buffers, e.g. ispell-buffer.

Note: Narrowing is indicated on the mode-line when active.

Prefix key for narrowing

C-x n

Main Commands

C-x n n

Narrow to region (‘narrow-to-region’).

C-x n w

Widen to make the entire buffer accessible again (‘widen’).

C-x n p

Narrow down to the current page (‘narrow-to-page’).

Note: In Emacs a "page" is not N number of lines but a section delimited by the user using the form feed character ^L.

This is quite different from software like Microsoft Word, where a page is typically defined by physical dimensions (like an A4 or Letter-sized sheet) or a specific numbers of lines.

Emacs does not create pages for you. You create pages in Emacs!

To create a page in Emacs type C-q C-l which will insert the form feed character ^L.

C-x n d

Narrow down to the current defun (‘narrow-to-defun’).

  ;; Duplicate a line in Emacs
(defun duplicate-line ()
  "Duplicate the current line."
  (interactive)
  (move-beginning-of-line 1)
  (kill-line)
  (yank)
  (open-line 1)
  (next-line 1)
  (yank))

(global-set-key (kbd "S-C-d") 'duplicate-line)

Note: You can get information on what part of the buffer you are narrowed using the C-x = command.

Return to Home