Skip to main content

ass_editor/commands/delta_commands/
insert.rs

1//! Incremental insert command with delta tracking
2
3use super::DeltaCommand;
4use crate::core::{EditorDocument, Position, Range, Result};
5
6#[cfg(not(feature = "std"))]
7use alloc::{format, string::String};
8
9/// Insert text command with delta tracking
10#[derive(Debug, Clone)]
11pub struct IncrementalInsertCommand {
12    pub position: Position,
13    pub text: String,
14}
15
16impl IncrementalInsertCommand {
17    /// Create a new incremental insert command
18    pub fn new(position: Position, text: String) -> Self {
19        Self { position, text }
20    }
21}
22
23impl DeltaCommand for IncrementalInsertCommand {
24    fn execute_with_delta(&self, document: &mut EditorDocument) -> Result<super::CommandResult> {
25        #[cfg(feature = "stream")]
26        {
27            if self.supports_incremental() {
28                // Use incremental parsing for optimal performance
29                match document.insert_incremental(self.position, &self.text) {
30                    Ok(delta) => {
31                        let result = super::CommandResult {
32                            success: true,
33                            message: Some(format!(
34                                "Inserted text at position {}",
35                                self.position.offset
36                            )),
37                            modified_range: Some(Range::new(
38                                self.position,
39                                Position::new(self.position.offset + self.text.len()),
40                            )),
41                            new_cursor: Some(Position::new(self.position.offset + self.text.len())),
42                            content_changed: true,
43                            script_delta: Some(delta),
44                        };
45                        return Ok(result);
46                    }
47                    Err(_) => {
48                        // Fallback to regular insert
49                    }
50                }
51            }
52        }
53
54        // Regular insert without delta tracking
55        document.insert(self.position, &self.text)?;
56        let result = super::CommandResult::success_with_change(
57            Range::new(
58                self.position,
59                Position::new(self.position.offset + self.text.len()),
60            ),
61            Position::new(self.position.offset + self.text.len()),
62        );
63        Ok(result)
64    }
65
66    fn description(&self) -> String {
67        format!(
68            "Insert '{}' at position {}",
69            self.text, self.position.offset
70        )
71    }
72}