How do I insert a linebreak where the cursor is without entering into insert mode in Vim?

For the example you've given, you could use rEnter to replace a single character (the space) with Enter. Then, fspace. to move forward to the next space and repeat the last command.

Depending on your autoindent settings, the above may or may not indent the return statement properly. If not, then use sEnterTabEsc instead to replace the space with a newline, indent the line, and exit insert mode. You would have to replace the second space with a different command so you couldn't use '.' in this case.


Here's how to create a macro that inserts a newline at the cursor whenever you press 'g' while not in insert mode:

From within vim, type:

:map g i[Ctrl+V][Enter][Ctrl+V][Esc][Enter]

Where:

  • [Ctrl+V] means hold the Ctrl key and press 'v'
  • [Enter] means press the Enter key
  • [Esc] means press the Esc key

You'll see the following at the bottom of your vim window until you press the final Enter:

:map g i^M^[

Explanation:

[Ctrl+V] means "quote the following character" -- it allows you to embed the newline and escape characters in the command.

So you're mapping the 'g' key to the sequence:

i [Enter] [Escape]

This is vim for insert a newline before the cursor, then exit insert mode.

Tweaks:

  • You can replace the 'g' with any character that's not already linked to a command you use.
  • Add more to the command, e.g. f}i^M^[O -- This will find the } and insert another newline, then escape from insert mode and Open an empty line for you to enter more code.
  • You can add the command to your .vimrc or .exrc file to make it permanent. Just omit the colon from the beginning, so the command starts with "map"

Enjoy!


A simple mapping to break the line at the cursor by pressing Ctrl+Enter:

:nmap <c-cr> i<cr><Esc>

essentially enters 'insert' mode, inserts a line break and goes back to normal mode.

put it in your .vimrc file for future use.