vim, fast same line function brackets

72 Views Asked by At

Is there a quick way to open curly brackets for a function and end in insert mode indented on the next line. So for example:

void myFunc(int arg) {
    <cursor>
}

Specifically, I’m asking for a motion to execute after writing the arguments inside ().

Right now the only way I can think is the direct way, insert both open and closed curly brackets, move the second one down two lines, move up one and then tab. {}<esc>i<enter><enter><esc>ki<tab>

This seems really redundant. I guess I can also wait to write the second curly after creating the new lines and save a mode switch. But is there a smarter vim-er way to do this?

2

There are 2 best solutions below

2
romainl On BEST ANSWER

You have two options:

  1. Create a custom mapping

    If the manual way is to do:

    {}<Esc>i<CR><CR>
    

    then you can map it to something shorter:

    inoremap {<CR> {}<Esc>i<CR><CR>
    

    and also do it for other brackets:

    inoremap {<CR> {}<Esc>i<CR><CR>
    inoremap (<CR> ()<Esc>i<CR><CR>
    " etc.
    

    That approach is very common. Here is a variant I've had in my vimrc for many years:

    inoremap (; (<CR>);<C-c>O
    " etc.
    
  2. Use a third-party plugin

    Just google for "vim auto close brackets".

1
Luc Hermitte On

Use <cr><c-c>O instead of the double <cr><cr><up>: this will ensure the cursor will be correctly indented at the end.

<cr><cr><up><c-f> would have worked as long as CTRL-F is present in 'indentkeys'. As such, <c-c>O is more robust.

Note: I would recommend using a bracketing plugin though as these mappings without mappings that helps jumping out of bracket-pairs can be really cumbersome to use. Also these plugins already know how to support redo/., and many other things.