With the Prose Mirror search module, I was wondering how to easily get the number of replacements when I perform a replace all. It works just fine, but I would like to tell the user how many instances were replaced, whether or not I first did a find (where I can get the number of ProseMirror-search-match matches in the document after doing a find.
You could run over the current document with the query using SearchQuery.findNext, and count the matches.
Two question there:
First, would I have to set the editor selection first to the beginning and then loop the findNext until it returns null? Since there is not a find first (sigh!), I do believe the findNext will start at the current selection position, returning null when the last match is found. Seems like I would have to get the current selection range (if I want it preserved), set it to the beginning, run the findNext loop and then perhaps set it back to what it was. A bit tedious (just as an observation!).
Second, would it be a good update to have the replaceAll return the number of matches instead of true/false? I use the library as is (via my npm) and do not want to have to host it locally to change it.
I pointed you to the findNext method on a query, not the findNext command. And no, replaceAll is a command and that doesn’t return a number.
So, are you saying that the query findNext (which I did understand) does not start at the current selection? I will check the source code, but because the title is findNext, I assumed it started the search at the current selection forward. Maybe it keeps its own position in the query.
So here is the code that works, thanks for the help Marijn!
// Find out how many will get replaced
let query = new SearchQuery({search: searchString, wholeWord: wholeword})
let numFound = 0, curPos=0, result
while (result = query.findNext(view.state, curPos)){
numFound++
curPos = result.from+1
}