I have a long line of characters in vim. I'd like to insert a newline after 80 characters. How do I do that?
Asked
Active
Viewed 1.3k times
17
-
1This 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
-
I don't think that `gq` would quite do this; it would do more than what is asked. Specifically, it would rearrange text of lines shorter than 80 characters. – Raffi Khatchadourian Sep 08 '21 at 15:05
3 Answers
27
:%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
- 3,042
- 3
- 31
- 37
-
1One 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
-
Interesting, the "}" doesn't need to be escaped like the other answers (even though the "{" is escaped) ? – Tung Aug 16 '22 at 01:19
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
- 672
- 5
- 10
6
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
- 496
- 8
- 20
-
Slightly more readable using the `\v` modifier: `%s/\v(.{80}.{-}\s)/\1\r/g` - I needed something that broke on spaces only, good job :) – phatskat Apr 30 '22 at 21:53