Tip 1131 Printable Monobook Previous Next

created 2006 · complexity basic · version 6.0

In Vim, you may want to format long lines, that is, wrap long lines so the longest is, say, 80 characters.

The standard approach is to set the local 'textwidth' option, then use gq to format the wanted lines.

:setl tw=80

In the above, gggqG is gg (go to the first line) then gq (format) to G (the last line).

That works, but it also joins consecutive short lines together although it does not join lines that are separated with an empty line. For example, this text:



would be formatted to:

hello world


To wrap long lines without affecting short lines, use:

:g/./ normal gqq

The g command executes normal gqq on each line matching . (any line with at least one character). The normal-mode gqq command then formats that line.

An alternative would be to use the par text reformatter. The following replaces each line that is 80 or more characters with the result of running par. If the buffer contains 1000 long lines, this will call par 1000 times.

:g/.\{80,\}/ .!par w70

This need arises when you copy/paste a programming snippet into Vim, and you want to leave the indented code alone, but format the long explanation.

See alsoEdit


How is this better than gq with a line width of 80?

This IS better than gq with a line width of 80 because it prevents short lines without empty line between them from being concatenated! --February 3, 2016
See :help 'formatprg'. You could probably get the best of both worlds. --Fritzophrenic (talk)

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.