vim中括号的自动补全

1576 查看

终于深刻地理解了括号自动补全[1]!vim的这一功能是需要手动配置的,在豆瓣上找到了一个比较完美的版本[2],赶紧偷了过来。因为懒,我还添加了引号的补全功能。有了这段代码,vim的括号补全就和Sublime Text 2一样一样的了(其实引号的匹配效果还是有些差距的)。

将以下代码粘贴到.vimrc文件中:

function! AutoPair(open, close)
        let line = getline('.')
        if col('.') > strlen(line) || line[col('.') - 1] == ' '
                return a:open.a:close."\<ESC>i"
        else
                return a:open
        endif
endf

function! ClosePair(char)
        if getline('.')[col('.') - 1] == a:char
                return "\<Right>"
        else
                return a:char
        endif
endf

function! SamePair(char)
        let line = getline('.')
        if col('.') > strlen(line) || line[col('.') - 1] == ' '
                return a:char.a:char."\<ESC>i"
        elseif line[col('.') - 1] == a:char
                return "\<Right>"
        else
                return a:char
        endif
endf

inoremap ( <c-r>=AutoPair('(', ')')<CR>
inoremap ) <c-r>=ClosePair(')')<CR>
inoremap { <c-r>=AutoPair('{', '}')<CR>
inoremap } <c-r>=ClosePair('}')<CR>
inoremap [ <c-r>=AutoPair('[', ']')<CR>
inoremap ] <c-r>=ClosePair(']')<CR>
inoremap " <c-r>=SamePair('"')<CR>
inoremap ' <c-r>=SamePair("'")<CR>
inoremap ` <c-r>=SamePair('`')<CR>

传送门

[1] 为什么编辑器会有“括号补全”这个功能?
[2] vim 括号补全小技巧