Skip to content

Instantly share code, notes, and snippets.

@hotoo
Created June 23, 2010 04:45
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save hotoo/449512 to your computer and use it in GitHub Desktop.
Save hotoo/449512 to your computer and use it in GitHub Desktop.
inoremap ( <c-r>=OpenPair('(')<CR>
inoremap ) <c-r>=ClosePair(')')<CR>
inoremap { <c-r>=OpenPair('{')<CR>
inoremap } <c-r>=ClosePair('}')<CR>
inoremap [ <c-r>=OpenPair('[')<CR>
inoremap ] <c-r>=ClosePair(']')<CR>
" just for xml document, but need not for now.
"inoremap < <c-r>=OpenPair('<')<CR>
"inoremap > <c-r>=ClosePair('>')<CR>
function! OpenPair(char)
let PAIRs = {
\ '{' : '}',
\ '[' : ']',
\ '(' : ')',
\ '<' : '>'
\}
if line('$')>2000
let line = getline('.')
let txt = strpart(line, col('.')-1)
else
let lines = getline(1,line('$'))
let line=""
for str in lines
let line = line . str . "\n"
endfor
let blines = getline(line('.')-1, line("$"))
let txt = strpart(getline("."), col('.')-1)
for str in blines
let txt = txt . str . "\n"
endfor
endif
let oL = len(split(line, a:char, 1))-1
let cL = len(split(line, PAIRs[a:char], 1))-1
let ol = len(split(txt, a:char, 1))-1
let cl = len(split(txt, PAIRs[a:char], 1))-1
if oL>=cL || (oL<cL && ol>=cl)
return a:char . PAIRs[a:char] . "\<Left>"
else
return a:char
endif
endfunction
function! ClosePair(char)
if getline('.')[col('.')-1] == a:char
return "\<Right>"
else
return a:char
endif
endf
inoremap ' <c-r>=CompleteQuote("'")<CR>
inoremap " <c-r>=CompleteQuote('"')<CR>
function! CompleteQuote(quote)
let ql = len(split(getline('.'), a:quote, 1))-1
let slen = len(split(strpart(getline("."), 0, col(".")-1), a:quote, 1))-1
let elen = len(split(strpart(getline("."), col(".")-1), a:quote, 1))-1
let isBefreQuote = getline('.')[col('.') - 1] == a:quote
if '"'==a:quote && "vim"==&ft && 0==match(strpart(getline('.'), 0, col('.')-1), "^[\t ]*$")
" for vim comment.
return a:quote
elseif "'"==a:quote && 0==match(getline('.')[col('.')-2], "[a-zA-Z0-9]")
" for Name's Blog.
return a:quote
elseif (ql%2)==1
" a:quote length is odd.
return a:quote
elseif ((slen%2)==1 && (elen%2)==1 && !isBefreQuote) || ((slen%2)==0 && (elen%2)==0)
return a:quote . a:quote . "\<Left>"
elseif isBefreQuote
return "\<Right>"
else
return a:quote . a:quote . "\<Left>"
endif
endfunction
@hotoo
Copy link
Author

hotoo commented Sep 16, 2010

2000 行之内的文档,使用全文括号智能匹配;
大于 2000 行的文档,使用行内括号智能匹配。
这个值请自行根据计算机硬件性能调整。

http://hotoo.github.com/blog/vim-autocomplete-pairs.html

@JoneWang
Copy link

JoneWang commented Apr 7, 2013

"123456"

光标在6后面的时候再次插入",会新插入",变成了"123456"",感觉 在此情况下应该还是"123456"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment