vim使用外部文件上的行号突出显示行 [英] vim highlight lines using line number on external file

查看:102
本文介绍了vim使用外部文件上的行号突出显示行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本文件,一个是我当前正在使用的文件,另一个包含行号列表.我想做的是在第一个文件中高亮显示行号与后一个匹配的行.

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.

例如:

文件1:

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

文件2:

2
4

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

In this example the those lines should be highlighted:

I like meat
My mom likes chocolate

谢谢!

推荐答案

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

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().

所有这些都压缩到一个自定义的:MatchLinesFromFile命令中:

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

这篇关于vim使用外部文件上的行号突出显示行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆