在未打开的文件中将行加载到VimScript中的变量中

时间:2015-02-09 02:30:10

标签: vim

我需要根据某些外部命令的输出构建一个quickfix列表。但该命令只给我文件名和行号,如:

foo.txt:10
bar.txt:20

我想将指定文件的实际内容添加到quickfix列表中,例如:

foo.txt:10: this is some line from foofile
bar.txt:20: hello world, we're a line from barfile

可以这样做吗?

理想情况下,我希望这是跨平台的,所以可能在纯VimScript中,没有调用 sed 等外部命令?

模拟

我可以使用以下函数模拟我当前的行为:

function! MyFunc()
    let mylist = ["foo.txt:10:...", "bar.txt:20:..."]
    cgetexpr mylist
    copen
endfunction

call MyFunc()

我希望...部分成为真实文件中的内容......

2 个答案:

答案 0 :(得分:3)

嗯,基于a partially related question on comp.editors:help readfile,我在下面说可能有用,无论多么浪费:

function! MyFunc()
    let mylist = ["foo.txt:10:...", "bar.txt:20:..."]
    let result = []
    for elem in mylist
        let temp = split(elem, ":")
        let line = elem . ":" . readfile(temp[0], "", temp[1])[temp[1]-1]
        call add(result, line)
    endfor
    cgetexpr line
    copen
endfunction

call MyFunc()

答案 1 :(得分:2)

这是一个解决方案:

fun! GetFileLine(fn,ln)
    return readfile(a:fn,'',a:ln)[a:ln-1]
endfun

fun! AppendLineToFnLn(list)
    return map(a:list, 'v:val.'':''.call(''GetFileLine'', split(v:val,'':'') )' )
endfun

fun! QuickFixWithLine(cmd)
    cexpr AppendLineToFnLn(split(system(a:cmd),"\n"))
endfun

call QuickFixWithLine('echo myfile:22; echo myfile:40;')
copen