你必须要么使用searchpair(),要么使用%(只要安装matchit,并且你在开始/结束时),然后标记这两个位置,测试它是文本还是括号,最后更新两条线.
nnoremap <buffer> <c-x>{ :call <sid>ToggleBeginOrBracket()<cr>
let s:k_be = [ 'begin', 'end' ]
function! s:ToggleBeginOrBracket()
let c = lh#position#char_at_mark('.')
if c =~ '[{}]'
" don't use matchit for {,}
exe 'normal! %s'.s:k_be[1-(c=='}')]."\<esc>``s".s:k_be[(c=='}')]."\<esc>"
else
let w = expand('<cword>')
if w == 'begin'
" use mathit
normal %
exe "normal! ciw}\<esc>``ciw{\<esc>"
elseif w == 'end'
" use mathit
normal %
exe "normal! ciw{\<esc>``ciw}\<esc>"
else
throw 'Cannot toggle block: cursor is not on {, }, begin, nor end'
endif
endif
endfunction
Run Code Online (Sandbox Code Playgroud)
这里lh#position#char_at_mark()定义的地方.
PS:这绝对是一个SO问题,因为它结合了ruby上下文和高级vim脚本.