Search code examples
vimcurly-braces

vim, fast same line function brackets


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?


Solution

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