ass_editor/commands/command_trait.rs
1//! The core `EditorCommand` trait implemented by all editor commands.
2
3use crate::core::{EditorDocument, Result};
4
5use super::CommandResult;
6
7/// Trait for editor commands that can be executed and undone
8///
9/// All commands implement this trait to provide a consistent interface
10/// for execution, undo/redo, and introspection.
11///
12/// # Examples
13///
14/// Creating a custom command:
15///
16/// ```
17/// use ass_editor::{EditorCommand, EditorDocument, CommandResult, Result, Position, Range};
18///
19/// #[derive(Debug)]
20/// struct UppercaseCommand {
21/// description: String,
22/// }
23///
24/// impl UppercaseCommand {
25/// fn new() -> Self {
26/// Self {
27/// description: "Convert to uppercase".to_string(),
28/// }
29/// }
30/// }
31///
32/// impl EditorCommand for UppercaseCommand {
33/// fn execute(&self, document: &mut EditorDocument) -> Result<CommandResult> {
34/// let text = document.text().to_uppercase();
35/// let range = Range::new(Position::new(0), Position::new(document.len()));
36/// document.replace(range, &text)?;
37/// Ok(CommandResult::success().with_message("Text converted to uppercase".to_string()))
38/// }
39///
40/// fn description(&self) -> &str {
41/// &self.description
42/// }
43/// }
44/// ```
45pub trait EditorCommand: core::fmt::Debug + Send + Sync {
46 /// Execute the command on the given document
47 ///
48 /// Returns a result indicating success/failure and metadata about
49 /// the operation for undo/redo tracking.
50 fn execute(&self, document: &mut EditorDocument) -> Result<CommandResult>;
51
52 /// Get a human-readable description of the command
53 fn description(&self) -> &str;
54
55 /// Check if this command modifies document content
56 ///
57 /// Used to determine if the document should be marked as modified
58 /// and whether to save undo state.
59 fn modifies_content(&self) -> bool {
60 true
61 }
62
63 /// Get the estimated memory usage of this command
64 ///
65 /// Used for memory management in undo stacks with limited capacity.
66 /// Default implementation provides a conservative estimate.
67 fn memory_usage(&self) -> usize {
68 64 // Conservative default estimate for command overhead
69 }
70}