Automatically insert a matching brace in Vim

前端 未结 18 2604
醉梦人生
醉梦人生 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:15

    Here is what I have in my vimrc:

    let s:pairs={
                \'<': '>',
                \'{': '}',
                \'[': ']',
                \'(': ')',
                \'«': '»',
                \'„': '“',
                \'“': '”',
                \'‘': '’',
            \}
    call map(copy(s:pairs), 'extend(s:pairs, {v:val : v:key}, "keep")')
    function! InsertPair(left, ...)
        let rlist=reverse(map(split(a:left, '\zs'), 'get(s:pairs, v:val, v:val)'))
        let opts=get(a:000, 0, {})
        let start   = get(opts, 'start',   '')
        let lmiddle = get(opts, 'lmiddle', '')
        let rmiddle = get(opts, 'rmiddle', '')
        let end     = get(opts, 'end',     '')
        let prefix  = get(opts, 'prefix',  '')
        let start.=prefix
        let rmiddle.=prefix
        let left=start.a:left.lmiddle
        let right=rmiddle.join(rlist, '').end
        let moves=repeat("\", len(split(right, '\zs')))
        return left.right.moves
    endfunction
     noremap!  ,f   InsertPair('{')
     noremap!  ,h   InsertPair('[')
     noremap!  ,s   InsertPair('(')
     noremap!  ,u   InsertPair('<')
    

    And, for some filetypes:

    inoremap { {o}O
    

    // I know that InsertPair function is trivial, but it saves time because with it I can define both command and normal mode mappings with one command without having to write lots of s.

提交回复
热议问题