这是一个有趣的问题。
原文链接:https://www.f2er.com/bash/388748.html我认为@sixtyfootersdude有正确的想法 – 让Vim的语法突出显示告诉你什么是评论,什么不是,然后在非评论内搜索匹配。
我们从一个模仿Vim的内置search()例程的函数开始,但也提供了一个“skip”参数,让它忽略一些匹配:
function! SearchWithSkip(pattern,flags,stopline,timeout,skip) " " Returns true if a match is found for {pattern},but ignores matches " where {skip} evaluates to false. This allows you to do nifty things " like,say,only matching outside comments,only on odd-numbered lines," or whatever else you like. " " Mimics the built-in search() function,but adds a {skip} expression " like that available in searchpair() and searchpairpos(). " (See the Vim help on search() for details of the other parameters.) " " Note the current position,so that if there are no unskipped " matches,the cursor can be restored to this location. " let l:matchpos = getpos('.') " Loop as long as {pattern} continues to be found. " while search(a:pattern,a:flags,a:stopline,a:timeout) > 0 " If {skip} is true,ignore this match and continue searching. " if eval(a:skip) continue endif " If we get here,{pattern} was found and {skip} is false," so this is a match we don't want to ignore. Update the " match position and stop searching. " let l:matchpos = getpos('.') break endwhile " Jump to the position of the unskipped match,or to the original " position if there wasn't one. " call setpos('.',l:matchpos) endfunction
这里有一些基于SearchWithSkip()的功能来实现语法敏感搜索:
function! SearchOutside(synName,pattern) " " Searches for the specified pattern,but skips matches that " exist within the specified Syntax region. " call SearchWithSkip(a:pattern,'',\ 'synIDattr(synID(line("."),col("."),0),"name") =~? "' . a:synName . '"' ) endfunction function! SearchInside(synName,but skips matches that don't " exist within the specified Syntax region. " call SearchWithSkip(a:pattern,"name") !~? "' . a:synName . '"' ) endfunction
command! -nargs=+ -complete=command SearchOutside call SearchOutside(<f-args>) command! -nargs=+ -complete=command SearchInside call SearchInside(<f-args>)
这还有很长的路要走,但现在我们可以这样做:
:SearchInside String hello
它搜索hello,但只在Vim认为一个字符串的文本内。
:SearchOutside Comment double
要重复搜索,请使用@:宏重复执行相同的命令,如按n重复搜索。
(感谢您提出这个问题,现在我已经构建了这些例程,我期望使用它们。)