Skip to main content

ass_editor/commands/script_info_commands/
delete.rs

1//! Command to remove a property from the `[Script Info]` section.
2
3use crate::commands::{CommandResult, EditorCommand};
4use crate::core::{EditorDocument, EditorError, Position, Range, Result};
5
6#[cfg(not(feature = "std"))]
7use alloc::{
8    format,
9    string::{String, ToString},
10};
11
12/// Command to delete a script info property from the ASS document
13///
14/// Removes a specific property from the `[Script Info]` section.
15/// Does not remove the section itself even if it becomes empty.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct DeleteScriptInfoCommand {
18    /// Property name to delete
19    pub property: String,
20}
21
22impl DeleteScriptInfoCommand {
23    /// Create a new delete script info command
24    pub fn new(property: String) -> Self {
25        Self { property }
26    }
27}
28
29impl EditorCommand for DeleteScriptInfoCommand {
30    fn execute(&self, document: &mut EditorDocument) -> Result<CommandResult> {
31        let content = document.text().to_string();
32
33        // Find [Script Info] section
34        let script_info_start = content
35            .find("[Script Info]")
36            .ok_or_else(|| EditorError::command_failed("No [Script Info] section found"))?;
37
38        // Find the end of Script Info section
39        let script_info_end = content[script_info_start..]
40            .find("\n[")
41            .map(|pos| script_info_start + pos)
42            .unwrap_or(content.len());
43
44        // Look for the property
45        let property_pattern = format!("{}: ", self.property);
46        let search_range = &content[script_info_start..script_info_end];
47
48        if let Some(prop_pos) = search_range.find(&property_pattern) {
49            let absolute_pos = script_info_start + prop_pos;
50            let line_end = content[absolute_pos..]
51                .find('\n')
52                .map(|pos| absolute_pos + pos + 1) // Include newline
53                .unwrap_or(content.len());
54
55            let range = Range::new(Position::new(absolute_pos), Position::new(line_end));
56            document.delete(range)?;
57
58            Ok(CommandResult::success_with_change(
59                Range::new(Position::new(absolute_pos), Position::new(absolute_pos)),
60                Position::new(absolute_pos),
61            ))
62        } else {
63            Ok(CommandResult::success())
64        }
65    }
66
67    fn description(&self) -> &str {
68        "Delete script info property"
69    }
70
71    fn memory_usage(&self) -> usize {
72        core::mem::size_of::<Self>() + self.property.len()
73    }
74}