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

vim
10,612

Solution 1

:%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

Solution 2

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

Solution 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
Share:
10,612

Related videos on Youtube

Raffi Khatchadourian
Author by

Raffi Khatchadourian

Assistant Professor at the Department of Computer Science, Hunter College, City University of New York.

Updated on September 16, 2022

Comments

  • Raffi Khatchadourian
    Raffi Khatchadourian over 1 year

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