Ads by Google

Thursday, July 21, 2011

A Visual Guide to Narrowing in Emacs

 Every once in a while, you'd hear someone talk about narrowing in Emacs and you'd wonder what they're talking about.  The idea behind narrowing is that, you might be interested in only a certain portion of the file/buffer you're working on and you'd like to work on that portion alone and nothing else.  Narrowing allows you to do that by simply eliminates from your viewing, any other extraneous lines other than the highlighted ones.  Here's an example

In the screenshot above, let's say I want to work on the rows only upto to 10-Jan-2006 in a file containing 1000s of rows.  Mark the region and hit C-x n n.

 The rest of the lines are gone and only the marked region is left.  Now, you can work on the narrowed region as usual; the normal editing editing commands apply. Once you've completed the changes, you can get your complete buffer back by using C-x n w which widens the buffer or cancels narrowing.  For example, I've changed ABB to XXX in the narrowed region and reverted to the normal buffer by C-x n w.

 That's it. A couple of points are in order. It is disabled by default, so you'd want to enable it by adding the following to your .emacs
;;;enable narrowing
(put 'narrow-to-region 'disabled nil)
If you're confused whether narrowing is in effect or not, the modeline should have the word Narrow in it as a visual indication.  Lastly, the hidden text and lines are not gone even if you save with narrowing in effect, so you really don't need to panic that you've accidently overwritten the entire file or any other pant turding fear!