How to break long lines in vim

text formattingvim

I have a quite big text file formed of blocks like

Short line.
Really long line.
Short line.

separated by empty lines, and I would like to use vim (on Linux) to break down the long lines and obtain blocks like

Short line.
This was
part of
a long line.
Short line.

My problem with gq (and gw) is that it reflows each block as an entire paragraph, i.e. it doesn't preserve the two line breaks within each block, and according to :help fo-table none of gq's format options would allow me to do what I want.
I also thought that I could achieve my goal if I could define new-line characters to be paragraph delimiters, but according to :help paragraph those are hard-coded.

Edit: I know that I could use gq or gw to format each long line one by one, but since my file runs over a few thousand lines I am looking for a way to achieve this automatically.

Best Answer

:%norm! gww

This applies the normal command gww (which formats the current line as with gw) on the entire buffer, without taking customized mappings into account (to avoid problems if e.g. gw has been mapped to something else).

See

  • :help :%
  • :help :norm
  • :help gww

This alternative is as per Ben's suggestion in the comments, and is more straightforward than the original solution, which is saved below since it might fit better in other similar circumstances due to the regular expression matching ability. In the "match all lines" case, it is unnecessarily brute, though.


Applying gww on every individual line in the buffer programmatically:

:g/^/norm gww

See :help :g and :help norm. ^ matches the beginning of a line, which in practice makes this match every line.

One can also opt to select only lines longer than e.g. 60 characters with

:g/\%>60v/norm gww

(see :help \%<) but in practice gww will only reformat lines longer than textwidth anyway, so it might not matter much in neither speed nor result.

(I am using v for "virtual column" instead of c for "column", since the latter really calculates a certain number of bytes into the line. This can lead to unexpected results when using multibyte encodings, which is often a reason to be wary. In practice it is not a real issue for the same reason as above, regarding that gww will not reformat lines shorter than textwidth anyway.)

Related Question