0

My end goal is to be able to highlight all the matches of the word being typed and echo their number, but this question is about one specific aspect of this, which I've been having trouble with, which is getting the number of those matches without altering the / buffer nor moving the curosor.

From the name, searchcount seemed promising, but in reality it isn't (if I understood correctly), because it has to do with the actual "last search", i.e. what you do with / or :s, whereas I'm actually using matchadd to highlight the matches of a given text, and I want the count of those matches.

So I thought that I could give execute('%s/the-text//gn') a try, but apparently it's not the right tool: the following toy example shows echos the number of characters being written, but writing ciao in a file results in oaic, just like echo execute('%s/.//gn')->split('\n')[0]¹ is causing the cursor to go back to the beginning of the line upon each keystroke.

augroup Foo
  autocmd!
  autocmd TextChangedI,TextChangedP * call <SID>foo()
  fun s:foo()
    echo execute('%s/.//gn')->split('\n')[0]
  endf
augroup END

Note that changing echo execute('%s/.//gn')->split('\n')[0] to echo "bla" or even echo execute('echo "ciao"')->split('\n')[0] doesn't cause the same issue, so echo and execute seem both innocent, whereas :s seems to be causing the issue.


(¹) The ->split('\n')[0] is to avoid the Press ENTER or type command to continue prompt.

6
  • 1
    :help getmatches() is mentioned at the bottom of :help matchadd().
    – romainl
    Commented Jun 29, 2023 at 5:38
  • 1
    the searchcount() function accepts a pattern argument! See also this answer which shows a complete example for the searchcount() function. You just need to provide a pattern to it Commented Jun 29, 2023 at 7:17
  • Does this link help? Restoring the cursor position from backtick register works for me; simply put let a = getpos("'`") | call cursor(a[1], a[2]) after the execute line.
    – Hoblovski
    Commented Jun 29, 2023 at 13:51
  • @Hoblovski, it seems to work, thanks!
    – Enlico
    Commented Jun 30, 2023 at 16:01
  • I've also asked a follow up question here.
    – Enlico
    Commented Jun 30, 2023 at 16:20

0

Your Answer

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