How can I wrap text to some length in Vim?

Let's speak of relative measures. My Vim looks like:

aaaaaaaaaaaaa 
bbbbbbbbbbbbb 
ccccccccccccc 
etc

I would like it to be smaller:

aaaaa
aaaaa
bbbbb
bbbbb
ccccc
ccccc
etc

How can I get it? And how can I manage setting the length of such a block?

Upvotes: 118

Views: 72874

Answers (6)

cjadeveloper
cjadeveloper

Reputation: 763

First, set textwidth to 5 with

:set tw=5

Then, press gqap to format a paragraph

Upvotes: 1

sleske
sleske

Reputation: 83577

You can actually do two things:

  1. Let vim format (i.e.change) your text to have shorter lines, by inserting linebreaks
  2. Leave lines as they are, but display them wrapped

Which do you want?

Option 1 would be achieved by setting textwidth (for example :set textwidth=30 (from Swaarop's answer)). Then you can reformat your text by highlighting it (in visual mode) and typing gq. (textwidth can be abbreviated as tw, thus :set tw=30.)

Option 2 can be toggled by running :set wrap / :set nowrap. This will wrap lines which are too long for the window.

Both are independent.

Upvotes: 213

Vlad Dogaru
Vlad Dogaru

Reputation: 1196

Once you set 'textwidth', you can select text with visual mode and press gq to wrap it nicely (you can also use Q on some older/legacy configurations).

A few useful tips:

gqq (wrap the current line)
gq} (wrap this 'paragraph', i.e. until the next blank line)
:h gq

Upvotes: 73

kthy
kthy

Reputation: 896

If you have text without spaces that you want to break at a certain length, it is neither necessary to use external fold nor write your own formatexpr.

:%s/\(.\{80\}\)/\1\r/g

will break all lines at 80 chars.

Upvotes: 8

Swaroop C H
Swaroop C H

Reputation: 17024

:set textwidth=30

Upvotes: 14

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17188

Using fold(1) is one possibility:

:%!fold -w5 

Result:

aaaaa
aaaaa
aaa 
bbbbb
bbbbb
bbb 
ccccc
ccccc
ccc

Upvotes: 25

Related Questions