# Find and replace

> Highlight, navigate, and replace matching text in a document.

Register Find and replace to power a search bar or a bulk text edit. Searches span adjacent marked text within a block, so formatting inside a word does not split the match.

## Try it

[Try the find-and-replace editor example](https://gpdoc.dev/docs/plugins/behavior/find-and-replace/#find-and-replace-example)

## Install

Run this from a [Quickstart project](/docs/quickstart/).

```sh
cargo add gpdoc-plugin-find-and-replace
```

## Example

Use `search_highlights` with the built-in `paint_match` painter to display matches in the [Quickstart editor](/docs/quickstart/#configure-the-editor).

```rust
use gpdoc::{EditorConfig, PluginViewExt, ViewPlugin};
use gpdoc_plugin_find_and_replace::{find_and_replace, paint_match, search_highlights};
use gpdoc_plugin_paragraph::paragraph;


let config = EditorConfig::builder()
    .plugin(paragraph())
    .plugin(find_and_replace().with_view(highlights))
    .build()
    .expect("configure editor");


fn highlights() -> ViewPlugin {
    search_highlights(paint_match)
}
```

Run `SetSearchTerm("draft".into())` on a document containing `draft and draft`. Both matches receive a highlight.

## Compose a search highlight

The plugin measures the visible fragments of each match and calls your painter for each fragment. A match that wraps across lines has a rectangle on each line.

### Anatomy

```text
search_highlights(...)  Maps search results to the editor's text layout
└── MatchHighlight      One visible fragment of a search result
    ├── current         Whether this result is the active match
    ├── bounds          Rectangle to paint in the window
    └── range           Document range of the entire match
```

### Paint only the current match

Replace `highlights` in the example. Use `hit.current` to decide which fragments to pass to the built-in painter.

```rust
fn highlights() -> ViewPlugin {
    search_highlights(|hit, window, cx| {
        if hit.current {
            paint_match(hit, window, cx);
        }
    })
}
```

Run `GoToNextResult` to move the highlight through the matches. The plugin draws the highlight above mark backgrounds and below the native selection.

## Replace every occurrence of a word

Use the configuration above to replace both occurrences of `draft` in one transaction.

```rust
use gpdoc::{Editor, Node};
use gpdoc_plugin_find_and_replace::{results, ReplaceAll, SetReplaceTerm, SetSearchTerm};


let mut editor = Editor::from_document(&config, vec![Node::textblock("paragraph", "draft and draft")])?;


editor.run(SetSearchTerm("draft".into()))?;
assert_eq!(results(&editor).ranges.len(), 2);


editor.run(SetReplaceTerm("final".into()))?;
editor.run(ReplaceAll)?;
assert_eq!(
  editor.document().blocks(),
  [Node::textblock("paragraph", "final and final")],
);
```

## Settings

### Search across blocks

The default plugin searches one text block at a time. In `find_and_replace_with`, returning `true` for a block lets its text continue the preceding block for both search and replacement.

```rust
use gpdoc_plugin_find_and_replace::find_and_replace_with;


let plugin = find_and_replace_with(|block| block.kind == "paragraph");
```

## Commands

### setSearchTerm

Set `term` to a string. An empty query clears the matches.

```rust
editor.run(gpdoc_plugin_find_and_replace::SetSearchTerm("draft".into()))?;
```

### setReplaceTerm

Set `term` to the literal replacement string. The default empty string deletes the matched text.

```rust
editor.run(gpdoc_plugin_find_and_replace::SetReplaceTerm("final".into()))?;
```

### setCaseSensitive

Matching ignores case by default. Set `caseSensitive` to `true` to distinguish `Draft` from `draft`.

```rust
editor.run(gpdoc_plugin_find_and_replace::SetCaseSensitive(true))?;
```

### setWholeWord

Set `wholeWord` to `true` to match complete words in a literal search. The default is `false`. In regex mode, include word boundaries in the pattern itself.

```rust
editor.run(gpdoc_plugin_find_and_replace::SetWholeWord(true))?;
```

### setUseRegex

Set `useRegex` to `true` to interpret the query as a Rust regular expression. The default is literal matching. Invalid patterns yield no matches.

```rust
editor.run(gpdoc_plugin_find_and_replace::SetUseRegex(true))?;
```

### goToNextResult

Select the first match on the first call. Subsequent calls advance and wrap to the beginning.

```rust
editor.run(gpdoc_plugin_find_and_replace::GoToNextResult)?;
```

### goToPreviousResult

Select the first match on the first call. Subsequent calls move backward and wrap to the last result.

```rust
editor.run(gpdoc_plugin_find_and_replace::GoToPreviousResult)?;
```

### replace

Replace the current match, or the first if you have not navigated yet. The next remaining match becomes selected.

```rust
editor.run(gpdoc_plugin_find_and_replace::Replace)?;
```

### replaceAll

Replace every match in one transaction.

```rust
editor.run(gpdoc_plugin_find_and_replace::ReplaceAll)?;
```

### clearSearch

Clear the search term, highlights, and current index while preserving the replacement text and matching options.

```rust
editor.run(gpdoc_plugin_find_and_replace::ClearSearch)?;
```

## Read matches

### results

Call `results(&editor)` to read a `SearchResults` value from the find-and-replace plugin. Its `ranges` are document positions with exclusive ends. Its `current` field is the zero-based index of the active match. A new query starts at the first match. An empty result has `current: None`. A custom view can use this index to emphasize it.

```rust
let matches = results(&editor);
let active = matches.current.and_then(|index| matches.ranges.get(index));
```

### search

Run an independent query against a document. `SearchOptions` defaults to an empty `term: String` and `false` for `case_sensitive`, `whole_word`, and `use_regex`.

```rust
use gpdoc_plugin_find_and_replace::{search, SearchOptions};


let options = SearchOptions { term: "draft".into(), ..Default::default() };
let matches = search(editor.document(), &options);
```

### search_with

Pass a continuation predicate to the standalone search. It returns document ranges using the same rules as the configured plugin.

```rust
use gpdoc_plugin_find_and_replace::search_with;


let matches = search_with(editor.document(), &options, |block| block.kind == "paragraph");
```

## Source code

[find-and-replace/src/lib.rs](/source/plugins/find-and-replace/src/lib.rs.txt)