Automatically insert a matching brace in Vim

前端 未结 18 2331
醉梦人生
醉梦人生 2020-12-13 05:23

I spend way too much time fumbling around because Vim doesn\'t handle closing braces like most IDEs do. Here\'s what I want to happen:

Type this:

         


        
相关标签:
18条回答
  • 2020-12-13 05:54

    As you'll see in the wikia tip: there are many solutions to this recurrent question (I even have mine).

    That is if you limit yourself to bracket pairs. Here you are in the context of a control statement. You're thus more likely to find snippet systems that will not expect you to type the ") {" when typing an "if" statement. Vim shortcut tend to be shorter from what I read in your question. Here again there are a lot of choices, you'll find most likely snipmate, and may be my C&C++ suite.

    0 讨论(0)
  • 2020-12-13 05:57

    For anyone that runs across this like I did, and was looking for something more recently updated than AutoClose: delimitMate I have found to be, not only a preferable solution to AutoClose, behavior wise, but also in active development. According to vim.org, AutoClose has not been updated since 2009.

    0 讨论(0)
  • 2020-12-13 05:58

    I have tried different plugins but I found most accurate and most easy to use auto-pairs. It is really intuitive and when you install it you get what you've expected out of the box.

    0 讨论(0)
  • 2020-12-13 05:59

    I've always preferred something like what sublime text does where it appends the closing brace as the next character, so I added the following to my .vimrc:

    inoremap (  ()<ESC>hli
    

    which moves the cursor to between the two braces.

    0 讨论(0)
  • 2020-12-13 05:59

    You do not need a special plugin to do this - but it is a two-step process.

    First, add the following to your .vimrc to eat the triggering character:

    " eat characters after abbreviation
    function! Eatchar(pat)
        let c = nr2char(getchar(0))
        return (c =~ a:pat) ? '' : c
    endfunction
    

    and then add this abbreviation to your .vimrc:

    inoreabbr <silent> { {
          \<cr><space><space>
          \<cr><esc>0i}<esc>k$i<c-r>=Eatchar('\m\s\<bar>\r')<cr>
    

    The \ at the start of lines two and three is just a line continuation character. You could have done this all on one line, however and i added it so that i could spread the abbreviation out in a way that mirrors the output you're looking for -- just so things are a little more intuitive.

    0 讨论(0)
  • 2020-12-13 06:00

    A solution for braces, brackets and parenthesis with tab in between.

    " Automatically closing braces
    inoremap {<CR> {<CR>}<Esc>ko<tab>
    inoremap [<CR> [<CR>]<Esc>ko<tab>
    inoremap (<CR> (<CR>)<Esc>ko<tab>
    

    Result:

    function() {
      |
    }
    
    0 讨论(0)
提交回复
热议问题