Search code examples
vimconfigindentationkey-bindings

Inserting a tab in Vim through a bind works only one time


I've made an Insert mode bind (opening curly bracket + Enter) which enters a tab (4 spaces) on the next line and a closing curly bracket after.

inoremap {<Enter> {<Enter><Enter>}<Up><Tab>

The example:

fn foo() {
    // Some code
}

It works fine, but when I try to use the bind again it won't insert tabs anymore, just a new line and a bracket.

fn bar() {
    if condition {
    loop {
    // Some more code
    }
    }
}

Solution

  • You don't need to insert that <Tab> yourself:

    inoremap {<CR> {<CR>}<C-o>O
    

    O will open a new line above the current line, with the right amount and type of indentation.