# Suggestion

> Find a completion query before the caret and replace it with an inline node.

`Trigger` finds text after a character such as `@` at the caret. Use the query to filter a mention picker in your app.

## Try it

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

## Install

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

```sh
cargo add gpdoc-plugin-suggestion gpdoc-plugin-mention
```

## Example

Use the Mention plugin’s inline node and `Accept` command to complete topic tags. The matcher finds a `#` query at the caret. The provider pairs each matching name with the command that inserts its tag.

```rust
use gpdoc::{AnchoredElement, EditorConfig, PluginViewExt, ViewPlugin};
use gpdoc_plugin_mention::{Accept, Mention, mention};
use gpdoc_plugin_paragraph::paragraph;
use gpdoc_plugin_suggestion::{SuggestionItem, SuggestionMenu, Trigger, suggestion_picker};
use gpui::{App, Window};


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


fn topic_picker() -> ViewPlugin {
    suggestion_picker(
        "topicPicker",
        |editor| Trigger::new('#').find(editor.document(), editor.selection()),
        |_, matched| {
            ["design", "docs", "release"]
                .into_iter()
                .filter(|name| name.starts_with(&matched.query))
                .map(|name| {
                    let mut tag = Mention::new(name, name);
                    tag.trigger = '#';
                    SuggestionItem::new(name, Accept(tag))
                })
                .collect()
        },
        render_topics,
    )
}


fn render_topics(menu: SuggestionMenu<&'static str>, _: &mut Window, _: &mut App) -> AnchoredElement {
    menu.labeled_list(|name| name.to_string())
}
```

Type `#d` at the start of a paragraph. Press **Down** to select **docs**, then **Enter** to insert `#docs` followed by a space.

## Compose a suggestion picker

Use `menu.list` to display matching records and track the active row. The picker handles arrow keys, Enter, and Escape.

### Anatomy

```text
menu.popover(...)          Anchors the list below the caret
└── menu.list(4, ...)      Keeps the active row within four visible matches
    └── row.element()      Accepts the candidate on click and keeps editor focus
```

### Show a picker in GPUI

Replace `render_topics` with a list that prefixes each name with the tag character. Read `row.value` for the name and `row.is_active()` for the current keyboard selection.

```rust
use gpui::prelude::*;


fn render_topics(menu: SuggestionMenu<&'static str>, _: &mut Window, _: &mut App) -> AnchoredElement {
    let list = menu.list(4, |row| {
        let marker = if row.is_active() { "› " } else { "" };
        row.element().child(format!("{marker}#{}", row.value))
    });
    menu.popover(list)
}
```

Type `#d` and click **#docs** to insert the tag. For pickers that already supply the matcher and candidates, see [Mention](/docs/plugins/media/mention/) and [Slash command](/docs/plugins/behavior/slash-command/#compose-a-slash-menu).

## Read a mention query at the caret

The suggestion crate supplies a helper that works with an existing editor. A config containing just `paragraph()` is enough to look up a query.

With the paragraph plugin installed, put the caret at the end of `Ask @Ada`. The query excludes the trigger character.

```rust
use gpdoc::{DocPos, Editor, EditorConfig, Node, Selection};
use gpdoc_plugin_paragraph::paragraph;
use gpdoc_plugin_suggestion::Trigger;


let config = EditorConfig::builder()
    .plugin(paragraph())
    .build()?;
let editor = Editor::from_document(&config, vec![Node::textblock("paragraph", "Ask @Ada")])?;
let result = Trigger::new('@')
  .find(editor.document(), Selection::caret(DocPos(9)))
  .expect("mention query at the caret");


assert_eq!(result.query, "Ada");
assert_eq!(result.range, DocPos(5)..DocPos(9));
```

## Trigger settings

### Trigger character

Construct a `Trigger` with the character that opens your picker. The public `character: char` field holds it.

```rust
let trigger = Trigger::new('@');
```

### Allowed prefixes

By default, a trigger can appear at the start of the examined text or immediately after a space. This keeps the picker closed in `ada@example.org`. Set `allowed_prefixes: Option<Vec<char>>` to `None` to permit any prefix.

```rust
let mut trigger = Trigger::new('@');
trigger.allowed_prefixes = Some(vec![' ', '(']);
```

### Spaces in queries

Set `allow_spaces` to match a full name such as `@Ada Lovelace`. The default is `false`.

```rust
let mut trigger = Trigger::new('@');
trigger.allow_spaces = true;
```

### Repeated trigger characters

Set `allow_to_include_char` to keep another trigger inside the query. This option defaults to `false` and takes precedence over `allow_spaces`.

```rust
let mut trigger = Trigger::new(':');
trigger.allow_to_include_char = true;
```

### Start of line

Set `start_of_line` to require the trigger at the beginning of the line examined by the matcher. The default is `false`.

```rust
let mut trigger = Trigger::new('/');
trigger.start_of_line = true;
```

## Handle a suggestion

### find

Pass a document and a collapsed text selection. The return value is `Option<SuggestionMatch>`. Use `query: String` to filter choices, `text: String` for the full typed token, and `range: Range<DocPos>` for its location.

```rust
let matched = Trigger::new('@').find(editor.document(), editor.selection());
```

### replace_with_atom

Inside a command handler, supply the selected choice as a registered inline leaf node allowed by the parent. The method returns `Result<Option<Transaction>, Error>`. The transaction replaces the entire token and leaves the caret after a single space. An existing following space is consumed.

```rust
use gpdoc_plugin::core::{CommandContext, Error, Node, Transaction};


fn accept(ctx: CommandContext<'_>, choice: Node) -> Result<Option<Transaction>, Error> {
  Trigger::new('@').replace_with_atom(ctx, choice)
}
```

## Source code

[suggestion/src/lib.rs](/source/plugins/suggestion/src/lib.rs.txt)