Search code examples
vimindentationesc-key

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?


Solution

  • 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.