Automatically insert a matching brace in Vim

前端 未结 18 2333
醉梦人生
醉梦人生 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 06:07

    Finally I found out there is no need for plugin but rather this works perfect for me:

    inoremap { {}<Esc>ha
    inoremap ( ()<Esc>ha
    inoremap [ []<Esc>ha
    inoremap " ""<Esc>ha
    inoremap ' ''<Esc>ha
    inoremap ` ``<Esc>ha
    
    0 讨论(0)
  • 2020-12-13 06:09

    Using AutoClose with the following works correctly.

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

    This is true for my system at least (Unix terminal on Mac OS X).

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

    Put the following in your .vimrc file:

    inoremap { {}<ESC>ha
    

    Whenever you press { in insert mode, {} is generated and puts your cursor on the right brace, so that you can start typing between them straight away. By putting the curly braces in sequence rather than on different lines, you can put tabs in front of } manually. That way you never have the wrong amount of tabs in front of it.

    Perhaps someone can figure out how to count the amount of tabs the cursor is on, and then generate an equal amount of tabs in front of the } on a new line.

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

    delimitMate has a setting for this.

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

    My solution:

    inoremap <expr> <CR> InsertMapForEnter()
    function! InsertMapForEnter()
        if pumvisible()
            return "\<C-y>"
        elseif strcharpart(getline('.'),getpos('.')[2]-1,1) == '}'
            return "\<CR>\<Esc>O"
        elseif strcharpart(getline('.'),getpos('.')[2]-1,2) == '</'
            return "\<CR>\<Esc>O"
        else
            return "\<CR>"
        endif
    endfunction
    

    Explaination:

    The code above first check if you are using Enter to do confirm a code completion, if not it will indent the {|} when you type Enter. Also, it provides html tags auto indent.

    Examples:

    if( whatever ){|}
    

    press Enter and you will get

    if( whatever )
    {
      |  
    }
    

    This also works for html file. See the following example

    <html>|<html>
    

    press Enter and you will get

    <html>
        |
    </html>
    
    0 讨论(0)
  • 2020-12-13 06:14

    In VimL, you can map the { to do exactly as you wish:

    inoremap { {<CR>}<Esc>ko
    

    depending on your autoindent setup, you may want to add a <BS> after <CR>.

    For a more complete solution, I'd suggest you take a look at Luc Hermitte's vim plugins. They've never failed me so far.

    0 讨论(0)
提交回复
热议问题