Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly redistribute number of words/character per line in VIM

Tags:

text

vim

For text writing in vim, when I need to edit a line/add some new text, the number of words per line gets all out of whack.

Is there a way of quickly re-adjusting/line-wrapping to evenly disperse the number of words per line in VIM?

Example with 80 character auto-line-wrapping:

Before edit

This is something that I have writting with automatic line-wrapping before I 
have edited the file. I'll write some more just for demonstration purposes for
this whole line wrapping problem of mine.

After edit

This is something that I have writting with automatic line-wrapping after I
have edited the file. I'm demonstrating
this whole line wrapping problem of mine.

Manually fixing these is a bore, especially if I fix it and go on to edit things again.

My dream

It would be perfect if I could visually select a number of lines using shit+v, and then automatically distribute the number of words per line.

like image 676
ryanjdillon Avatar asked Jan 19 '26 15:01

ryanjdillon


2 Answers

You can set the textwidth option (or tw for short) for your desired width. Lets say 80.

:set tw=80

Now, use either the built-in formatter or your custom one, with the command gq. Check the help for gq, gw, and 'formatprg' to known more. This is used with a motion. So to reformat the current paragraph, do gqip. The whole text, gggqG (cursor to top (gg) then format until bottom). And all other sorts off motion.

Additionally, please explore the help for format options (:h 'fo' and :h fo-table). A particular interesting option for you is a. So if you do:

:set tw=80
:set fo+=a

Now you don't even need to reformat nothing. Vim will keep checking the width of the line as you type and reformatting your paragraph on the go by inserting or removing newlines.

I like the flexibility of external programs, and also recommend you checking them out. This answer's MarkDown for example was formatted with the UNIX program par. Check the original text.

like image 193
sidyll Avatar answered Jan 21 '26 07:01

sidyll


  • vip to select the current paragraph, then
  • gqto reformat the paragraph using textwidth.

or

  • gqip to combine an operator and a range (see :help text-objectsfor more details)

If you use it often, you can probably remap a new command that would execute the two previously mentioned commands.

See :help gqfor more details.

like image 39
Xavier T. Avatar answered Jan 21 '26 09:01

Xavier T.