Skip to main content

EditorStateManager

Struct EditorStateManager 

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

Editor state manager

EditorStateManager wraps the command executor (CommandExecutor) and its internal EditorCore and provides the following features:

  • State Queries: Retrieve various state snapshots (document, cursor, viewport, etc.)
  • Version Tracking: Automatically increment version number after each modification, supporting incremental updates
  • Change Notifications: Notify subscribers of state changes via callback mechanism
  • Viewport Management: Manage scroll position and visible regions
  • Modification Tracking: Track whether the document has been modified (for save prompts)

§Architecture Notes

The state manager adopts a “unidirectional data flow” pattern:

  1. Frontends execute edits, cursor movement, viewport changes, and other user actions via execute() or CommandExecutor.
  2. Derived state such as diagnostics, styles, decorations, symbols, and folds is replaced via explicit manager or Workspace methods so notifications stay in sync.
  3. editor_mut() is reserved for advanced access to EditorCore public methods; EditorCore fields remain private and cannot be mutated directly.
  4. Manager increments version number and triggers all subscribed callbacks.
  5. Frontends retrieve the latest state via various get_*_state() methods.

§Example

use editor_core::{Command, EditCommand, EditorStateManager};

let mut manager = EditorStateManager::new("Initial text", 80);

// Subscribe to state changes
manager.subscribe(|change| {
    println!("Version {} -> {}: {:?}",
        change.old_version, change.new_version, change.change_type);
});

// Modify document (automatically maintains consistency + automatically triggers state notifications)
manager.execute(Command::Edit(EditCommand::Insert {
    offset: 0,
    text: "New: ".to_string(),
})).unwrap();

// Query state
let doc_state = manager.get_document_state();
assert!(doc_state.is_modified);
assert_eq!(doc_state.version, 1);

Implementations§

Source§

impl EditorStateManager

Source

pub fn new(text: &str, viewport_width: usize) -> Self

Create a new state manager

Source

pub fn empty(viewport_width: usize) -> Self

Create an empty state manager

Source

pub fn editor(&self) -> &EditorCore

Get a reference to the Editor Core

Source

pub fn editor_mut(&mut self) -> &mut EditorCore

Get a mutable reference to the field-private Editor Core.

Prefer execute and the explicit derived-state methods on this manager for observable mutations. This accessor is intended for advanced callers that need to invoke public EditorCore methods directly; it does not expose private storage, layout, folding, style, or cursor fields.

Source

pub fn line_ending(&self) -> LineEnding

Get the preferred line ending for saving this document.

Source

pub fn set_line_ending(&mut self, line_ending: LineEnding)

Override the preferred line ending for saving this document.

Source

pub fn has_active_snippet_session(&self) -> bool

Return true if this editor currently has an active snippet session.

Source

pub fn get_text_for_saving(&self) -> String

Get the current document text converted to the preferred line ending for saving.

Source

pub fn execute( &mut self, command: Command, ) -> Result<CommandResult, CommandError>

Execute a command and automatically trigger state change notifications.

  • This method calls the underlying CommandExecutor to ensure consistency of components such as the text buffer, line index, and layout engine.
  • For commands that cause state changes, mark_modified is automatically called.
  • For pure query commands (such as GetViewport), the version number is not incremented.
Source

pub fn version(&self) -> u64

Get current version number

Source

pub fn set_viewport_height(&mut self, height: usize)

Set viewport height

Source

pub fn set_scroll_top(&mut self, scroll_top: usize)

Set scroll position

Source

pub fn set_scroll_sub_row_offset(&mut self, sub_row_offset: u16)

Set sub-row smooth-scroll offset (normalized 0..=65535).

Source

pub fn set_overscan_rows(&mut self, overscan_rows: usize)

Set overscan rows for viewport prefetch range.

Source

pub fn set_smooth_scroll_state(&mut self, state: SmoothScrollState)

Set full smooth-scroll state.

Source

pub fn get_smooth_scroll_state(&self) -> SmoothScrollState

Get smooth-scroll state.

Source

pub fn get_full_state(&self) -> EditorState

Get complete editor state snapshot

Source

pub fn get_document_state(&self) -> DocumentState

Get document state

Source

pub fn get_cursor_state(&self) -> CursorState

Get cursor state

Source

pub fn get_viewport_state(&self) -> ViewportState

Get viewport state

Source

pub fn get_undo_redo_state(&self) -> UndoRedoState

Get undo/redo state

Source

pub fn get_folding_state(&self) -> FoldingState

Get folding state

Source

pub fn get_style_state(&self) -> StyleState

Get style state

Source

pub fn get_diagnostics_state(&self) -> DiagnosticsState

Get diagnostics state.

Source

pub fn get_decorations_state(&self) -> DecorationsState

Get decorations state.

Source

pub fn get_styles_in_range( &self, start: usize, end: usize, ) -> Vec<(usize, usize, StyleId)>

Get all styles within the specified range

Source

pub fn get_styles_at(&self, offset: usize) -> Vec<StyleId>

Get all styles at the specified position

Source

pub fn replace_style_layer( &mut self, layer: StyleLayerId, intervals: Vec<Interval>, )

Replace all intervals in the specified style layer.

Suitable for scenarios such as LSP semantic highlighting and simple syntax highlighting that require “full layer refresh”. This method only triggers StyleChanged once, avoiding version number explosion due to individual insertions.

Source

pub fn clear_style_layer(&mut self, layer: StyleLayerId)

Clear the specified style layer.

Source

pub fn replace_diagnostics(&mut self, diagnostics: Vec<Diagnostic>)

Replace diagnostics wholesale.

Source

pub fn clear_diagnostics(&mut self)

Clear all diagnostics.

Source

pub fn replace_document_symbols(&mut self, symbols: DocumentOutline)

Replace document symbols / outline wholesale.

Source

pub fn clear_document_symbols(&mut self)

Clear document symbols / outline.

Source

pub fn replace_decorations( &mut self, layer: DecorationLayerId, decorations: Vec<Decoration>, )

Replace a decoration layer wholesale.

Source

pub fn clear_decorations(&mut self, layer: DecorationLayerId)

Clear a decoration layer.

Source

pub fn replace_folding_regions( &mut self, regions: Vec<FoldRegion>, preserve_collapsed: bool, )

Replace folding regions wholesale.

If preserve_collapsed is true, matching existing collapsed derived regions stay collapsed after replacement, including conservative matches across small line-number drift.

Source

pub fn clear_folding_regions(&mut self)

Clear all derived folding regions (leaves user folds intact).

Source

pub fn toggle_fold_at_current_line(&mut self) -> bool

Toggle the fold region that starts on the current cursor line.

Source

pub fn expand_all_folds(&mut self)

Expand all folding regions.

Source

pub fn apply_processing_edits<I>(&mut self, edits: I)
where I: IntoIterator<Item = ProcessingEdit>,

Apply derived-state edits produced by a document processor (highlighting, folding, etc.).

Source

pub fn apply_processor<P>(&mut self, processor: &mut P) -> Result<(), P::Error>

Run a DocumentProcessor against the current document and apply its edits.

Source

pub fn get_viewport_content( &self, start_row: usize, count: usize, ) -> HeadlessGrid

Get viewport content

Source

pub fn get_viewport_content_styled( &self, start_visual_row: usize, count: usize, ) -> HeadlessGrid

Get styled viewport content (by visual line).

  • Supports soft wrapping (based on LayoutEngine)
  • Cell.styles will contain the merged result of interval_tree and all style_layers
Source

pub fn get_minimap_content( &self, start_visual_row: usize, count: usize, ) -> MinimapGrid

Get lightweight minimap content (by visual line).

Source

pub fn get_viewport_content_composed( &self, start_visual_row: usize, count: usize, ) -> ComposedGrid

Get a decoration-aware composed viewport snapshot (by composed visual line).

See EditorCore::get_headless_grid_composed for detailed semantics and caveats.

Source

pub fn total_visual_lines(&self) -> usize

Get total visual line count under current wrap/folding state.

Source

pub fn visual_to_logical_line(&self, visual_row: usize) -> (usize, usize)

Map global visual row to (logical_line, visual_in_logical).

Source

pub fn logical_position_to_visual( &self, line: usize, column: usize, ) -> Option<(usize, usize)>

Map logical position to visual (row, x_cells).

Source

pub fn visual_position_to_logical( &self, visual_row: usize, x_cells: usize, ) -> Option<Position>

Map visual (row, x_cells) back to logical position.

Source

pub fn subscribe<F>(&mut self, callback: F)
where F: FnMut(&StateChange) + Send + 'static,

Subscribe to state change notifications

Source

pub fn has_changed_since(&self, version: u64) -> bool

Check if state has changed since a version

Source

pub fn mark_modified(&mut self, change_type: StateChangeType)

Mark document as modified and increment version number

Source

pub fn mark_saved(&mut self)

Mark document as unmodified (e.g., after saving)

Source

pub fn undo_history_snapshot(&self) -> UndoHistorySnapshot

Capture a persistable snapshot of the undo/redo history for this document.

Source

pub fn restore_undo_history( &mut self, snapshot: UndoHistorySnapshot, ) -> Result<(), UndoHistoryRestoreError>

Restore a previously captured UndoHistorySnapshot.

Notes:

  • This does not modify the current document text.
  • Callers should only restore a snapshot into the same text it was captured from.
Source

pub fn last_text_delta(&self) -> Option<&TextDelta>

Get the structured text delta produced by the last document edit, if any.

Source

pub fn take_last_text_delta(&mut self) -> Option<Arc<TextDelta>>

Take the structured text delta produced by the last document edit, if any.

Source

pub fn toggle_bookmark_at_cursor_line(&mut self) -> bool

Toggle a bookmark at the current cursor line.

Returns true if a bookmark was added, or false if an existing bookmark on that line was removed.

Source

pub fn bookmark_lines(&self) -> Vec<usize>

Return all bookmark line numbers (0-based).

Source

pub fn clear_bookmarks(&mut self)

Clear all bookmarks.

Source

pub fn goto_next_bookmark(&mut self) -> Result<Option<Position>, CommandError>

Move the cursor to the next bookmark (wrapping to the first bookmark).

Returns the new cursor position, or None if there are no bookmarks.

Source

pub fn goto_prev_bookmark(&mut self) -> Result<Option<Position>, CommandError>

Move the cursor to the previous bookmark (wrapping to the last bookmark).

Returns the new cursor position, or None if there are no bookmarks.

Source

pub fn set_mark_at_cursor(&mut self, name: String) -> Result<(), CommandError>

Set (or replace) a named mark at the current cursor position.

Source

pub fn goto_mark( &mut self, name: &str, ) -> Result<Option<Position>, CommandError>

Move the cursor to a named mark (if present).

Returns the new cursor position, or None if the mark does not exist.

Source

pub fn clear_mark(&mut self, name: &str) -> bool

Remove a named mark.

Returns true if the mark existed.

Source

pub fn mark_names(&self) -> Vec<String>

Return all mark names (deterministic order).

Source

pub fn clear_all_marks(&mut self)

Clear all marks.

Source

pub fn push_jump_location(&mut self)

Record the current cursor position as a jump-list location.

Typical usage: call this before performing a “jump” (go-to-definition, search result, symbol navigation, …).

Source

pub fn jump_back(&mut self) -> Result<Option<Position>, CommandError>

Jump back in the jump list.

Returns the new cursor position, or None if there is no back entry.

Source

pub fn jump_forward(&mut self) -> Result<Option<Position>, CommandError>

Jump forward in the jump list.

Returns the new cursor position, or None if there is no forward entry.

Source

pub fn clear_jump_list(&mut self)

Clear the jump list (both back/forward stacks).

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.