Search code examples
vimvi

How to keep the index and value after using `filter()` in Vim


I'll use getline(1, '$') to get an all line list in a document. and filter() them by some expression. But I also need to keep the index(the line number) for after reference. How could I do this?

let lines = getline(1, '$')
filter(lines, 'EXPRESSION')

The result should be a list or anything I can refer to the index: [[1, LINE1], [4, LINE4],... [n, LINEn]]


Solution

  • You can use v:key to get the index of the list in map(), and then v:key + 1 will be the line numer as follows.

    let lines = map(getline(1, '$'), '[v:key + 1, v:val]')
    call filter(lines, 'v:val[1] == "EXPRESSION"')