Vim以C/C++代码行搜索

前端之家收集整理的这篇文章主要介绍了Vim以C/C++代码行搜索前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法在跳过注释行时在C/C++源文件搜索字符串?
这是一个有趣的问题。

我认为@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重复搜索

(感谢您提出这个问题,现在我已经构建了这些例程,我期望使用它们。)

猜你在找的Bash相关文章