Is there a command to split lines in Vim?

14

1

In Vim, the J key joins two lines together. Is there a similar, built-in, key combination to split lines with a newline (at the cursor position, or similar)?

Alternatively, what would be the most robust way to define a key combination to do that (in normal mode, not insert mode)?

Andrew Ferrier

Posted 2013-06-24T15:12:15.757

Reputation: 1 604

See also: http://stackoverflow.com/questions/624821/vim-split-line-command – dreftymac – 2017-01-07T15:36:23.907

Answers

15

No, there's no built-in command for that.

When I want to split on a <Space>, I do r<CR>.

--- EDIT ---

@keith-nicholas' comment reminded me about this question. FWIW I came up with an hopefully "universal" method in the mean time:

function! BreakHere()
    s/^\(\s*\)\(.\{-}\)\(\s*\)\(\%#\)\(\s*\)\(.*\)/\1\2\r\1\4\6
    call histdel("/", -1)
endfunction

nnoremap <key> :<C-u>call BreakHere()<CR>

romainl

Posted 2013-06-24T15:12:15.757

Reputation: 19 227

3Using r<CR> is simply clever! Thanks! – Marcelo – 2017-04-08T13:33:58.343

1that's great! super annoying going into insert to insert lines – Keith Nicholas – 2017-07-13T04:06:13.510

I found s<CR> keeps indentation whereas r<CR> does not. – toxefa – 2019-03-01T11:41:37.450

5

a Enter Esc to split to the right of the cursor, or i Enter Esc to split to the left.

Scott

Posted 2013-06-24T15:12:15.757

Reputation: 17 653

1That is it. Just insert a single newline. Alternatively: use r+<return> to replace the character under the cursor with a newline. Would be nice to have a single letter command for it, but as far as I know there isn't one. – Tonny – 2013-06-24T15:23:32.057

1

The easiest way I've found to split lines in Vim is the normal mode command gq (type both letters in quick succession in normal or visual mode):

  • In visual mode, it will split whatever is selected.
  • In normal mode, you follow gq with a motion.

For example, gql will split one line to the currently set width. To set the width of the split lines to be different from your current setting, you can use

:set textwidth=<n>

Where n=number of characters you want in a line, e.g., 10, and change back to your normal width when you're done.

Got this information from a Youtube video by Kholidfu that shows how to join and split lines in normal mode using a motion: Vim Tutorial - Join and Split Lines.

vdicarlo

Posted 2013-06-24T15:12:15.757

Reputation: 11

1

You could define your own using map. To define z as the command for example:

:map z i<CTRL+m>

suspectus

Posted 2013-06-24T15:12:15.757

Reputation: 3 957

0

You can record a macro:

in normal mode type "q+" to start the record. press "i", the macro you want to record. then press "q" again to stop recording.

to use the macro go to normal mode and type "@+letter".

in my case I used the "b" to use this macro: to record type in normal mode "qbiq" to use type in normal mode "@b"

luizhj

Posted 2013-06-24T15:12:15.757

Reputation: 1