Friday, October 19, 2012

Reformatting for 80 characters in vim

After reading The Pragmatic Programmer and Clean Code, I've pretty much settled on using text files (specifically in markdown format) for all my personal notes and documentation and editing them with vim.  That being said, I like to keep my files limited to 80 columns wide.  That way I can look at and review multiple documents simultaneously in splits and vertical split easily.

In my .vimrc I have the following setting to get the auto wrapping working for me:

set textwidth=80

That way as I type along, vim is keeping track of the file's column width and when I get to the 80th column it automatically moves me to the next line.  Pretty handy.

Here's my problem though, if I change some text that I've already entered and reword it, my paragraph loses it's nicely formatted set column width.  Here's an example but with the textwidth setting set at 40:

Before my edit change:

Lorem ipsum dolor sit amet, consectetur
adipiscing elit.  Proin neque sapien,
facilisis eget tincidunt ut, porttitor
laoreet lacus. Class aptent taciti
sociosqu ad litora torquent per conubia
nostra, per inceptos himenaeos.  Etiam
semper elementum congue.

After my edit change:

Lorem ipsum dolor sit amet, consectetur
adipiscing elit.  Proin neque sapien,
facilisis eget tincidunt ut, porttitor
laoreet lacus. Class aptent taciti
sociosqu ad litora torquent per conubia
nostra, per inceptos himenaeos.  I
forgot some text. Etiam
semper elementum congue.

Notice the problem:  After editing the paragraph,  the second to last line doesn't go to the 40th column before wrapping.  This is a little annoying to me because I feel the need to reformat the paragraph to get it back to looking like the "before".  It's not too big of a deal when I only have to reformat a line or two but if I've change something high up in a fairly long paragraph, reformatting dozens of lines can get tedious.

Here's a little tip that I stumbled across that can make that reformatting go a bit quicker:

1.  Select the whole paragraph with V. and then h,j,k and/or l.
2.  Then strip the new-line characters with J.
3.  Finally reformat it with gq.

Hope you find this helpful!