Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Pre-Exit (Esc Key) Command?

Right now in Vim when I go to a new line (or press 'p' or 'o' in normal mode) I get a lovely automatic indent, that also disappears if I exit insert mode without adding anything to it.

Is there a way to bind something to before I exit insert mode, such as inserting a phantom character then removing it?

like image 419
Jookia Avatar asked Sep 27 '11 15:09

Jookia


People also ask

How do I use ESC in vim?

If you have an American English keyboard, pressing Ctrl-[ (control plus left square bracket) is equivalent to pressing Esc.

How do I escape without vim key?

Sometimes you need to escape, and you can't use the esc key. Whether its missing, on a touch bar, or you simply don't want to stretch your fingers away from home row, it's nice to have another option. In Vim, Ctrl+[ sends an escape character, equivalent to pressing the escape key.

How do I exit insert mode?

Pressing ESC quits from insert mode to normal mode, where you can press : to type in a command.

How do I enter insert mode in Vim?

To go into INSERT mode from COMMAND mode, you type i . To go back to COMMAND mode, you type the esc key. vim starts out in COMMAND mode. Over time, you will likely spend more time in COMMAND mode than INSERT mode.


2 Answers

Argh, I just read about this exact thing like two days ago but I can't remember where.

Anyway, the trick is to input a character right after <CR> and delete it immediately. There are a bunch of ways to do it:

<CR>a<Esc>x
<CR>a<C-w>
<CR>a<BS>

--EDIT--

Vim being Vim there are probably many other ways.

To automate these, you need to add a mapping to your .vimrc:

inoremap <CR> <CR>a<BS> " insert mode mapping for <CR>
nnoremap o oa<BS>       " normal mode mapping for o

But I'm not sure you should overwrite defaults like that.

--EDIT--

However, what is annoying with Vim's default behaviour is that you may need to do some <Tab><Tab><Tab><Tab> before actually inputing some text on non-indented line or do == when you are done or rely on the automatic indentation rules for your language at the next <CR>.

All that can be skipped by using <S-S> which puts you in INSERT mode right at the correct indentation level.

like image 128
romainl Avatar answered Sep 27 '22 18:09

romainl


Try either cc or S in normal mode to change a line with respect to indention. No need for phantom characters.

:h cc
:h S
like image 26
Peter Rincker Avatar answered Sep 27 '22 18:09

Peter Rincker