Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new line after current line in insert mode vim

Tags:

vim

vi

I am new at Vim, and the transition from Sublime to Vim is being really hard. I want to know if there's a shortcut to add a new line above or behind the current line while I'm in insert mode without leaving it. In sublime I used

cmd + Enter

cmd + Shift + Enter

to do but I didn't find a similar way to do it on vim.

I found the way to do it in normal mode using 'o' and 'O' and also configuring this amazing way http://vim.wikia.com/wiki/Insert_newline_without_entering_insert_mode but none of them reach what I need.

Thanks !

like image 716
Guillermo kuster Avatar asked Jan 28 '16 12:01

Guillermo kuster


People also ask

How do I insert a line break in Vim?

Using search and replace In the substitute command, the find pattern is empty, so the last search is used; in the replacement, \r inserts a newline and & inserts the search hit (see search and replace). Use :%s//\r&/g if you want to replace all occurrences in all lines.

How do we make a new line under the current line?

If you want a new line at the top of the current line then press CTRL + SHIFT + ENTER. If you want a new line at the bottom of the current line then press CTRL+ ENTER.

How do I insert a blank line in Vi?

To insert a blank line below the current line use :put , or :put! to insert one above. To specify where to insert the blank line (nth line) use :[n]put .


1 Answers

Defining a shortcut for adding line below is easy, just type the following on the Vim command-line (after typing : in normal mode) or add it to your vimrc file:

imap <C-Enter> <Esc>o

That adds an insert-mode mapping (imap) so that Ctrl-Enter will leave insert mode, then use o to add a new line after the current line (leaving you back in insert mode where you started). (<C-xxx> is how Vim represents the special key sequence Ctrl+xxx, and <Esc> is the Escape key).

That's very similar to the "amazing way" you link to, but just using the appropriate key sequence to go from insert mode to normal mode and then add the line. The way to create shortcuts in Vim is to build them up from smaller pieces. If you know about O and o then all you need to do is create a mapping to get into normal mode first then use them.

From that, it should be obvious how to do the other mapping too:

imap <C-S-Enter> <Esc>O

(<C-S-xxx> means Ctrl+Shift+xxx)

Those mappings work fine for me in gvim GUI but may not work in the terminal-based vim, as the key sequences might not get passed correctly from the terminal to vim. Use some other mappings such as Ctrl+o if necessary.

like image 170
Jonathan Wakely Avatar answered Oct 10 '22 02:10

Jonathan Wakely