# Transactions and plugin state

> Remember the last inserted snippet in one editor and reuse it in a second command.

Extend [the snippet command](/docs/plugins/custom/commands/) with **Mod-Shift-J** to repeat the last snippet. Keep the last string in editor-local state so each open editor remembers its own snippet.

## Commit the text and state together

Replace `src/commands.rs` with the complete plugin below. Add `REPEAT_SNIPPET` to the existing `pub use commands::{...}` declaration in `src/lib.rs`.

**src/commands.rs**

```rust
use gpdoc_plugin::prelude::*;


#[derive(Clone)]
pub struct InsertSnippet {
    pub text: String,
}


impl Command for InsertSnippet {
    const NAME: &'static str = "insertSnippet";
}
unit_command!(pub RepeatSnippet, "repeatSnippet");


#[derive(Clone, Debug, Default, PartialEq)]
struct LastSnippet(String);


pub fn snippets() -> Plugin {
    Plugin::new("snippets", |p| {
        p.command::<InsertSnippet>(|ctx, command| insert_snippet(ctx, command.text));
        p.command::<RepeatSnippet>(|ctx, _| {
            let Some(last) = ctx.plugin_state::<LastSnippet>() else {
                return Ok(None);
            };
            insert_snippet(ctx, last.0.clone())
        });


        p.shortcut(
            gpdoc_plugin::key!("Mod-Alt-j"),
            InsertSnippet { text: "Hi!".into() },
        );
        p.shortcut(gpdoc_plugin::key!("Mod-Shift-j"), RepeatSnippet);
    })
}


fn insert_snippet(ctx: CommandContext<'_>, text: String) -> CommandResult {
    let Selection::Text { anchor, head } = ctx.selection() else {
        return Ok(None);
    };
    let mut tx = ctx.transaction();
    tx.update_plugin_state(|last: &mut LastSnippet| last.0.clone_from(&text));
    tx.push(Edit::ReplaceText {
        range: anchor.min(head)..anchor.max(head),
        text,
    });
    Ok(Some(tx))
}


#[cfg(test)]
mod tests;
```

`insert_snippet` starts a transaction from the command context. It writes the new value of `LastSnippet` and pushes the text replacement into the same transaction. If the edit fails, the editor discards both changes.

`repeatSnippet` reads the current value from the context. Until an insert succeeds, there is no value to repeat and the command returns `Ok(None)`. Once a snippet exists, both shortcuts use the same insertion handler.

The editor stores one value per Rust type. A dedicated `LastSnippet` type gives this plugin its own slot. The editor’s document undo history tracks the text edits. Undoing an insertion leaves the remembered snippet available.

## Test repeat and undo

Create `src/commands/tests.rs` for the `mod tests;` declaration above.

**src/commands/tests.rs**

```rust
use super::{InsertSnippet, RepeatSnippet, snippets};
use gpdoc_plugin::EditorConfig;
use gpdoc_plugin::prelude::*;
use gpdoc_plugin_paragraph::paragraph;


#[test]
fn repeat_the_last_snippet() -> Result<(), Error> {
    let config = EditorConfig::builder()
        .plugin(paragraph())
        .plugin(snippets())
        .build()?;
    let mut editor =
        gpdoc_plugin::core::Editor::from_document(&config, vec![Node::textblock("paragraph", "")])?;
    assert!(matches!(
        editor.run(RepeatSnippet)?,
        CommandOutcome::NotApplicable
    ));


    editor.run(InsertSnippet { text: "Hi!".into() })?;
    editor.run(RepeatSnippet)?;
    assert_eq!(
        editor.document().blocks(),
        [Node::textblock("paragraph", "Hi!Hi!")]
    );


    editor.undo()?;
    assert_eq!(
        editor.document().blocks(),
        [Node::textblock("paragraph", "Hi!")]
    );
    editor.undo()?;
    assert_eq!(
        editor.document().blocks(),
        [Node::textblock("paragraph", "")]
    );
    editor.run(RepeatSnippet)?;
    assert_eq!(
        editor.document().blocks(),
        [Node::textblock("paragraph", "Hi!")]
    );
    Ok(())
}
```

Run `cargo test`. The test checks repeat before the first insert, the text after two insertions, and what repeat can still insert after undo.

## Share the writing plugins

To let an app install both the caption and snippet plugins together, add this preset to `src/lib.rs`. An app can pass `writing_plugins()` alongside its paragraph plugin when assembling the config.

```rust
pub fn writing_plugins() -> Vec<Plugin> {
    vec![caption(), snippets()]
}
```