Is possible to insert a line break where the cursor is in Vim without entering into insert mode? Here's an example ([x]
means cursor is on x
):
if (some_condition) {[ ]return; }
Occasionally, I might want to enter some more code. So I'd press i to get into insert mode, press Enter to insert the line break and then delete the extra space. Next, I'd enter normal mode and position the cursor before the closing brace and then do the same thing to get it on its own line.
I've been doing this a while, but there's surely a better way to do it?
Ctrl - V tells vi that the next character typed should be inserted literally and ctrl - m is the keystroke for a carriage return.
Command mode is used for cursor movement, editing, retrieving and saving files, etc. If you want to type in text, you need to be in Insert mode. To move from Command mode to Insert mode, press "i" (no quotes). To move from Insert mode to Command mode, press "ESC" (the Escape key).
Press the Return key to move the cursor to the beginning of the next line down.
Place the cursor where you want the line break. Use the keyboard shortcut – ALT + ENTER (hold the ALT key and then press Enter).
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:
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:
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.Enjoy!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With