khatchad
khatchad

Reputation: 3178

How do you insert a newline after every 80 characters in vim?

I have a long line of characters in vim. I'd like to insert a newline after 80 characters. How do I do that?

Upvotes: 18

Views: 15242

Answers (3)

Tjaart
Tjaart

Reputation: 496

You can also modify this approved answer to only insert the newline at the first space occurring after the 80th character:

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

Upvotes: 6

dvk317960
dvk317960

Reputation: 792

Using regular expression:

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

Using recursive Vim macro:

qqqqq79la<Enter><esc>@qq@q


qqq  Clear contents in register q.
qq   start marco in register q
79la<Enter> Carriage return after 80 characters.
<esc> go back to normal mode
 @q   run macro q which we are about to create now.
 q   complete recording macro
 @q run macro

Upvotes: 6

khatchad
khatchad

Reputation: 3178

:%s/.\{80}/&\r/g
  • %: process the entire file
  • s: substitute
  • .: matches any character
  • {80}: matches every 80 occurrences of previous character (in this case, any character)
  • &: the match result
  • \r: newline character
  • g: perform the replacement globally

Upvotes: 29

Related Questions