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 echo
s 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.
:help getmatches()
is mentioned at the bottom of:help matchadd()
.pattern
argument! See also this answer which shows a complete example for the searchcount() function. You just need to provide a pattern to itlet a = getpos("'`") | call cursor(a[1], a[2])
after theexecute
line.