13

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

Raffi Khatchadourian
  • 2,795
  • 2
  • 25
  • 33
  • 1
    This is arguably a duplicated of https://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns which shows that `set textwidth=80` and `gqq` would do it. – Griffith Rees Apr 29 '18 at 10:20
  • Possible duplicate of [vim command to restructure/force text to 80 columns](https://stackoverflow.com/questions/3033423/vim-command-to-restructure-force-text-to-80-columns) – D. Ben Knoble Aug 27 '19 at 18:36

3 Answers3

23
:%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
Raffi Khatchadourian
  • 2,795
  • 2
  • 25
  • 33
  • 1
    One caveat: if your goal is to wrap lines that are too long, the above command will add the new line character even if the line is exactly 80 character. To avoid this behavior, you need to exclude this case: `:%s/.\{80}\($\)\@!/&\r/g` – xzhu Sep 28 '15 at 21:19
  • I would be interested in only inserting a line break at the first space occurring after the 80th character. – Tjaart Aug 27 '19 at 13:53
6

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
dvk317960
  • 624
  • 4
  • 10
3

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
Tjaart
  • 396
  • 6
  • 19