我有两个文本文件,一个是我正在处理的文件,另一个是包含行号列表。我想要做的是突出显示第一个文件中行号与后一行匹配的行。
E.g:
File1中:
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
谢谢!
答案 0 :(得分:4)
您可以使用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