Skip to main content

ass_editor/commands/style_commands/
delete.rs

1//! Style deletion command for ASS documents.
2//!
3//! Provides [`DeleteStyleCommand`] to remove a named style line from the
4//! styles section.
5
6use crate::commands::{CommandResult, EditorCommand};
7use crate::core::{EditorDocument, EditorError, Position, Range, Result};
8
9#[cfg(not(feature = "std"))]
10use alloc::{format, string::String};
11
12/// Command to delete a style
13#[derive(Debug, Clone)]
14pub struct DeleteStyleCommand {
15    pub style_name: String,
16    pub description: Option<String>,
17}
18
19impl DeleteStyleCommand {
20    /// Create a new style deletion command
21    pub fn new(style_name: String) -> Self {
22        Self {
23            style_name,
24            description: None,
25        }
26    }
27
28    /// Set custom description
29    #[must_use]
30    pub fn with_description(mut self, description: String) -> Self {
31        self.description = Some(description);
32        self
33    }
34}
35
36impl EditorCommand for DeleteStyleCommand {
37    fn execute(&self, document: &mut EditorDocument) -> Result<CommandResult> {
38        let content = document.text();
39        let style_pattern = format!("Style: {}", self.style_name);
40
41        if let Some(style_start) = content.find(&style_pattern) {
42            // Find the complete line including the newline
43            let line_start = content[..style_start]
44                .rfind('\n')
45                .map(|pos| pos + 1)
46                .unwrap_or(0);
47            let line_end = content[style_start..]
48                .find('\n')
49                .map(|pos| style_start + pos + 1) // Include the newline
50                .unwrap_or(content.len());
51
52            let range = Range::new(Position::new(line_start), Position::new(line_end));
53            document.delete(range)?;
54
55            Ok(CommandResult::success_with_change(
56                Range::new(Position::new(line_start), Position::new(line_start)),
57                Position::new(line_start),
58            )
59            .with_message(format!("Deleted style '{}'", self.style_name)))
60        } else {
61            Err(EditorError::command_failed(format!(
62                "Style '{}' not found",
63                self.style_name
64            )))
65        }
66    }
67
68    fn description(&self) -> &str {
69        self.description.as_deref().unwrap_or("Delete style")
70    }
71
72    fn memory_usage(&self) -> usize {
73        core::mem::size_of::<Self>()
74            + self.style_name.len()
75            + self.description.as_ref().map_or(0, |d| d.len())
76    }
77}