13

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)?

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>
  • 3
    Using r<CR> is simply clever! Thanks! – Marcelo Apr 8 '17 at 13:33
  • 1
    that's great! super annoying going into insert to insert lines – Keith Nicholas Jul 13 '17 at 4:06
  • I found s<CR> keeps indentation whereas r<CR> does not. – toxefa Mar 1 at 11:41
5

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

  • 1
    That 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 Jun 24 '13 at 15:23
1

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

:map z i<CTRL+m>
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.

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.