Find/Replace within selection

Following several user requests for a “find/replace within selection” option, I’ve been thinking about how to implement this feature. It feels like there are two main options:

  • Instead of moving the selection to highlight the current search match while searching, use a different decoration to highlight the current search match. Use the actual selection to limit the scope of the search matching, and decide whether to move the selection to the range of the current search match when the search form loses focus.
  • Store the original selection(s) when the search form opens, use the stored selection(s) to limit the scope of the search matching, and decide whether to restore the original selection when the search form loses focus.

Do those sound like reasonable possibilities, and would one of them make more sense than the other?

It would be ideal if this can be added in a way that’s compatible with the @codemirror/search extension, to avoid having to fork the extension and duplicate existing functionality.

Both of these should work, but I’m not sure what integrating them with @codemirror/search would look like. It seems like this would require support both in the search query data type (to add some kind of scope) and in the dialog (to add controls for it).

I think I’ve found an approach which seems to work, and doesn’t change too much of the existing search extension.

It stores the current editor selection at the time the “within selection” option is enabled, and passes that as a scope option to subsequent queries. The scope is then used as a filter for each search match.

If that seems like a reasonable approach, I can open a pull request.

It would perhaps be useful if the scope was made visible using a faint decoration, but I haven’t attempted that yet.

I don’t think I want this in @codemirror/search—my remark earlier was pointing out the integration with the rest of the search functionality being difficult without support in the package, not requesting a PR.

No problem - I’ve applied this to a fork of @codemirror/search , with the addition of a state field which provides a decoration that highlights the stored selection, and it seems to be working nicely.