How do I get the current search match index and total count programmatically in Vim?
Answer
searchcount()
Explanation
The searchcount() function returns a dictionary containing the current search state: which match the cursor is on, how many total matches exist, and whether the count was truncated. It is available in Vim 8.1.1270+ and Neovim, and is especially useful for building custom statuslines that show [3/15]-style search indicators.
How it works
searchcount() returns a dictionary with these keys:
current— the index of the current match (1-based)total— the total number of matches in the bufferincomplete—0if complete,1if search timed out,2if count exceededmaxcountexact_item—1if cursor is on an exact match
Run this from the command line to inspect the live state:
:echo searchcount()
Example
After pressing * on a word that appears 15 times, with the cursor on the 3rd match:
:echo searchcount()
Outputs:
{'current': 3, 'total': 15, 'incomplete': 0, 'exact_item': 1}
You can embed this in a statusline. For example, in a Neovim Lua config:
set statusline+=%{get(searchcount(),'current',0).'/'.get(searchcount(),'total',0)}
Tips
- Pass
{'recompute': 1}to force a fresh count:searchcount({'recompute': 1}) - Pass
{'maxcount': 0}to count all matches without the default limit of 99 - Works with any active search pattern — set the pattern with
:let @/ = 'pattern'before calling it