EditorDocument

Struct EditorDocument 

Source
pub struct EditorDocument { /* private fields */ }
Expand description

Main document container for editing ASS scripts

Manages both text content and parsed ASS structures with direct access to events, styles, and script info without manual parsing.

Implementations§

Source§

impl EditorDocument

Source

pub fn new() -> Self

Create a new empty document

Source

pub fn with_event_channel(event_tx: Sender<DocumentEvent>) -> Self

Available on crate feature std only.

Create a new document with event channel

Source

pub fn from_file(path: &str) -> Result<Self>

Available on crate feature std only.

Create document from file path

Source

pub fn save(&mut self) -> Result<()>

Available on crate feature std only.

Save document to file

Source

pub fn save_to_file(&mut self, path: &str) -> Result<()>

Available on crate feature std only.

Save document to specific file path

Source

pub fn with_id(id: String) -> Self

Create document with specific ID

Source

pub fn set_event_channel(&mut self, event_tx: Sender<DocumentEvent>)

Available on crate feature std only.

Set the event channel for this document

Source

pub fn has_event_channel(&self) -> bool

Available on crate feature std only.

Check if document has an event channel

Source

pub fn from_content(content: &str) -> Result<Self>

Load document from string content

Creates a new EditorDocument from ASS subtitle content. The content is validated during creation to ensure it’s parseable.

§Examples
use ass_editor::EditorDocument;

let content = r#"
[Script Info]
Title: My Subtitle

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
Dialogue: 0,0:00:00.00,0:00:05.00,Default,,0,0,0,,Hello World
"#;

let doc = EditorDocument::from_content(content).unwrap();
assert!(doc.text().contains("Hello World"));
§Errors

Returns Err if the content cannot be parsed as valid ASS format.

Source

pub fn parse_script_with<F, R>(&self, f: F) -> Result<R>
where F: FnOnce(&Script<'_>) -> R,

Parse the current document content into a Script

Returns a boxed closure that provides the parsed Script. This avoids lifetime issues by ensuring the content outlives the Script.

Source

pub fn validate(&self) -> Result<()>

Validate the document content can be parsed as valid ASS This is the basic validation that just checks parsing

Source

pub fn execute_command( &mut self, command: &dyn EditorCommand, ) -> Result<CommandResult>

Execute a command with proper history recording

This method ensures that commands are properly recorded in the undo history. Use this instead of calling command.execute() directly if you want undo support.

For BatchCommand, this creates a synthetic undo operation that captures the aggregate effect of all sub-commands.

Source

pub fn validate_comprehensive(&mut self) -> Result<ValidationResult>

Perform comprehensive validation using the LazyValidator Returns detailed validation results including warnings and suggestions

Note: Returns a cloned result to avoid borrow checker issues

Source

pub fn force_validate(&mut self) -> Result<ValidationResult>

Force revalidation even if cached results exist

Source

pub fn is_valid_cached(&mut self) -> Result<bool>

Check if document is valid (quick check using cache if available)

Source

pub fn validation_result(&self) -> Option<&ValidationResult>

Get cached validation result without revalidating

Source

pub fn set_validator_config(&mut self, config: ValidatorConfig)

Configure the validator

Source

pub fn validator_mut(&mut self) -> &mut LazyValidator

Get mutable access to the validator

Source

pub fn id(&self) -> &str

Get document ID

Source

pub fn file_path(&self) -> Option<&str>

Get file path if document is associated with a file

Source

pub fn set_file_path(&mut self, path: Option<String>)

Set file path for the document

Source

pub fn import_format( content: &str, format: Option<SubtitleFormat>, ) -> Result<Self>

Available on crate feature formats only.

Import content from another subtitle format

Source

pub fn export_format( &self, format: SubtitleFormat, options: &ConversionOptions, ) -> Result<String>

Available on crate feature formats only.

Export document to another subtitle format

Source

pub const fn is_modified(&self) -> bool

Check if document has unsaved changes

Source

pub fn cursor_position(&self) -> Option<Position>

Get current cursor position (if tracked)

Source

pub fn set_cursor_position(&mut self, position: Option<Position>)

Set current cursor position for tracking

Source

pub fn set_modified(&mut self, modified: bool)

Mark document as modified

Source

pub fn len_bytes(&self) -> usize

Get total length in bytes

Source

pub fn len_lines(&self) -> usize

Get total number of lines

Source

pub fn is_empty(&self) -> bool

Check if document is empty

Source

pub fn text(&self) -> String

Get text content as string

Source

pub fn rope(&self) -> &Rope

Available on crate feature rope only.

Get direct access to the rope for advanced operations

Source

pub fn len(&self) -> usize

Get the length of the document in bytes

Source

pub fn text_range(&self, range: Range) -> Result<String>

Get text content for a range

Source

pub fn position_to_line_column(&self, pos: Position) -> Result<LineColumn>

Available on crate feature rope only.

Convert byte position to line/column

Source

pub fn insert(&mut self, pos: Position, text: &str) -> Result<()>

Insert text at position with undo support

Inserts text at the given position, automatically updating the underlying text representation and recording the operation in the undo history.

§Examples
use ass_editor::{EditorDocument, Position};

let mut doc = EditorDocument::from_content("Hello World").unwrap();
let pos = Position::new(5); // Insert after "Hello"
doc.insert(pos, " there").unwrap();

assert_eq!(doc.text(), "Hello there World");

// Can undo the operation
doc.undo().unwrap();
assert_eq!(doc.text(), "Hello World");
§Errors

Returns Err if the position is beyond the document bounds.

Source

pub fn delete(&mut self, range: Range) -> Result<()>

Delete text in range with undo support

Source

pub fn replace(&mut self, range: Range, text: &str) -> Result<()>

Replace text in range with undo support

Source

pub fn events_count(&self) -> Result<usize>

Get number of events without manual parsing

Source

pub fn styles_count(&self) -> Result<usize>

Get number of styles without manual parsing

Source

pub fn script_info_fields(&self) -> Result<Vec<String>>

Get script info field names

Source

pub fn sections_count(&self) -> Result<usize>

Get number of sections

Source

pub fn has_events(&self) -> Result<bool>

Check if document has events section

Source

pub fn has_styles(&self) -> Result<bool>

Check if document has styles section

Source

pub fn find_event_text(&self, pattern: &str) -> Result<Vec<String>>

Get event text by line pattern (simplified search)

Source

pub fn edit_event_by_index<F>( &mut self, index: usize, update_fn: F, ) -> Result<String>
where F: for<'a> FnOnce(&Event<'a>) -> Vec<(&'static str, String)>,

Edit event by index with full field support

Allows structured editing of specific event fields by index. Returns the modified event line for undo support.

§Arguments
  • index - Zero-based index of the event to edit
  • update_fn - Function that receives the current event and returns modifications
§Example
doc.edit_event_by_index(0, |event| {
    vec![
        ("text", "New dialogue text".to_string()),
        ("style", "NewStyle".to_string()),
    ]
})?;
Source

pub fn add_event_line(&mut self, event_line: &str) -> Result<()>

Add event line to document

Source

pub fn edit_style_line( &mut self, style_name: &str, new_style_line: &str, ) -> Result<()>

Edit style line

Source

pub fn add_style_line(&mut self, style_line: &str) -> Result<()>

Add style line to document

Source

pub fn edit_incremental( &mut self, range: Range, new_text: &str, ) -> Result<ScriptDeltaOwned>

Available on crate feature stream only.

Perform incremental edit using core’s parse_partial for optimal performance

Includes error recovery with fallback strategies:

  1. Try incremental parsing with Script::parse_partial()
  2. On failure, fall back to full reparse
  3. On repeated failures, reset parser state and retry
Source

pub fn insert_incremental( &mut self, pos: Position, text: &str, ) -> Result<ScriptDeltaOwned>

Available on crate feature stream only.

Insert text with incremental parsing (< 1ms target)

Source

pub fn delete_incremental(&mut self, range: Range) -> Result<ScriptDeltaOwned>

Available on crate feature stream only.

Delete text with incremental parsing

Source

pub fn edit_safe(&mut self, range: Range, new_text: &str) -> Result<()>

Safe edit with automatic fallback to regular replace on error

This method tries incremental parsing first for performance, but falls back to regular replace if incremental parsing is unavailable or fails. This ensures edits always succeed.

Source

pub fn edit_event_incremental( &mut self, event_text: &str, new_text: &str, ) -> Result<ScriptDeltaOwned>

Available on crate feature stream only.

Edit event using incremental parsing for performance

Source

pub fn parse_with_delta_tracking<F, R>( &self, range: Option<StdRange<usize>>, new_text: Option<&str>, f: F, ) -> Result<R>
where F: FnOnce(&Script<'_>, Option<&ScriptDeltaOwned>) -> R,

Available on crate feature stream only.

Parse with delta tracking for command system integration

Source

pub fn edit_event_with_builder<F>( &mut self, index: usize, builder_fn: F, ) -> Result<String>
where F: for<'a> FnOnce(EventBuilder<'_>) -> EventBuilder<'_>,

Edit event using a builder for structured modifications

Allows editing events using the EventBuilder fluent API. The builder is pre-populated with the current event’s values, allowing selective field updates.

§Arguments
  • index - Zero-based index of the event to edit
  • builder_fn - Function that receives a pre-populated EventBuilder
§Example
doc.edit_event_with_builder(0, |builder| {
    builder
        .text("New dialogue text")
        .style("NewStyle")
        .end_time("0:00:10.00")
})?;
Source

pub fn edit_event_text(&mut self, old_text: &str, new_text: &str) -> Result<()>

Edit an event by finding and replacing text (simplified ASS-aware editing)

Source

pub fn get_script_info_field(&self, key: &str) -> Result<Option<String>>

Get script info field value by key

Source

pub fn set_script_info_field(&mut self, key: &str, value: &str) -> Result<()>

Set script info field (ASS-aware editing)

Source

pub fn undo(&mut self) -> Result<CommandResult>

Perform an undo operation

Retrieves the most recent operation from the undo stack and reverses it. If the operation includes a script delta, it will be applied for efficient updates.

Source

pub fn redo(&mut self) -> Result<CommandResult>

Perform a redo operation

Retrieves the most recent operation from the redo stack and re-executes it. If the operation includes a script delta, it will be applied for efficient updates.

Source

pub fn can_undo(&self) -> bool

Check if undo is available

Source

pub fn can_redo(&self) -> bool

Check if redo is available

Source

pub fn next_undo_description(&self) -> Option<&str>

Get description of the next undo operation

Source

pub fn next_redo_description(&self) -> Option<&str>

Get description of the next redo operation

Source

pub fn undo_manager_mut(&mut self) -> &mut UndoManager

Get mutable reference to the undo manager for configuration

Source

pub fn undo_manager(&self) -> &UndoManager

Get reference to the undo manager

Source

pub fn apply_script_delta(&mut self, delta: ScriptDeltaOwned) -> Result<()>

Available on crate feature stream only.

Apply a script delta and record it with undo data

Source§

impl EditorDocument

Source

pub fn at(&mut self, pos: Position) -> DocumentPosition<'_>

Get fluent API for position-based operations

Source

pub fn initialize_registry(&mut self) -> Result<()>

Available on crate feature plugins only.

Initialize the extension registry with built-in handlers

Source

pub fn registry(&self) -> Option<&ExtensionRegistry>

Available on crate feature plugins only.

Get the extension registry for use in parsing

Source

pub fn parse_with_extensions<F, R>(&self, f: F) -> Result<R>
where F: FnOnce(&Script<'_>) -> R,

Available on crate feature plugins only.

Parse the document content with extension support and process it with a callback

Since Script<’a> requires the source text to outlive it, this method uses a callback pattern to process the script while the content is still in scope.

Source

pub fn register_tag_handler( &mut self, extension_name: String, handler: Box<dyn TagHandler>, ) -> Result<()>

Available on crate feature plugins only.

Register a custom tag handler

Source

pub fn register_section_processor( &mut self, extension_name: String, processor: Box<dyn SectionProcessor>, ) -> Result<()>

Available on crate feature plugins only.

Register a custom section processor

Source§

impl EditorDocument

Extension trait to add fluent API to EditorDocument

Source

pub fn at_pos(&mut self, position: Position) -> AtPosition<'_>

Start a fluent operation at a position

Source

pub fn at_line(&mut self, line: usize) -> Result<AtPosition<'_>>

Available on crate feature rope only.

Start a fluent operation at a line

Source

pub fn at_start(&mut self) -> AtPosition<'_>

Start a fluent operation at the start of the document

Source

pub fn at_end(&mut self) -> AtPosition<'_>

Start a fluent operation at the end of the document

Source

pub fn select(&mut self, range: Range) -> SelectRange<'_>

Start a fluent operation on a range

Source

pub fn styles(&mut self) -> StyleOps<'_>

Start fluent style operations

Source

pub fn events(&mut self) -> EventOps<'_>

Start fluent event operations

Source

pub fn tags(&mut self) -> TagOps<'_>

Start fluent tag operations

Source

pub fn karaoke(&mut self) -> KaraokeOps<'_>

Start fluent karaoke operations

Source

pub fn position_to_line_col(&self, pos: Position) -> Result<(usize, usize)>

Available on crate feature rope only.

Convert a Position to line/column tuple

Source

pub fn line_column_to_position( &self, line: usize, column: usize, ) -> Result<Position>

Available on crate feature rope only.

Convert line/column to Position

Trait Implementations§

Source§

impl Debug for EditorDocument

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for EditorDocument

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl DocumentCommandExt for EditorDocument

Source§

fn command(&mut self) -> TextCommand<'_>

Start a fluent command chain
Source§

fn insert_at(&mut self, position: Position, text: &str) -> Result<CommandResult>

Quick insert at position
Source§

fn delete_range(&mut self, range: Range) -> Result<CommandResult>

Quick delete range
Source§

fn replace_range(&mut self, range: Range, text: &str) -> Result<CommandResult>

Quick replace range

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.