I have two text files, ones is the file I'm currently working, the other contains a list of line numbers. What I would like to do is to highlight lines in the first file where the line number matches the latter one.
E.g.:
File1:
I like eggs
I like meat
I don't like eggplant
My mom likes chocolate
I like chocolate too
File2:
2
4
In this example the those lines should be highlighted:
I like meat
My mom likes chocolate
Thanks!
You can use readfile() to read in the line numbers, and then convert them into a regular expression that matches those line numbers (e.g. \%42l). The highlighting can be done via :match, or matchadd().
Here's all this condensed into a custom :MatchLinesFromFile command:
":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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With