0

Sorry. Although this is one duplicate question of this, but I don't have reputations now, so I can't comment on the above original question. As one workaround, I posted a new question and this is my first question in this vi community. Hope someone can help me.

My question: If I search multiple times in one file, the counter won't be reinited as 0 between each search (here counter is to index the searched items). So it will keep increasing if I do the same search twice which is obviously not what needed.

for example, for string 111, if I searched first time and replaced, it is replaced as 123, but if I search 222 in the same file without quiting vim, it will be replaced as 456, which is not what I want( 123 to index them).

So can vim function reinited the counter referenced in the above link every time it gets called?

Specifically, I added one keymap based on above link

"from above link
function! MakeSearchIndex()
    let counter = 0
    function! SearchIndex() closure
        let counter += 1
        return counter
    endfunction
    return funcref('SearchIndex')
endfunction
let SI=MakeSearchIndex()
"my added keymap
cnoremap si s/\v/\=SI()/g<left><left><left><left><left><left><left><left><left>
4
  • 1
    It is easier for the reader if the question are self consistent. Maybe could you repeat the part of the question you are referencing and the answer you are using. Commented Apr 20, 2023 at 9:03
  • What counter are you talking about?
    – romainl
    Commented Apr 20, 2023 at 10:15
  • Thanks for the above quick answers, I updated and hoped you can understand my question and help me.
    – An5Drama
    Commented Apr 20, 2023 at 11:24
  • Welcome to vi and vim SE. Asking questions (and getting answers) is pretty much the whole point of this site, no need to apologize.
    – Friedrich
    Commented Apr 20, 2023 at 14:23

1 Answer 1

0

To reinitialize the counter to zero you have to run:

:let SI=MakeSearchIndex()

If you want to reinitialize the counter to zero at every search you could do:

cnoremap si let SI=MakeSearchIndex() <bar> s/\v/\=SI()/g<left><left><left><left><left><left><left><left><left>
2
  • 1
    Thanks. This is same as the original link. And since | may be misinterpreted (which I also met when following my reference link but at that time I didn‘t make a deeper try) according to fandom, this cnoremap si s/\v /\=SI()/g <bar> let SI=MakeSearchIndex()<C-Left><C-Left><C-Left><C-Left><BS> works
    – An5Drama
    Commented Apr 20, 2023 at 14:42
  • Thanks for the feedback!. I have updated the solution. If the solution fit your need maybe could you validate it using the v button next to the arrow voting buttons. It allow the question to rest :-) Commented Apr 20, 2023 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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