开发者

Vimscript: find last open parenthese or bracket

开发者 https://www.devze.com 2023-01-19 02:33 出处:网络
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

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 highl开发者_如何学Cight unbalanced brackets, it should be possible to find the last unclosed parenthese/bracket on a line. How can this be done?


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.


Use [( and ]):

[(          go to [count] previous unmatched '('.
])          go to [count] next unmatched ')'.

For curly braces: [{ and [}.


I don't have any direct answer for you, but you may want to check out the code in the matchparen.vim plugin, which is a standard plugin included in Vim installs (in the plugin directory). That plugin is the one used for highlighting of matching parens, if you have that function enabled. The code is more general than what you need, since it matches across lines, but you may be able to work with it and test whether it finds a match on same line, or at least get some ideas from its code.

0

精彩评论

暂无评论...
验证码 换一张
取 消