Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim magic closing bracket

Tags:

vim

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?

like image 849
luqui Avatar asked May 21 '11 07:05

luqui


People also ask

How do I automatically close brackets in vim?

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.

How do I match parentheses in Vim?

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.


1 Answers

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.

like image 141
mike3996 Avatar answered Sep 29 '22 10:09

mike3996