I'd like to write a function in vimscript that finds the last open parenthese or bracket in a line. This isn't necessarily an easy problem, because it needs to be able to handle all of the following:
function(abc
function(abc, [def
function(abc, [def], "string("
function(abc, [def], "string(", ghi(
As you can see, nested parenthesis, differing symbols, and string tokens all need to be handled intelligently. Is this even possible? Are there tools with vimscript regexes to do context-aware searches that know the difference between unclosed parentheses and parenthesis in strings?
Given that you can syntax highlight unbalanced brackets, it should be possible to find the last unclosed parenthese/bracket on a line. How can this be done?
A simpler solution is to use Vim's navigation. 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.
place the cursor on the opening parenthesis ( or braces { press esc key and press v to enter into the visual mode. now press the % symbol (this will select the whole text between parens inclusive) press the key y to yank (i.e. copy) the text (press d if you rather want to cut it.)
So, basicly, you have to find the last parenthese which is not in comment and not in string.
I am not sure what this syntax is so I placed those lines in a buffer and did
:set ft=javascript
to get strings highlighting
function(abc
function(abc, [def
function(abc, [def], "string("
function(abc, [def], "string(", ghi(
Now put your cursor to the 3rd line open parenthese and issue the following command:
:echo synIDattr(synID(line('.'), col('.'), 0), 'name') =~? '\(Comment\|String\)'
It'll echo you '1' and it means that character under the cursor is in comment or in a string.
If you place the cursor to the last col of the last line and do the same command you'll get '0'.
Now you can iterate backwards over parenthesis and test them against 'comment' and 'string' and get the last open parenthese.
You can check this archive of "LISP: Balance unmatched parentheses in Vim" to see how to close unmatched parenthesis using vimscript.
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