gpt4 book ai didi

Vim 在 C/C++ 代码行中搜索

转载 作者:行者123 更新时间:2023-12-04 13:37:12 24 4
gpt4 key购买 nike

有没有办法在跳过注释行的同时搜索 C/C++ 源文件中的字符串?

最佳答案

这是一个耐人寻味的问题。

我认为@sixtyfootersdude 的想法是正确的——让 Vim 的语法突出显示告诉您什么是注释,什么不是,然后在非注释中搜索匹配项。

让我们从一个模仿 Vim 内置的函数开始 search()例程,但也提供了一个“跳过”参数,让它忽略一些匹配:

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, pattern)
"
" Searches for the specified pattern, but skips matches that don't
" exist within the specified syntax region.
"
call SearchWithSkip(a:pattern, '', '', '',
\ 'synIDattr(synID(line("."), col("."), 0), "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 认为是字符串的文本中。

并且(终于!)这将搜索 double除评论外的所有地方:
:SearchOutside Comment double

要重复搜索,请使用 @:重复执行相同命令的宏,例如按 n重复搜索。

(顺便说一下,感谢您提出这个问题。既然我已经构建了这些例程,我希望能经常使用它们。)

关于Vim 在 C/C++ 代码行中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2683521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com