Trait undo::UndoCmd [] [src]

pub trait UndoCmd: Debug {
    fn redo(&mut self) -> Result;
    fn undo(&mut self) -> Result;

    fn id(&self) -> Option<u64> { ... }
}

Trait that defines the functionality of a command.

Every command needs to implement this trait to be able to be used with the UndoStack.

Required Methods

Executes the desired command and returns Ok if everything went fine, and Err if something went wrong.

Restores the state as it was before redo was called and returns Ok if everything went fine, and Err if something went wrong.

Provided Methods

Used for merging of UndoCmds.

Two commands are merged together when a command is pushed on the UndoStack, and it has the same id as the top command already on the stack. When commands are merged together, undoing and redoing them are done in one step. An example where this is useful is a text editor where you might want to undo a whole word instead of each character.

Default implementation returns None, which means the command will never be merged.

Examples

use undo::{UndoCmd, UndoStack};

#[derive(Debug)]
struct TxtCmd(char);

impl UndoCmd for TxtCmd {
    fn redo(&mut self) -> undo::Result {
        Ok(())
    }

    fn undo(&mut self) -> undo::Result {
        Ok(())
    }

    fn id(&self) -> Option<u64> {
        // Merge cmd if not a space.
        if self.0 == ' ' {
            None
        } else {
            Some(1)
        }
    }
}

fn foo() -> undo::Result {
    let mut stack = UndoStack::new();
    stack.push(TxtCmd('a'))?;
    stack.push(TxtCmd('b'))?; // 'a' and 'b' is merged.
    stack.push(TxtCmd(' '))?;
    stack.push(TxtCmd('c'))?;
    stack.push(TxtCmd('d'))   // 'c' and 'd' is merged.
}

Implementors