In VIM, how do I break one really long line into m

2020-05-10 18:58发布

Say I have a super long line in the VIM editor (say around 300+ characters). How would I break that up into multiple lines so that the word boundaries roughly break at 80 characters?

Example:

This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line This is a really long line

to

This is a really long line 
This is a really long line
This is a really long line
This is a really long line
This is a really long line
This is a ...

标签: vim
9条回答
看我几分像从前
2楼-- · 2020-05-10 19:17

As a quick and nasty, maybe try the following map:

map q 080lwbels<CR><ESC>

which says:

  • start a 0th position of line,
  • move to 80th char to the right,
  • go to beginning of next word,
  • go back to previous word,
  • go to end of current word,
  • go one char right, and
  • substitute a CR for that char.

Then hitting q and CR will break the line up into chunks on the word boundary.

查看更多
爷、活的狠高调
3楼-- · 2020-05-10 19:20

To split long lines in the complete document without removing already present line breaks, use:

:set formatoptions+=w
:set tw=80
gggqG
查看更多
Melony?
4楼-- · 2020-05-10 19:21

Vim does this very easy (break lines at word boundaries).

gq{motion} % format the line that {motion} moves over
{Visual}gq % format the visually selected area
gqq        % format the current line
...

I'd suggest you check out :help gq and :help gw.

Also setting textwidth (tw) will give you auto line break when exceeded during typing. It is used in gq too, though if disabled gq breaks on window size or 79 depending on which comes first.

:set tw=80

By setting format options to include text width vim will automatically break at the tw setting.

:set fo+=t
查看更多
不美不萌又怎样
5楼-- · 2020-05-10 19:21

I needed to reformat an entire file rather than one line. As Wernsey points out, I could have used 'fmt', but the following sequence in vim did the trick also (borrowing from the various answers here):

<ESC>
:setl tw=80 fo=t
1GVGgq
查看更多
来,给爷笑一个
6楼-- · 2020-05-10 19:35

I manually inserted '\' (and then CR / tab to format) in each LONGLINE after the last whitespace but before the 80 column. That is to say:

1 this is a long, long, line

now looks like

1 this is a long, \
        long line

and compiles normally.

查看更多
家丑人穷心不美
7楼-- · 2020-05-10 19:37

For solid lines of text highlight the area using v in normal mode, then press

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

This will add a newline at the end of every 80th character.

:s/       replaces within the current select
\v        uses regular expressions
(.{80})   selects 80 characters & placed them into group one
\1\r      replaces group one with group one and a newline
查看更多
登录 后发表回答