Thursday, January 3, 2008

rewrapping paragraphs in vim

taken from here:

If you ever edited text and still wanted to make your lines break at about 70 characters, you know it's sometimes needed to "rewrap" the lines to make them fill those 70 characters again.

VIM has the ideal solution for this. Select a block of text and press gq. Instant rewrap! This even "understands" basic things like dashed lists, indentation of a block of text, and even Usenet quotation marks like '>'.

To rewrap the current paragraph, press gq}. Since this is a bit tiresome, I remapped this to Ctrl-q in my ~/.vimrc:
map <C-q> {gq}

8 comments:

Franco said...

You might want to reconsider mapping to q. q is very useful in vim: it allows you to record a sequence of characters that you can "play back".

For example, 'qaYp[Ctrl-a]q' will record into register "a" the command: (Y)ank the entire line; (p)aste it (below the current line); increment the first integer on that line (Ctrl-A).

This is useful for creating a numbered list. If you type 1 on a line, then hit 19@q, you will get 19 new lines, numbered from 1 through 20.

leo said...

Franco, you're absolutely right! Mapping to [q] really wasn't a great idea. Thank you very much for the hint!

Now I'm using [Ctrl-q], apparently this doesn't disable any important vim function (originally it goes into Visual-Block mode, but that's also available using [Ctrl-v]). I've updated the post to reflect this.

Anonymous said...

Thanks for your post, it helped me find it in help. I've also learned there that you can use gwap instead of {gq} to rewrap current paragraph. This will also return to the position you were before this action.

Read more with :help gw.

leo said...

Cool, thanks!

Anonymous said...

Thank ou.

Brandon McCaig said...

Thanks! :) I've been struggling with manually reformatting paragraphs for a while and finally thought, "Vim can do this for me, I know it!" Thanks for showing me how. ;)

Anonymous said...

Ctrl-q didn't work for me in Ubuntu, probably because this is normally used to quit the application running.

Instead, I got it working with Ctrl-r, which makes more sense if "r" is for "rewrap"! :)

Anonymous said...

Actually, scratch that. I'm now using <F8> as Ctrl-r is "redo".