2

I search some words so that there are many highlight results in the current window.

I use n to move cursor to a matching result, how to know its index of match results easily?

I have tried SearchPosition, but it does not work in my Vim.

2

I don't know if it's exactly what you want, but to get the number of matches and the index of the current match, I'm using a modified version of this:

nno n n@=Search_and_index()<CR>
nno N N@=Search_and_index()<CR>

fu! Search_and_index() abort
    let winview     = winsaveview()
    let [line, col] = [winview.lnum, winview.col]

    call cursor(1, 1)
    let [idx, total]          = [1, 0]
    let [matchline, matchcol] = searchpos(@/, 'cW')
    while matchline && total <= 999
        let total += 1
        if matchline < line || (matchline == line && matchcol <= col)
            let idx += 1
        endif
        let [matchline, matchcol] = searchpos(@/, 'W')
    endwhile

    call winrestview(winview)
    echo @/ . '(' . idx . '/' . total . ')'
    return ''
endfu

It remaps n and N to call the function Search_and_index() which should echo a message such as pattern(3/4).

The while loop is responsible for incrementing the variables total and idx. And at the end of the loop, their values should be respectively the total number of matches of your last search pattern, and the index of the current match (the one under the cursor).

But the loop stops at 999 to avoid taking too much time. You could increase this number if you feel it's too low.

  • My English is poor, but you are right, I want to get the index of the current match! By the way the number of matches is useful too, thank you! – acgtyrant Jan 22 '17 at 3:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.