It would be great in vim if I could type ]
(or some other character, maybe <C-]>
) and have it automatically insert whichever bracket properly closes the opening bracket. Eg. if I have this in my buffer:
object(function(x) { x+[1,2,3
And I press ]]]
, the characters ]})
would be inserted. How might one accomplish this this?
This autocomplete in insert mode, provided set paste is not set. Keep it in the vimrc to avoid typing it every time and when we don't want the mapping, we need to escape it using ctrl + v before typing the mapped char like ( { etc.
You can easily use the % key to jump to a matching opening or closing parenthesis, bracket or curly brace. You can also set the option showmatch . The cursor will briefly jump to the matching bracket, wen you insert one.
Here's a sketch of what you probably wanted. The builtin functions searchpair
and searchpairpos
are of enormous help for various text editing tasks :)
" Return a corresponding paren to be sent to the buffer
function! CloseParen()
let parenpairs = {'(' : ')',
\ '[' : ']',
\ '{' : '}'}
let [m_lnum, m_col] = searchpairpos('[[({]', '', '[\])}]', 'nbW')
if (m_lnum != 0) && (m_col != 0)
let c = getline(m_lnum)[m_col - 1]
return parenpairs[c]
endif
return ''
endfun
To use it comfortably, make an imap
of it:
imap <C-e> <C-r>=CloseParen()<CR>
Edit: over-escaped the search regexp so \
got included in the search. One less problem now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With