Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to close quote/bracket when I press tab in Vim

Tags:

vim

I've been playing with Vim plugins that auto-close quotes and brackets.

I don't think I'll continue using these plugins because they freak me out sometimes with their behaviours, but I thought it would be a nice plugin idea.

Basically the following. When you are inside a block (of quotes or brackets or whatever) pressing tab brings you to the outside, end of the block.

Here's an example, | is the cursor:

(let stuff (+ 1 2|)) ; yo!

; press tab:
(let stuff (+ 1 2)|) ; yo!

; press tab again:
(let stuff (+ 1 2))| ; yo!

Hope that gets the idea across. There probably already is a plugin or config for this somewhere but I would still be interested in seeing how to achieve this.

Quote from a comment of mine, below:

What I need is something that works in insert mode and ONLY if I'm inside one of these blocks, otherwise do something like inserting a real tab (because how often do you need to put a tab in a string?).

like image 334
greduan Avatar asked Dec 26 '22 12:12

greduan


2 Answers

This will work for one of your requirement but it won't insert tab if you are not inside a block.

imap <tab> <esc>])a

Use the ]) command to move to the end of parenthesis, it will take you to the closing parenthesis.

And you can map it to tab with

nnoremap <tab> ])
like image 95
Amit Verma Avatar answered Dec 28 '22 02:12

Amit Verma


This can indeed be implemented with an :inoremap <expr> <Tab> ..., which would have to return the (e.g. <Right>) keys to move the cursor beyond the closing bracket (an expression mapping is better than temporarily leaving insert mode, which would create a new undo point etc.)

To implement this, you can use search() with the n flag so it doesn't move, using a regular expression with \%# to assert parentheses around the cursor.

:inoremap <expr> <Tab> search('\%#[]>)}]', 'n') ? '<Right>' : '<Tab>'
like image 23
Ingo Karkat Avatar answered Dec 28 '22 01:12

Ingo Karkat