vim 仅在非注释行上搜索和替换

vim search and replace only on non-commented lines

我正在尝试仅在非注释行中搜索和替换。

我所说的非注释行是指未被 vim 语法高亮显示为灰色的行。

例如:

/*
...
DO NOT REPLACE
....
*/

不应搜索和替换。 我的问题特定于 C++,但如果有办法使用 vim 的 "syntax engine",则可以扩展到任何语言。

编辑:link 仅与搜索有关,与替换无关。

我终于用 Bill Odom code 作为基础自己完成了:

function Repl(pattern, patternSub)

    " Move to top of the file
    normal 1G

    " Search Pattern, no wrap
    while search(a:pattern, "W", "", "") > 0

        " If found pattern is a comment, skip
        if eval(synIDattr(synID(line("."), col("."), 0), "name") =~? "Comment")
            continue
        endif

        " If found pattern is a string, skip
        if eval(synIDattr(synID(line("."), col("."), 0), "name") =~? "String")
            continue
        endif

        " Replace pattern by it's substitute
        exec '.s/'.a:pattern.'/'.a:patternSub.'/'

        " Restore cursor position
        normal ``
    endwhile
endfunction

command! -nargs=+ -complete=command Repl call Repl(<args>)

它不会替换任何出现的注释或字符串模式。 它实际上是独立于语言的。

您必须这样使用它(例如:在所有未注释的括号后删除 space):

:Repl '( *','('