3

我有两个文本文件,一个是我当前正在工作的文件,另一个包含行号列表。我想做的是突出显示第一个文件中行号与后一个文件匹配的行。

例如:

文件1:

I like eggs
I like meat
I don't like eggplant
My mom likes chocolate
I like chocolate too

文件2:

2
4

在此示例中,应突出显示这些行:

I like meat
My mom likes chocolate

谢谢!

4

1 回答 1

5

您可以使用readfile()读取行号,然后将它们转换为与这些行号匹配的正则表达式(例如\%42l)。突出显示可以通过:match或完成matchadd()

这是所有这些都浓缩成一个自定义:MatchLinesFromFile命令:

":MatchLinesFromFile {file}
"           Read line numbers from {file} and highlight all those
"           lines in the current window.
":MatchLinesFromFile    Remove the highlighting of line numbers.
"
function! s:MatchLinesFromFile( filespec )
    if exists('w:matchLinesId')
        silent! call matchdelete(w:matchLinesId)
        unlet w:matchLinesId
    endif
    if empty(a:filespec)
        return
    endif

    try
        let l:lnums =
        \   filter(
        \   map(
        \       readfile(a:filespec),
        \       'matchstr(v:val, "\\d\\+")'
        \   ),
        \   '! empty(v:val)'
        \)

        let l:pattern = join(
        \   map(l:lnums, '"\\%" . v:val . "l"'),
        \   '\|')

        let w:matchLinesId = matchadd('MatchLines',  l:pattern)
    catch /^Vim\%((\a\+)\)\=:E/
        " v:exception contains what is normally in v:errmsg, but with extra
        " exception source info prepended, which we cut away.
        let v:errmsg = substitute(v:exception, '^Vim\%((\a\+)\)\=:', '', '')
        echohl ErrorMsg
        echomsg v:errmsg
        echohl None
    endtry
endfunction
command! -bar -nargs=? -complete=file MatchLinesFromFile call <SID>MatchLinesFromFile(<q-args>)

highlight def link MatchLines Search
于 2012-12-03T08:56:20.083 回答