Skip to content

Instantly share code, notes, and snippets.

@chemzqm
Last active May 9, 2019 16:28
Show Gist options
  • Save chemzqm/79c542efef8ddf98a732 to your computer and use it in GitHub Desktop.
Save chemzqm/79c542efef8ddf98a732 to your computer and use it in GitHub Desktop.
Fixed simple_pairs
" ============================================================================
" Description: Insert pair charactor automaticly
" Author: Qiming Zhao <[email protected]>
" Licence: Vim licence
" Version: 0.1
" Last Modified: Sep 13, 2016
" ============================================================================
if exists('did_simple_pairs_loaded') | finish | endif
let did_simple_pairs_loaded = 1
let s:pairs = {'(': ')', '[': ']', '{': '}', '"': '"', "'": "'", '`' : '`'}
function! s:getNextChar()
let pos = getcurpos()
let lnum = pos[1]
let cnum = pos[2]
let line = getline('.')
if cnum == len(line) + 1 | return -1 | endif
return line[cnum - 1]
endfunction
function! s:getPrevChar()
let pos = getcurpos()
let lnum = pos[1]
let cnum = pos[2]
echo cnum
if cnum < 2 | return -1 | endif
return getline('.')[cnum - 2]
endfunction
function! s:InsertPair(c)
let matchingPair = s:pairs[a:c]
let nextChar = s:getNextChar()
let prevChar = s:getPrevChar()
let isQuote = index(['"', "'", '`'], a:c) != -1
if isQuote && prevChar == a:c && nextChar == -1
return a:c
endif
if nextChar == -1
let insertPair = 1
else
if isQuote && nextChar == a:c
return "\<Right>"
else
if isQuote
let insertPair = (nextChar != matchingPair)
else
let insertPair = 1
endif
endif
endif
if insertPair
let result = a:c . matchingPair . "\<Left>"
else
let result = a:c
endif
return result
endfunction
function! s:ClosePair(c)
let nextChar = s:getNextChar()
if nextChar ==# a:c
return "\<Right>"
else
return a:c
endif
endfunction
for key in keys(s:pairs)
execute 'inoremap <silent> '.key.' <C-R>=<SID>InsertPair("'.escape(key, '"').'")<CR>'
endfor
for key in [']', ')', '}']
execute 'inoremap <silent> '.key.' <C-R>=<SID>ClosePair("'.key.'")<CR>'
endfor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment