In normal mode with default mappings, suppose I type /[,_@]. This then causes all matches of that pattern to be highlighted. Is there some way to examine the results of this search? I am specifically interested in:

  • the start and end positions of each match,
  • the number of matches in the file,
  • the number of matches between my cursor and the end of the file.

Is it possible to obtain this information, for use in further scripting?

If possible, I would like a solution that works without having to explicitly pass a filename, because I want it to be usable when editing text read from stdin or on a new buffer (as with :enew). This, as far as I can tell, disqualifies the use of :vimgrep which requires a filename.

I am aware of the search() function, but I'm not sure if it helps here.

Also, I use Neovim, so I will accept a Neovim-only solution.

  • You can get the number of matches with :%s///n. The rest will probably require a custom function. – B Layer Dec 15 '20 at 3:20
  • @BLayer I clarified that I want to use the output for scripting, not just printing it. – shadowtalker Dec 15 '20 at 3:26
  • Well, in that particular case you can capture in, say, a variable using execute(), e.g. :let foo = execute('%s///n') and likewise if you had a custom function. Or, for anything that outputs text you can use redir (:h :redir) to capture in a file, vim variable or register. I'll write that custom function if I get some time (if no one gets to it before me). – B Layer Dec 15 '20 at 3:30
  • You should add some more details about capturing. The format you have in mind, for one. And how do you intend to use that in a script? Are you talking about another vim function(s)? Or some other scripting method? – B Layer Dec 15 '20 at 3:34
  • BTW. Vim 8.2.0877+ has :h searchcount(). Maybe, it will be ported to Neovim... some day. – Matt Dec 15 '20 at 6:31

Your Answer

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

Browse other questions tagged or ask your own question.