Skip to content

Instantly share code, notes, and snippets.

@pedro-hs
Last active June 6, 2021 03:51
Show Gist options
  • Save pedro-hs/a4a0c4d1c8b3b5e2f3cd8e6a9389a053 to your computer and use it in GitHub Desktop.
Save pedro-hs/a4a0c4d1c8b3b5e2f3cd8e6a9389a053 to your computer and use it in GitHub Desktop.
auto close pair brackets in vim/neovim
" Auto close
inoremap { {}<left>
inoremap ( ()<left>
inoremap [ []<left>
inoremap " ""<left>
inoremap ' ''<left>
inoremap ` ``<left>
inoremap < <><left>
" Auto close with enter
inoremap (<cr> (<cr>)<esc>O
inoremap {<cr> {<cr>}<esc>O
inoremap [<cr> [<cr>]<esc>O
" Auto close space
inoremap {<space> {<space><space>}<left><left>
inoremap (<space> (<space><space>)<left><left>
inoremap [<space> [<space><space>]<left><left>
inoremap "<space> "<space><space>"<left><left>
inoremap '<space> '<space><space>'<left><left>
inoremap `<space> `<space><space>`<left><left>
inoremap <<space> <<space><space>><left><left>
" Do nothing when closing pair
inoremap <expr> } strpart(getline('.'), col('.')-1, 1) == '}' ? '<right>' : '}'
inoremap <expr> ) strpart(getline('.'), col('.')-1, 1) == ')' ? '<right>' : ')'
inoremap <expr> ] strpart(getline('.'), col('.')-1, 1) == ']' ? '<right>' : ']'
inoremap <expr> > strpart(getline('.'), col('.')-1, 1) == '>' ? '<right>' : '>'
inoremap <expr> ' strpart(getline('.'), col('.')-1, 1) == "'" ? "\<right>" : "''\<Left>"
inoremap <expr> ` strpart(getline('.'), col('.')-1, 1) == "`" ? "\<right>" : "``\<Left>"
inoremap <expr> " strpart(getline('.'), col('.')-1, 1) == '"' ? "\<right>" : '""<Left>'
" Delete full pair when is empty
function! s:get_char(num) abort
if a:num == 0
return matchstr(getline('.'), '.\%' . col('.') . 'c')
else
return matchstr(getline('.'), '\%' . col('.') . 'c.')
endif
endfunction
function! s:is_surrounded(match_list)
return index(a:match_list, s:get_char(0) . s:get_char(1)) >= 0
endfunction
ino <expr> <BS>
\ <SID>is_surrounded(["()", "[]", "{}", "''", '""']) ?
\ "\<C-g>U<Right>\<BS>\<BS>" : "\<BS>"
" end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment