Vim Tips Wiki
Register
Advertisement
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
gggqG

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:

hello
world

final

would be formatted to:

hello world

final

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 also[]

Comments[]

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)

Quick Question: Let's say I set the line width. How do I restore it to it's default? Thanks-- A

To see the default:
:set tw?
To reset to default :help :set:
:set tw&
JohnBeckett (talk) 09:12, 22 February 2021 (UTC)
Advertisement