BasicNarrowing

Narrowing shows only part of the buffer – a contiguous block of text, hiding the rest. The part showing can be specified by the region, a `defun, or a page.

When narrowing is in effect, the excluded portions of the buffer are not seen, and some commands ignore them altogether. When saving, the entire buffer is written.

See Also:

Narrowing and Widening Commands

The narrowing commands are DisabledCommands because they can confuse users who are unfamiliar with narrowing. You can enable them by using command ‘enable-command’ or by putting the following EmacsLisp code in your init file:

    (put 'narrow-to-defun  'disabled nil)
    (put 'narrow-to-page   'disabled nil)
    (put 'narrow-to-region 'disabled nil)

Each of these narrowing commands is bound to a key with prefix ‘C-x n’.

When the buffer is narrowed, the mode line indicates this with the word ‘Narrow’ in the MinorMode portion.

To widen the buffer (cancel the narrowing), click ‘Narrow’ in the mode line with ‘mouse-2’, or invoke command ‘widen’, using ‘C-x n w’. Widening always exposes the whole buffer (but see MultipleNarrowings).

Narrowing Example

I often replace a regular expression, but want to limit its effective region:

    (defun replace-regexp-in-region (start end)
      (interactive "*r")
      (save-excursion
        (save-restriction
          (let ((regexp (read-string "Regexp: "))
                (to-string (read-string "Replacement: ")))
            (narrow-to-region start end)
            (goto-char (point-min))
            (while (re-search-forward regexp nil t)
              (replace-match to-string nil nil))))))

CUA-mode and narrow-to-region

In CUA-mode C-x is doing “cut” when the region is highlighted. Then obviously C-x n n can’t run narrow-to-region. It is easy to work around the problem: Just move the point back and forward one char. This will dehighlight the region but it is still there. So now C-x n n will run narrow-to-region.


CategoryRegion CategoryHideStuff