Skip to content

Instantly share code, notes, and snippets.

@jams2
Created May 9, 2019 16:15
Show Gist options
  • Save jams2/b3eadf8e3c338ee14f35866aacfab7f0 to your computer and use it in GitHub Desktop.
Save jams2/b3eadf8e3c338ee14f35866aacfab7f0 to your computer and use it in GitHub Desktop.
vimscript function for replacing pairs of parens
""""""""""""""""""""""""""""""""""""""""""
" Change matching pair of parens
nnoremap <leader>cp :call CycleParens()<CR>
function! CycleParens() abort
let parens = ['[', '{', '(', ']', '}', ')']
call CyclePairs(parens)
endfunction
function! CyclePairs(pairs) abort
let cycleLen = len(a:pairs)
let halfCycle = cycleLen / 2
let currentChar = strcharpart(getline('.')[col('.') - 1:], 0, 1)
let charIndex = index(a:pairs, currentChar)
if charIndex == -1 | return | endif
if charIndex + 1 == cycleLen || charIndex + 1 == halfCycle
let nextChar = charIndex + 1 - halfCycle
else
let nextChar = charIndex + 1
endif
execute 'normal! %r' . a:pairs[(nextChar + halfCycle) % cycleLen] .
\ '``r' . a:pairs[nextChar]
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment