Skip to main content

editor_core/
state.rs

1//! Editor State Interface
2//!
3//! Provides a complete state query interface for the editor, used for frontend rendering and state synchronization.
4//!
5//! # Overview
6//!
7//! The state interface layer exposes the editor's internal state to the frontend in a structured, immutable manner.
8//! It supports:
9//!
10//! - **State Queries**: Retrieve document, cursor, viewport, and other state information
11//! - **Version Tracking**: Track state changes through version numbers
12//! - **Change Notifications**: Subscribe to state change events
13//! - **Viewport Management**: Obtain rendering data for visible regions
14//!
15//! # Example
16//!
17//! ```rust
18//! use editor_core::{Command, EditCommand, EditorStateManager};
19//!
20//! let mut manager = EditorStateManager::new("Hello, World!", 80);
21//!
22//! // Query document state
23//! let doc_state = manager.get_document_state();
24//! println!("Line count: {}", doc_state.line_count);
25//!
26//! // Subscribe to state changes
27//! manager.subscribe(|change| {
28//!     println!("State changed: {:?}", change.change_type);
29//! });
30//!
31//! // Modify document through the command path so text, layout, and derived state stay in sync.
32//! manager.execute(Command::Edit(EditCommand::Insert {
33//!     offset: 0,
34//!     text: "New: ".to_string(),
35//! })).unwrap();
36//! ```
37
38use crate::delta::TextDelta;
39use crate::intervals::{FoldRegion, Interval, StyleId, StyleLayerId};
40use crate::processing::{DocumentProcessor, ProcessingEdit};
41use crate::snapshot::{ComposedGrid, HeadlessGrid};
42use crate::{
43    AnchorBias, Command, CommandError, CommandExecutor, CommandResult, CursorCommand, Decoration,
44    DecorationLayerId, Diagnostic, EditCommand, EditorCore, LineEnding, Position, Selection,
45    SelectionDirection, StyleCommand, TextAnchor, UndoHistoryRestoreError, UndoHistorySnapshot,
46    ViewCommand,
47};
48use std::collections::BTreeMap;
49use std::ops::Range;
50use std::sync::Arc;
51
52/// Document state
53#[derive(Debug, Clone)]
54pub struct DocumentState {
55    /// Total documentLine count
56    pub line_count: usize,
57    /// Total document character count
58    pub char_count: usize,
59    /// Total document byte count
60    pub byte_count: usize,
61    /// Whether document has been modified
62    pub is_modified: bool,
63    /// Document version number (incremented after each modification)
64    pub version: u64,
65}
66
67/// Cursor state
68#[derive(Debug, Clone)]
69pub struct CursorState {
70    /// Primary cursor position (logical coordinates)
71    pub position: Position,
72    /// Primary cursor position (char offsets)
73    pub offset: usize,
74    /// Multi-cursor list (active positions of secondary carets, excluding primary)
75    pub multi_cursors: Vec<Position>,
76    /// Primary selection range (only primary; returns None for empty selection)
77    pub selection: Option<Selection>,
78    /// All selection set (including primary; each Selection may be empty)
79    pub selections: Vec<Selection>,
80    /// Index of primary in `selections`
81    pub primary_selection_index: usize,
82}
83
84/// Viewport state
85#[derive(Debug, Clone)]
86pub struct ViewportState {
87    /// Viewport width (in character cells)
88    pub width: usize,
89    /// Viewport height (line count, determined by the frontend)
90    pub height: Option<usize>,
91    /// Current scroll position (visual line number)
92    pub scroll_top: usize,
93    /// Sub-row smooth-scroll offset (0..=65535, normalized).
94    pub sub_row_offset: u16,
95    /// Overscan rows used to compute `prefetch_lines`.
96    pub overscan_rows: usize,
97    /// Visible visual line range
98    pub visible_lines: Range<usize>,
99    /// Recommended prefetch range (visible range expanded by `overscan_rows`).
100    pub prefetch_lines: Range<usize>,
101    /// Total visual lines under current wrap/folding state.
102    pub total_visual_lines: usize,
103}
104
105/// Smooth-scrolling state for single-view manager.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct SmoothScrollState {
108    /// Top visual row anchor.
109    pub top_visual_row: usize,
110    /// Sub-row offset within top row (0..=65535, normalized).
111    pub sub_row_offset: u16,
112    /// Overscan rows for prefetching.
113    pub overscan_rows: usize,
114}
115
116/// Undo/redo stack state
117#[derive(Debug, Clone)]
118pub struct UndoRedoState {
119    /// Can undo
120    pub can_undo: bool,
121    /// Can redo
122    pub can_redo: bool,
123    /// Undo stack depth
124    pub undo_depth: usize,
125    /// Redo stack depth
126    pub redo_depth: usize,
127    /// Number of redo branches available at the current history node.
128    pub redo_branch_count: usize,
129    /// Currently selected redo branch index, if any.
130    pub selected_redo_branch_index: Option<usize>,
131    /// Current change group ID
132    pub current_change_group: Option<usize>,
133}
134
135/// Folding state
136#[derive(Debug, Clone)]
137pub struct FoldingState {
138    /// All folding regions
139    pub regions: Vec<FoldRegion>,
140    /// Count of collapsed lines
141    pub collapsed_line_count: usize,
142    /// Count of visible logical lines
143    pub visible_logical_lines: usize,
144    /// Total visual line count (considering folding)
145    pub total_visual_lines: usize,
146}
147
148/// Diagnostics state
149#[derive(Debug, Clone)]
150pub struct DiagnosticsState {
151    /// Total number of diagnostics.
152    pub diagnostics_count: usize,
153}
154
155/// Decorations state
156#[derive(Debug, Clone)]
157pub struct DecorationsState {
158    /// Total number of decoration layers.
159    pub layer_count: usize,
160    /// Total number of decorations (across all layers).
161    pub decoration_count: usize,
162}
163
164/// Style state
165#[derive(Debug, Clone)]
166pub struct StyleState {
167    /// Total number of style intervals
168    pub style_count: usize,
169}
170
171/// State change type
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum StateChangeType {
174    /// Document content modified
175    DocumentModified,
176    /// Cursor moved
177    CursorMoved,
178    /// Selection changed
179    SelectionChanged,
180    /// Navigation / anchor state changed (bookmarks, marks, jump list, ...).
181    NavigationChanged,
182    /// Viewport changed
183    ViewportChanged,
184    /// Folding state changed
185    FoldingChanged,
186    /// Style changed
187    StyleChanged,
188    /// Decorations changed
189    DecorationsChanged,
190    /// Diagnostics changed
191    DiagnosticsChanged,
192    /// Document symbols / outline changed
193    SymbolsChanged,
194}
195
196/// State change record
197#[derive(Debug, Clone)]
198pub struct StateChange {
199    /// Change type
200    pub change_type: StateChangeType,
201    /// Old version number
202    pub old_version: u64,
203    /// New version number
204    pub new_version: u64,
205    /// Affected region (character offset range)
206    pub affected_region: Option<Range<usize>>,
207    /// Structured text delta for document changes (if available).
208    pub text_delta: Option<Arc<TextDelta>>,
209}
210
211impl StateChange {
212    /// Create a new state change record without an affected region.
213    pub fn new(change_type: StateChangeType, old_version: u64, new_version: u64) -> Self {
214        Self {
215            change_type,
216            old_version,
217            new_version,
218            affected_region: None,
219            text_delta: None,
220        }
221    }
222
223    /// Attach the affected character range to this change record.
224    pub fn with_region(mut self, region: Range<usize>) -> Self {
225        self.affected_region = Some(region);
226        self
227    }
228
229    /// Attach a structured text delta to this change record.
230    pub fn with_text_delta(mut self, delta: Arc<TextDelta>) -> Self {
231        self.text_delta = Some(delta);
232        self
233    }
234}
235
236/// Complete editor state snapshot
237#[derive(Debug, Clone)]
238pub struct EditorState {
239    /// Document state
240    pub document: DocumentState,
241    /// Cursor state
242    pub cursor: CursorState,
243    /// Viewport state
244    pub viewport: ViewportState,
245    /// Undo/redo state
246    pub undo_redo: UndoRedoState,
247    /// Folding state
248    pub folding: FoldingState,
249    /// Diagnostics state
250    pub diagnostics: DiagnosticsState,
251    /// Decorations state
252    pub decorations: DecorationsState,
253    /// Style state
254    pub style: StyleState,
255}
256
257/// State change callback function type
258pub type StateChangeCallback = Box<dyn FnMut(&StateChange) + Send>;
259
260#[derive(Debug, Default, Clone, PartialEq, Eq)]
261struct BookmarkSet {
262    anchors: Vec<TextAnchor>,
263}
264
265impl BookmarkSet {
266    fn toggle_line_start(&mut self, line_start_offset: usize) -> bool {
267        let anchor = TextAnchor::new(line_start_offset, AnchorBias::Left);
268        match self
269            .anchors
270            .binary_search_by_key(&anchor.offset, |a| a.offset)
271        {
272            Ok(idx) => {
273                self.anchors.remove(idx);
274                false
275            }
276            Err(idx) => {
277                self.anchors.insert(idx, anchor);
278                true
279            }
280        }
281    }
282
283    fn clear(&mut self) {
284        self.anchors.clear();
285    }
286
287    fn apply_delta(&mut self, delta: &TextDelta) {
288        for a in &mut self.anchors {
289            a.apply_delta(delta);
290        }
291        self.anchors.sort_by_key(|a| a.offset);
292        self.anchors.dedup_by_key(|a| a.offset);
293    }
294
295    fn line_numbers(&self, line_index: &crate::LineIndex) -> Vec<usize> {
296        let mut lines: Vec<usize> = self
297            .anchors
298            .iter()
299            .map(|a| line_index.char_offset_to_position(a.offset).0)
300            .collect();
301        lines.sort_unstable();
302        lines.dedup();
303        lines
304    }
305
306    fn next_after_line_start(&self, current_line_start: usize) -> Option<TextAnchor> {
307        self.anchors
308            .iter()
309            .copied()
310            .find(|a| a.offset > current_line_start)
311            .or_else(|| self.anchors.first().copied())
312    }
313
314    fn prev_before_line_start(&self, current_line_start: usize) -> Option<TextAnchor> {
315        self.anchors
316            .iter()
317            .copied()
318            .rfind(|a| a.offset < current_line_start)
319            .or_else(|| self.anchors.last().copied())
320    }
321}
322
323#[derive(Debug, Default, Clone, PartialEq, Eq)]
324struct MarkSet {
325    marks: BTreeMap<String, TextAnchor>,
326}
327
328impl MarkSet {
329    fn set(&mut self, name: String, offset: usize) {
330        self.marks
331            .insert(name, TextAnchor::new(offset, AnchorBias::Right));
332    }
333
334    fn get(&self, name: &str) -> Option<TextAnchor> {
335        self.marks.get(name).copied()
336    }
337
338    fn remove(&mut self, name: &str) -> bool {
339        self.marks.remove(name).is_some()
340    }
341
342    fn clear(&mut self) {
343        self.marks.clear();
344    }
345
346    fn names(&self) -> Vec<String> {
347        self.marks.keys().cloned().collect()
348    }
349
350    fn apply_delta(&mut self, delta: &TextDelta) {
351        for anchor in self.marks.values_mut() {
352            anchor.apply_delta(delta);
353        }
354    }
355}
356
357#[derive(Debug, Default, Clone, PartialEq, Eq)]
358struct JumpList {
359    back: Vec<TextAnchor>,
360    forward: Vec<TextAnchor>,
361    max_len: usize,
362}
363
364impl JumpList {
365    fn new(max_len: usize) -> Self {
366        Self {
367            back: Vec::new(),
368            forward: Vec::new(),
369            max_len: max_len.max(1),
370        }
371    }
372
373    fn record(&mut self, offset: usize) {
374        let anchor = TextAnchor::new(offset, AnchorBias::Right);
375        if self.back.last().is_some_and(|last| *last == anchor) {
376            return;
377        }
378
379        self.back.push(anchor);
380        self.forward.clear();
381
382        if self.back.len() > self.max_len {
383            let overflow = self.back.len() - self.max_len;
384            self.back.drain(0..overflow);
385        }
386    }
387
388    fn back(&mut self, current_offset: usize) -> Option<TextAnchor> {
389        let current = TextAnchor::new(current_offset, AnchorBias::Right);
390        let target = self.back.pop()?;
391        if !self.forward.last().is_some_and(|last| *last == current) {
392            self.forward.push(current);
393        }
394        Some(target)
395    }
396
397    fn forward(&mut self, current_offset: usize) -> Option<TextAnchor> {
398        let current = TextAnchor::new(current_offset, AnchorBias::Right);
399        let target = self.forward.pop()?;
400        if !self.back.last().is_some_and(|last| *last == current) {
401            self.back.push(current);
402        }
403        Some(target)
404    }
405
406    fn clear(&mut self) {
407        self.back.clear();
408        self.forward.clear();
409    }
410
411    fn apply_delta(&mut self, delta: &TextDelta) {
412        for a in self.back.iter_mut().chain(self.forward.iter_mut()) {
413            a.apply_delta(delta);
414        }
415    }
416}
417
418/// Classifies a view command for change detection: a bare `SetViewportWidth` can be a no-op
419/// (width unchanged), whereas other view-config commands mutate state unconditionally.
420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421enum ViewChangeKind {
422    ViewportWidthOnly,
423    Other,
424}
425
426/// Editor state manager
427///
428/// `EditorStateManager` wraps the command executor ([`CommandExecutor`]) and its internal [`EditorCore`]
429/// and provides the following features:
430///
431/// - **State Queries**: Retrieve various state snapshots (document, cursor, viewport, etc.)
432/// - **Version Tracking**: Automatically increment version number after each modification, supporting incremental updates
433/// - **Change Notifications**: Notify subscribers of state changes via callback mechanism
434/// - **Viewport Management**: Manage scroll position and visible regions
435/// - **Modification Tracking**: Track whether the document has been modified (for save prompts)
436///
437/// # Architecture Notes
438///
439/// The state manager adopts a "unidirectional data flow" pattern:
440///
441/// 1. Frontends execute edits, cursor movement, viewport changes, and other user actions via
442///    [`execute()`](EditorStateManager::execute) or [`CommandExecutor`].
443/// 2. Derived state such as diagnostics, styles, decorations, symbols, and folds is replaced via
444///    explicit manager or [`Workspace`](crate::Workspace) methods so notifications stay in sync.
445/// 3. [`editor_mut()`](EditorStateManager::editor_mut) is reserved for advanced access to
446///    `EditorCore` public methods; `EditorCore` fields remain private and cannot be mutated
447///    directly.
448/// 4. Manager increments version number and triggers all subscribed callbacks.
449/// 5. Frontends retrieve the latest state via various `get_*_state()` methods.
450///
451/// # Example
452///
453/// ```rust
454/// use editor_core::{Command, EditCommand, EditorStateManager};
455///
456/// let mut manager = EditorStateManager::new("Initial text", 80);
457///
458/// // Subscribe to state changes
459/// manager.subscribe(|change| {
460///     println!("Version {} -> {}: {:?}",
461///         change.old_version, change.new_version, change.change_type);
462/// });
463///
464/// // Modify document (automatically maintains consistency + automatically triggers state notifications)
465/// manager.execute(Command::Edit(EditCommand::Insert {
466///     offset: 0,
467///     text: "New: ".to_string(),
468/// })).unwrap();
469///
470/// // Query state
471/// let doc_state = manager.get_document_state();
472/// assert!(doc_state.is_modified);
473/// assert_eq!(doc_state.version, 1);
474/// ```
475pub struct EditorStateManager {
476    /// Command executor (wraps EditorCore and maintains consistency)
477    executor: CommandExecutor,
478    /// State version number
479    state_version: u64,
480    /// Whether document has been modified
481    is_modified: bool,
482    /// State change callback list
483    callbacks: Vec<StateChangeCallback>,
484    /// Current scroll position
485    scroll_top: usize,
486    /// Sub-row smooth-scroll offset.
487    scroll_sub_row_offset: u16,
488    /// Overscan rows for prefetching.
489    overscan_rows: usize,
490    /// Viewport height (optional)
491    viewport_height: Option<usize>,
492    /// Structured text delta produced by the last document edit.
493    last_text_delta: Option<Arc<TextDelta>>,
494    bookmarks: BookmarkSet,
495    marks: MarkSet,
496    jump_list: JumpList,
497}
498
499impl EditorStateManager {
500    /// Create a new state manager
501    pub fn new(text: &str, viewport_width: usize) -> Self {
502        Self {
503            executor: CommandExecutor::new(text, viewport_width),
504            state_version: 0,
505            is_modified: false,
506            callbacks: Vec::new(),
507            scroll_top: 0,
508            scroll_sub_row_offset: 0,
509            overscan_rows: 0,
510            viewport_height: None,
511            last_text_delta: None,
512            bookmarks: BookmarkSet::default(),
513            marks: MarkSet::default(),
514            jump_list: JumpList::new(200),
515        }
516    }
517
518    /// Create an empty state manager
519    pub fn empty(viewport_width: usize) -> Self {
520        Self::new("", viewport_width)
521    }
522
523    /// Get a reference to the Editor Core
524    pub fn editor(&self) -> &EditorCore {
525        self.executor.editor()
526    }
527
528    /// Get a mutable reference to the field-private Editor Core.
529    ///
530    /// Prefer [`execute`](Self::execute) and the explicit derived-state methods on this manager for
531    /// observable mutations. This accessor is intended for advanced callers that need to invoke
532    /// public [`EditorCore`] methods directly; it does not expose private storage, layout, folding,
533    /// style, or cursor fields.
534    pub fn editor_mut(&mut self) -> &mut EditorCore {
535        self.executor.editor_mut()
536    }
537
538    /// Get the preferred line ending for saving this document.
539    pub fn line_ending(&self) -> LineEnding {
540        self.executor.line_ending()
541    }
542
543    /// Override the preferred line ending for saving this document.
544    pub fn set_line_ending(&mut self, line_ending: LineEnding) {
545        self.executor.set_line_ending(line_ending);
546    }
547
548    /// Return `true` if this editor currently has an active snippet session.
549    pub fn has_active_snippet_session(&self) -> bool {
550        self.executor.has_active_snippet_session()
551    }
552
553    /// Get the current document text converted to the preferred line ending for saving.
554    pub fn get_text_for_saving(&self) -> String {
555        let text = self.editor().get_text();
556        self.line_ending().apply_to_text(&text)
557    }
558
559    /// Execute a command and automatically trigger state change notifications.
560    ///
561    /// - This method calls the underlying [`CommandExecutor`] to ensure consistency of components
562    ///   such as the text buffer, line index, and layout engine.
563    /// - For commands that cause state changes, [`mark_modified`](Self::mark_modified) is automatically called.
564    /// - For pure query commands (such as `GetViewport`), the version number is not incremented.
565    pub fn execute(&mut self, command: Command) -> Result<CommandResult, CommandError> {
566        let change_type = Self::change_type_for_command(&command);
567        let is_delete_like = matches!(
568            &command,
569            Command::Edit(EditCommand::Backspace | EditCommand::DeleteForward)
570        );
571        // A bare `SetViewportWidth` may be a no-op (width unchanged); every other view command
572        // that classifies as `ViewportChanged` mutates config unconditionally.
573        let command_kind = if matches!(&command, Command::View(ViewCommand::SetViewportWidth { .. }))
574        {
575            ViewChangeKind::ViewportWidthOnly
576        } else {
577            ViewChangeKind::Other
578        };
579
580        // Detect changes for potential no-ops: when command execution succeeds but state doesn't change, version should not increment.
581        let cursor_before = self.executor.editor().cursor_position();
582        let selection_before = self.executor.editor().selection().cloned();
583        let secondary_before = self.executor.editor().secondary_selections().to_vec();
584        let viewport_width_before = self.executor.editor().viewport_width();
585        let char_count_before = self.executor.editor().char_count();
586
587        let result = self.executor.execute(command)?;
588        let char_count_after = self.executor.editor().char_count();
589        let delta_present = self.executor.last_text_delta().is_some();
590
591        if let Some(change_type) = change_type {
592            let changed = match change_type {
593                StateChangeType::CursorMoved => {
594                    self.executor.editor().cursor_position() != cursor_before
595                        || self.executor.editor().secondary_selections()
596                            != secondary_before.as_slice()
597                }
598                StateChangeType::SelectionChanged => {
599                    self.executor.editor().cursor_position() != cursor_before
600                        || self.executor.editor().selection().cloned() != selection_before
601                        || self.executor.editor().secondary_selections()
602                            != secondary_before.as_slice()
603                }
604                StateChangeType::ViewportChanged => {
605                    // View-config setters (tab-key behavior, indentation, auto-pairs, word
606                    // boundaries, wrap mode/indent, tab width) mutate view-local state
607                    // unconditionally; they are not observable through `viewport_width` alone.
608                    // Only a bare `SetViewportWidth` is a potential no-op we can cheaply detect.
609                    if matches!(command_kind, ViewChangeKind::ViewportWidthOnly) {
610                        self.executor.editor().viewport_width() != viewport_width_before
611                    } else {
612                        true
613                    }
614                }
615                StateChangeType::DocumentModified => {
616                    // EditCommand::Backspace / DeleteForward can be valid no-ops at boundaries.
617                    // Detect via char count change (they only delete text).
618                    if is_delete_like {
619                        char_count_after != char_count_before
620                    } else {
621                        delta_present
622                    }
623                }
624                StateChangeType::NavigationChanged => true,
625                // Style/folding/diagnostics commands are currently treated as "success means change".
626                StateChangeType::FoldingChanged
627                | StateChangeType::StyleChanged
628                | StateChangeType::DecorationsChanged
629                | StateChangeType::DiagnosticsChanged
630                | StateChangeType::SymbolsChanged => true,
631            };
632
633            if changed {
634                if matches!(change_type, StateChangeType::DocumentModified) {
635                    let is_modified = !self.executor.is_clean();
636                    let delta = self.executor.take_last_text_delta().map(Arc::new);
637                    if let Some(ref delta) = delta {
638                        self.bookmarks.apply_delta(delta);
639                        self.marks.apply_delta(delta);
640                        self.jump_list.apply_delta(delta);
641                    }
642                    self.last_text_delta = delta.clone();
643                    self.mark_modified_internal(change_type, Some(is_modified), delta);
644                } else {
645                    self.mark_modified_internal(change_type, None, None);
646                }
647            }
648        }
649
650        Ok(result)
651    }
652
653    fn change_type_for_command(command: &Command) -> Option<StateChangeType> {
654        match command {
655            Command::Edit(EditCommand::Delete { length: 0, .. }) => None,
656            Command::Edit(EditCommand::Replace {
657                length: 0, text, ..
658            }) if text.is_empty() => None,
659            Command::Edit(EditCommand::EndUndoGroup) => None,
660            Command::Edit(_) => Some(StateChangeType::DocumentModified),
661            Command::Cursor(
662                CursorCommand::MoveTo { .. }
663                | CursorCommand::MoveBy { .. }
664                | CursorCommand::MoveVisualBy { .. }
665                | CursorCommand::MoveToVisual { .. }
666                | CursorCommand::MoveToLineStart
667                | CursorCommand::MoveToLineEnd
668                | CursorCommand::MoveToVisualLineStart
669                | CursorCommand::MoveToVisualLineEnd
670                | CursorCommand::MoveGraphemeLeft
671                | CursorCommand::MoveGraphemeRight
672                | CursorCommand::MoveWordLeft
673                | CursorCommand::MoveWordRight
674                | CursorCommand::MoveToMatchingBracket,
675            ) => Some(StateChangeType::CursorMoved),
676            Command::Cursor(
677                CursorCommand::SetSelection { .. }
678                | CursorCommand::ExtendSelection { .. }
679                | CursorCommand::ClearSelection
680                | CursorCommand::SetSelections { .. }
681                | CursorCommand::ClearSecondarySelections
682                | CursorCommand::SetRectSelection { .. }
683                | CursorCommand::SelectLine
684                | CursorCommand::SelectWord
685                | CursorCommand::ExpandSelection
686                | CursorCommand::ExpandSelectionBy { .. }
687                | CursorCommand::SnippetNextPlaceholder
688                | CursorCommand::SnippetPrevPlaceholder
689                | CursorCommand::AddCursorAbove
690                | CursorCommand::AddCursorBelow
691                | CursorCommand::AddNextOccurrence { .. }
692                | CursorCommand::AddAllOccurrences { .. }
693                | CursorCommand::FindNext { .. }
694                | CursorCommand::FindPrev { .. },
695            ) => Some(StateChangeType::SelectionChanged),
696            // `ScrollTo` is transient viewport positioning and `GetViewport` is a pure query;
697            // neither is a persisted state mutation. Every other view command changes view-local
698            // config (wrap, tab, indentation, auto-pairs, word boundaries) and must notify
699            // subscribers, matching `ViewCommand::is_mutating` and the `Workspace` execute path.
700            Command::View(ViewCommand::ScrollTo { .. } | ViewCommand::GetViewport { .. }) => None,
701            Command::View(_) => Some(StateChangeType::ViewportChanged),
702            Command::Style(
703                StyleCommand::AddStyle { .. }
704                | StyleCommand::RemoveStyle { .. }
705                | StyleCommand::UpdateBracketMatchHighlights
706                | StyleCommand::ClearBracketMatchHighlights,
707            ) => Some(StateChangeType::StyleChanged),
708            Command::Style(
709                StyleCommand::Fold { .. } | StyleCommand::Unfold { .. } | StyleCommand::UnfoldAll,
710            ) => Some(StateChangeType::FoldingChanged),
711        }
712    }
713
714    /// Get current version number
715    pub fn version(&self) -> u64 {
716        self.state_version
717    }
718
719    /// Set viewport height
720    pub fn set_viewport_height(&mut self, height: usize) {
721        self.viewport_height = Some(height);
722    }
723
724    /// Set scroll position
725    pub fn set_scroll_top(&mut self, scroll_top: usize) {
726        let old_scroll = self.scroll_top;
727        self.scroll_top = scroll_top;
728
729        if old_scroll != scroll_top {
730            self.notify_change(StateChangeType::ViewportChanged);
731        }
732    }
733
734    /// Set sub-row smooth-scroll offset (normalized 0..=65535).
735    pub fn set_scroll_sub_row_offset(&mut self, sub_row_offset: u16) {
736        let old = self.scroll_sub_row_offset;
737        self.scroll_sub_row_offset = sub_row_offset;
738        if old != sub_row_offset {
739            self.notify_change(StateChangeType::ViewportChanged);
740        }
741    }
742
743    /// Set overscan rows for viewport prefetch range.
744    pub fn set_overscan_rows(&mut self, overscan_rows: usize) {
745        let old = self.overscan_rows;
746        self.overscan_rows = overscan_rows;
747        if old != overscan_rows {
748            self.notify_change(StateChangeType::ViewportChanged);
749        }
750    }
751
752    /// Set full smooth-scroll state.
753    pub fn set_smooth_scroll_state(&mut self, state: SmoothScrollState) {
754        let mut changed = false;
755        if self.scroll_top != state.top_visual_row {
756            self.scroll_top = state.top_visual_row;
757            changed = true;
758        }
759        if self.scroll_sub_row_offset != state.sub_row_offset {
760            self.scroll_sub_row_offset = state.sub_row_offset;
761            changed = true;
762        }
763        if self.overscan_rows != state.overscan_rows {
764            self.overscan_rows = state.overscan_rows;
765            changed = true;
766        }
767        if changed {
768            self.notify_change(StateChangeType::ViewportChanged);
769        }
770    }
771
772    /// Get smooth-scroll state.
773    pub fn get_smooth_scroll_state(&self) -> SmoothScrollState {
774        SmoothScrollState {
775            top_visual_row: self.scroll_top,
776            sub_row_offset: self.scroll_sub_row_offset,
777            overscan_rows: self.overscan_rows,
778        }
779    }
780
781    /// Get complete editor state snapshot
782    pub fn get_full_state(&self) -> EditorState {
783        EditorState {
784            document: self.get_document_state(),
785            cursor: self.get_cursor_state(),
786            viewport: self.get_viewport_state(),
787            undo_redo: self.get_undo_redo_state(),
788            folding: self.get_folding_state(),
789            diagnostics: self.get_diagnostics_state(),
790            decorations: self.get_decorations_state(),
791            style: self.get_style_state(),
792        }
793    }
794
795    /// Get document state
796    pub fn get_document_state(&self) -> DocumentState {
797        let editor = self.executor.editor();
798        DocumentState {
799            line_count: editor.line_count(),
800            char_count: editor.char_count(),
801            byte_count: editor.get_text().len(),
802            is_modified: self.is_modified,
803            version: self.state_version,
804        }
805    }
806
807    /// Get cursor state
808    pub fn get_cursor_state(&self) -> CursorState {
809        let editor = self.executor.editor();
810        let mut selections: Vec<Selection> =
811            Vec::with_capacity(1 + editor.secondary_selections().len());
812
813        let primary = editor.selection().cloned().unwrap_or(Selection {
814            start: editor.cursor_position(),
815            end: editor.cursor_position(),
816            direction: SelectionDirection::Forward,
817        });
818        selections.push(primary);
819        selections.extend(editor.secondary_selections().iter().cloned());
820
821        let (selections, primary_selection_index) =
822            crate::selection_set::normalize_selections(selections, 0);
823        let primary = selections
824            .get(primary_selection_index)
825            .cloned()
826            .unwrap_or(Selection {
827                start: editor.cursor_position(),
828                end: editor.cursor_position(),
829                direction: SelectionDirection::Forward,
830            });
831
832        let position = primary.end;
833        let offset = editor
834            .line_index()
835            .position_to_char_offset(position.line, position.column);
836
837        let selection = if primary.start == primary.end {
838            None
839        } else {
840            Some(primary)
841        };
842
843        let multi_cursors: Vec<Position> = selections
844            .iter()
845            .enumerate()
846            .filter_map(|(idx, sel)| {
847                if idx == primary_selection_index {
848                    None
849                } else {
850                    Some(sel.end)
851                }
852            })
853            .collect();
854
855        CursorState {
856            position,
857            offset,
858            multi_cursors,
859            selection,
860            selections,
861            primary_selection_index,
862        }
863    }
864
865    /// Get viewport state
866    pub fn get_viewport_state(&self) -> ViewportState {
867        let editor = self.executor.editor();
868        let total_visual_lines = editor.visual_line_count();
869        let clamped_top = self.scroll_top.min(total_visual_lines);
870        let visible_end = if let Some(height) = self.viewport_height {
871            clamped_top.saturating_add(height)
872        } else {
873            total_visual_lines
874        };
875        let visible_lines = clamped_top..visible_end.min(total_visual_lines);
876        let prefetch_start = visible_lines.start.saturating_sub(self.overscan_rows);
877        let prefetch_end = visible_lines
878            .end
879            .saturating_add(self.overscan_rows)
880            .min(total_visual_lines);
881
882        ViewportState {
883            width: editor.viewport_width(),
884            height: self.viewport_height,
885            scroll_top: clamped_top,
886            sub_row_offset: self.scroll_sub_row_offset,
887            overscan_rows: self.overscan_rows,
888            visible_lines,
889            prefetch_lines: prefetch_start..prefetch_end,
890            total_visual_lines,
891        }
892    }
893
894    /// Get undo/redo state
895    pub fn get_undo_redo_state(&self) -> UndoRedoState {
896        UndoRedoState {
897            can_undo: self.executor.can_undo(),
898            can_redo: self.executor.can_redo(),
899            undo_depth: self.executor.undo_depth(),
900            redo_depth: self.executor.redo_depth(),
901            redo_branch_count: self.executor.redo_branch_count(),
902            selected_redo_branch_index: self.executor.selected_redo_branch_index(),
903            current_change_group: self.executor.current_change_group(),
904        }
905    }
906
907    /// Get folding state
908    pub fn get_folding_state(&self) -> FoldingState {
909        let editor = self.executor.editor();
910        let regions = editor.folding_manager().regions().to_vec();
911        // Count hidden lines by union of collapsed ranges so nested/overlapping folds are not
912        // double-counted (which could otherwise underflow `line_count - collapsed_line_count`).
913        let collapsed_line_count = editor.folding_manager().collapsed_hidden_line_count();
914
915        let visible_logical_lines = editor.line_count().saturating_sub(collapsed_line_count);
916
917        FoldingState {
918            regions,
919            collapsed_line_count,
920            visible_logical_lines,
921            total_visual_lines: editor.visual_line_count(),
922        }
923    }
924
925    /// Get style state
926    pub fn get_style_state(&self) -> StyleState {
927        let editor = self.executor.editor();
928        let layered_count: usize = editor.style_layers().values().map(|t| t.len()).sum();
929        StyleState {
930            style_count: editor.interval_tree().len() + layered_count,
931        }
932    }
933
934    /// Get diagnostics state.
935    pub fn get_diagnostics_state(&self) -> DiagnosticsState {
936        let editor = self.executor.editor();
937        DiagnosticsState {
938            diagnostics_count: editor.diagnostics().len(),
939        }
940    }
941
942    /// Get decorations state.
943    pub fn get_decorations_state(&self) -> DecorationsState {
944        let editor = self.executor.editor();
945        let decoration_count: usize = editor.decorations().values().map(|d| d.len()).sum();
946        DecorationsState {
947            layer_count: editor.decorations().len(),
948            decoration_count,
949        }
950    }
951
952    /// Get all styles within the specified range
953    pub fn get_styles_in_range(&self, start: usize, end: usize) -> Vec<(usize, usize, StyleId)> {
954        let editor = self.executor.editor();
955        let mut result: Vec<(usize, usize, StyleId)> = editor
956            .interval_tree()
957            .query_range(start, end)
958            .iter()
959            .map(|interval| (interval.start, interval.end, interval.style_id))
960            .collect();
961
962        for tree in editor.style_layers().values() {
963            result.extend(
964                tree.query_range(start, end)
965                    .iter()
966                    .map(|interval| (interval.start, interval.end, interval.style_id)),
967            );
968        }
969
970        result.sort_unstable_by_key(|(s, e, id)| (*s, *e, *id));
971        result
972    }
973
974    /// Get all styles at the specified position
975    pub fn get_styles_at(&self, offset: usize) -> Vec<StyleId> {
976        let editor = self.executor.editor();
977        let mut styles: Vec<StyleId> = editor
978            .interval_tree()
979            .query_point(offset)
980            .iter()
981            .map(|interval| interval.style_id)
982            .collect();
983
984        for tree in editor.style_layers().values() {
985            styles.extend(
986                tree.query_point(offset)
987                    .iter()
988                    .map(|interval| interval.style_id),
989            );
990        }
991
992        styles.sort_unstable();
993        styles.dedup();
994        styles
995    }
996
997    /// Replace all intervals in the specified style layer.
998    ///
999    /// Suitable for scenarios such as LSP semantic highlighting and simple syntax highlighting that require "full layer refresh".
1000    /// This method only triggers `StyleChanged` once, avoiding version number explosion due to individual insertions.
1001    pub fn replace_style_layer(&mut self, layer: StyleLayerId, intervals: Vec<Interval>) {
1002        self.executor
1003            .editor_mut()
1004            .replace_style_layer(layer, intervals);
1005        self.mark_modified(StateChangeType::StyleChanged);
1006    }
1007
1008    /// Clear the specified style layer.
1009    pub fn clear_style_layer(&mut self, layer: StyleLayerId) {
1010        self.executor.editor_mut().clear_style_layer(layer);
1011        self.mark_modified(StateChangeType::StyleChanged);
1012    }
1013
1014    /// Replace diagnostics wholesale.
1015    pub fn replace_diagnostics(&mut self, diagnostics: Vec<Diagnostic>) {
1016        self.executor.editor_mut().replace_diagnostics(diagnostics);
1017        self.mark_modified(StateChangeType::DiagnosticsChanged);
1018    }
1019
1020    /// Clear all diagnostics.
1021    pub fn clear_diagnostics(&mut self) {
1022        self.executor.editor_mut().clear_diagnostics();
1023        self.mark_modified(StateChangeType::DiagnosticsChanged);
1024    }
1025
1026    /// Replace document symbols / outline wholesale.
1027    pub fn replace_document_symbols(&mut self, symbols: crate::DocumentOutline) {
1028        self.executor.editor_mut().replace_document_symbols(symbols);
1029        self.mark_modified(StateChangeType::SymbolsChanged);
1030    }
1031
1032    /// Clear document symbols / outline.
1033    pub fn clear_document_symbols(&mut self) {
1034        self.executor.editor_mut().clear_document_symbols();
1035        self.mark_modified(StateChangeType::SymbolsChanged);
1036    }
1037
1038    /// Replace a decoration layer wholesale.
1039    pub fn replace_decorations(&mut self, layer: DecorationLayerId, decorations: Vec<Decoration>) {
1040        self.executor
1041            .editor_mut()
1042            .replace_decorations(layer, decorations);
1043        self.mark_modified(StateChangeType::DecorationsChanged);
1044    }
1045
1046    /// Clear a decoration layer.
1047    pub fn clear_decorations(&mut self, layer: DecorationLayerId) {
1048        self.executor.editor_mut().clear_decorations(layer);
1049        self.mark_modified(StateChangeType::DecorationsChanged);
1050    }
1051
1052    /// Replace folding regions wholesale.
1053    ///
1054    /// If `preserve_collapsed` is true, matching existing collapsed derived regions stay collapsed
1055    /// after replacement, including conservative matches across small line-number drift.
1056    pub fn replace_folding_regions(&mut self, regions: Vec<FoldRegion>, preserve_collapsed: bool) {
1057        self.executor
1058            .editor_mut()
1059            .replace_folding_regions(regions, preserve_collapsed);
1060        self.mark_modified(StateChangeType::FoldingChanged);
1061    }
1062
1063    /// Clear all *derived* folding regions (leaves user folds intact).
1064    pub fn clear_folding_regions(&mut self) {
1065        self.executor.editor_mut().clear_derived_folding_regions();
1066        self.mark_modified(StateChangeType::FoldingChanged);
1067    }
1068
1069    /// Toggle the fold region that starts on the current cursor line.
1070    pub fn toggle_fold_at_current_line(&mut self) -> bool {
1071        let line = self.executor.editor().cursor_position().line;
1072        let toggled = self.executor.editor_mut().toggle_fold_at_line(line);
1073        if toggled {
1074            self.mark_modified(StateChangeType::FoldingChanged);
1075        }
1076        toggled
1077    }
1078
1079    /// Expand all folding regions.
1080    pub fn expand_all_folds(&mut self) {
1081        let had_collapsed = self
1082            .executor
1083            .editor()
1084            .folding_manager()
1085            .regions()
1086            .iter()
1087            .any(|region| region.is_collapsed);
1088        self.executor.editor_mut().expand_all_folds();
1089        if had_collapsed {
1090            self.mark_modified(StateChangeType::FoldingChanged);
1091        }
1092    }
1093
1094    /// Apply derived-state edits produced by a document processor (highlighting, folding, etc.).
1095    pub fn apply_processing_edits<I>(&mut self, edits: I)
1096    where
1097        I: IntoIterator<Item = ProcessingEdit>,
1098    {
1099        for edit in edits {
1100            match edit {
1101                ProcessingEdit::ReplaceStyleLayer { layer, intervals } => {
1102                    self.replace_style_layer(layer, intervals);
1103                }
1104                ProcessingEdit::ClearStyleLayer { layer } => {
1105                    self.clear_style_layer(layer);
1106                }
1107                ProcessingEdit::ReplaceFoldingRegions {
1108                    regions,
1109                    preserve_collapsed,
1110                } => {
1111                    self.replace_folding_regions(regions, preserve_collapsed);
1112                }
1113                ProcessingEdit::ClearFoldingRegions => {
1114                    self.clear_folding_regions();
1115                }
1116                ProcessingEdit::ReplaceDiagnostics { diagnostics } => {
1117                    self.replace_diagnostics(diagnostics);
1118                }
1119                ProcessingEdit::ClearDiagnostics => {
1120                    self.clear_diagnostics();
1121                }
1122                ProcessingEdit::ReplaceDecorations { layer, decorations } => {
1123                    self.replace_decorations(layer, decorations);
1124                }
1125                ProcessingEdit::ClearDecorations { layer } => {
1126                    self.clear_decorations(layer);
1127                }
1128                ProcessingEdit::ReplaceDocumentSymbols { symbols } => {
1129                    self.replace_document_symbols(symbols);
1130                }
1131                ProcessingEdit::ClearDocumentSymbols => {
1132                    self.clear_document_symbols();
1133                }
1134            }
1135        }
1136    }
1137
1138    /// Run a [`DocumentProcessor`] against the current document and apply its edits.
1139    pub fn apply_processor<P>(&mut self, processor: &mut P) -> Result<(), P::Error>
1140    where
1141        P: DocumentProcessor,
1142    {
1143        let edits = processor.process(self)?;
1144        self.apply_processing_edits(edits);
1145        Ok(())
1146    }
1147
1148    /// Get viewport content
1149    pub fn get_viewport_content(&self, start_row: usize, count: usize) -> HeadlessGrid {
1150        let editor = self.executor.editor();
1151        let text = editor.get_text();
1152        let generator = crate::SnapshotGenerator::from_text_with_layout_options(
1153            &text,
1154            editor.viewport_width(),
1155            editor.layout_engine().tab_width(),
1156            editor.layout_engine().wrap_mode(),
1157            editor.layout_engine().wrap_indent(),
1158        );
1159        generator.get_headless_grid(start_row, count)
1160    }
1161
1162    /// Get styled viewport content (by visual line).
1163    ///
1164    /// - Supports soft wrapping (based on `LayoutEngine`)
1165    /// - `Cell.styles` will contain the merged result of `interval_tree` and all `style_layers`
1166    pub fn get_viewport_content_styled(
1167        &self,
1168        start_visual_row: usize,
1169        count: usize,
1170    ) -> HeadlessGrid {
1171        self.executor
1172            .editor()
1173            .get_headless_grid_styled(start_visual_row, count)
1174    }
1175
1176    /// Get lightweight minimap content (by visual line).
1177    pub fn get_minimap_content(&self, start_visual_row: usize, count: usize) -> crate::MinimapGrid {
1178        self.executor
1179            .editor()
1180            .get_minimap_grid(start_visual_row, count)
1181    }
1182
1183    /// Get a decoration-aware composed viewport snapshot (by composed visual line).
1184    ///
1185    /// See [`EditorCore::get_headless_grid_composed`](crate::EditorCore::get_headless_grid_composed)
1186    /// for detailed semantics and caveats.
1187    pub fn get_viewport_content_composed(
1188        &self,
1189        start_visual_row: usize,
1190        count: usize,
1191    ) -> ComposedGrid {
1192        self.executor
1193            .editor()
1194            .get_headless_grid_composed(start_visual_row, count)
1195    }
1196
1197    /// Get total visual line count under current wrap/folding state.
1198    pub fn total_visual_lines(&self) -> usize {
1199        self.executor.editor().visual_line_count()
1200    }
1201
1202    /// Map global visual row to `(logical_line, visual_in_logical)`.
1203    pub fn visual_to_logical_line(&self, visual_row: usize) -> (usize, usize) {
1204        self.executor.editor().visual_to_logical_line(visual_row)
1205    }
1206
1207    /// Map logical position to visual `(row, x_cells)`.
1208    pub fn logical_position_to_visual(&self, line: usize, column: usize) -> Option<(usize, usize)> {
1209        self.executor
1210            .editor()
1211            .logical_position_to_visual(line, column)
1212    }
1213
1214    /// Map visual `(row, x_cells)` back to logical position.
1215    pub fn visual_position_to_logical(
1216        &self,
1217        visual_row: usize,
1218        x_cells: usize,
1219    ) -> Option<Position> {
1220        self.executor
1221            .editor()
1222            .visual_position_to_logical(visual_row, x_cells)
1223    }
1224
1225    /// Subscribe to state change notifications
1226    pub fn subscribe<F>(&mut self, callback: F)
1227    where
1228        F: FnMut(&StateChange) + Send + 'static,
1229    {
1230        self.callbacks.push(Box::new(callback));
1231    }
1232
1233    /// Check if state has changed since a version
1234    pub fn has_changed_since(&self, version: u64) -> bool {
1235        self.state_version > version
1236    }
1237
1238    /// Mark document as modified and increment version number
1239    pub fn mark_modified(&mut self, change_type: StateChangeType) {
1240        self.mark_modified_internal(change_type, None, None);
1241    }
1242
1243    fn mark_modified_internal(
1244        &mut self,
1245        change_type: StateChangeType,
1246        is_modified_override: Option<bool>,
1247        delta: Option<Arc<TextDelta>>,
1248    ) {
1249        let old_version = self.state_version;
1250        self.state_version += 1;
1251
1252        // Only mark as modified for document content changes
1253        if matches!(change_type, StateChangeType::DocumentModified) {
1254            self.is_modified = is_modified_override.unwrap_or(true);
1255        }
1256
1257        let mut change = StateChange::new(change_type, old_version, self.state_version);
1258        if let Some(delta) = delta {
1259            change = change.with_text_delta(delta);
1260        }
1261        self.notify_callbacks(&change);
1262    }
1263
1264    /// Mark document as unmodified (e.g., after saving)
1265    pub fn mark_saved(&mut self) {
1266        self.executor.mark_clean();
1267        self.is_modified = false;
1268    }
1269
1270    /// Capture a persistable snapshot of the undo/redo history for this document.
1271    pub fn undo_history_snapshot(&self) -> UndoHistorySnapshot {
1272        self.executor.undo_history_snapshot()
1273    }
1274
1275    /// Restore a previously captured [`UndoHistorySnapshot`].
1276    ///
1277    /// Notes:
1278    /// - This does **not** modify the current document text.
1279    /// - Callers should only restore a snapshot into the **same text** it was captured from.
1280    pub fn restore_undo_history(
1281        &mut self,
1282        snapshot: UndoHistorySnapshot,
1283    ) -> Result<(), UndoHistoryRestoreError> {
1284        self.last_text_delta = None;
1285        self.executor.restore_undo_history(snapshot)?;
1286        self.is_modified = !self.executor.is_clean();
1287        Ok(())
1288    }
1289
1290    /// Notify state change (without modifying version number)
1291    fn notify_change(&mut self, change_type: StateChangeType) {
1292        let change = StateChange::new(change_type, self.state_version, self.state_version);
1293        self.notify_callbacks(&change);
1294    }
1295
1296    /// Get the structured text delta produced by the last document edit, if any.
1297    pub fn last_text_delta(&self) -> Option<&TextDelta> {
1298        self.last_text_delta.as_deref()
1299    }
1300
1301    /// Take the structured text delta produced by the last document edit, if any.
1302    pub fn take_last_text_delta(&mut self) -> Option<Arc<TextDelta>> {
1303        self.last_text_delta.take()
1304    }
1305
1306    /// Toggle a bookmark at the current cursor line.
1307    ///
1308    /// Returns `true` if a bookmark was added, or `false` if an existing bookmark on that line was
1309    /// removed.
1310    pub fn toggle_bookmark_at_cursor_line(&mut self) -> bool {
1311        let line = self.executor.editor().cursor_position().line;
1312        let line_start = self
1313            .executor
1314            .editor()
1315            .line_index()
1316            .position_to_char_offset(line, 0);
1317        let added = self.bookmarks.toggle_line_start(line_start);
1318        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1319        added
1320    }
1321
1322    /// Return all bookmark line numbers (0-based).
1323    pub fn bookmark_lines(&self) -> Vec<usize> {
1324        self.bookmarks
1325            .line_numbers(self.executor.editor().line_index())
1326    }
1327
1328    /// Clear all bookmarks.
1329    pub fn clear_bookmarks(&mut self) {
1330        self.bookmarks.clear();
1331        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1332    }
1333
1334    /// Move the cursor to the next bookmark (wrapping to the first bookmark).
1335    ///
1336    /// Returns the new cursor position, or `None` if there are no bookmarks.
1337    pub fn goto_next_bookmark(&mut self) -> Result<Option<Position>, CommandError> {
1338        let line = self.executor.editor().cursor_position().line;
1339        let current_line_start = self
1340            .executor
1341            .editor()
1342            .line_index()
1343            .position_to_char_offset(line, 0);
1344
1345        let Some(target) = self.bookmarks.next_after_line_start(current_line_start) else {
1346            return Ok(None);
1347        };
1348
1349        let (line, column) = self
1350            .executor
1351            .editor()
1352            .line_index()
1353            .char_offset_to_position(target.offset);
1354        self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1355        let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1356        Ok(Some(Position::new(line, column)))
1357    }
1358
1359    /// Move the cursor to the previous bookmark (wrapping to the last bookmark).
1360    ///
1361    /// Returns the new cursor position, or `None` if there are no bookmarks.
1362    pub fn goto_prev_bookmark(&mut self) -> Result<Option<Position>, CommandError> {
1363        let line = self.executor.editor().cursor_position().line;
1364        let current_line_start = self
1365            .executor
1366            .editor()
1367            .line_index()
1368            .position_to_char_offset(line, 0);
1369
1370        let Some(target) = self.bookmarks.prev_before_line_start(current_line_start) else {
1371            return Ok(None);
1372        };
1373
1374        let (line, column) = self
1375            .executor
1376            .editor()
1377            .line_index()
1378            .char_offset_to_position(target.offset);
1379        self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1380        let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1381        Ok(Some(Position::new(line, column)))
1382    }
1383
1384    /// Set (or replace) a named mark at the current cursor position.
1385    pub fn set_mark_at_cursor(&mut self, name: String) -> Result<(), CommandError> {
1386        if name.trim().is_empty() {
1387            return Err(CommandError::Other("Mark name cannot be empty".to_string()));
1388        }
1389
1390        let pos = self.executor.editor().cursor_position();
1391        let offset = self
1392            .executor
1393            .editor()
1394            .line_index()
1395            .position_to_char_offset(pos.line, pos.column);
1396        self.marks.set(name, offset);
1397        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1398        Ok(())
1399    }
1400
1401    /// Move the cursor to a named mark (if present).
1402    ///
1403    /// Returns the new cursor position, or `None` if the mark does not exist.
1404    pub fn goto_mark(&mut self, name: &str) -> Result<Option<Position>, CommandError> {
1405        let Some(anchor) = self.marks.get(name) else {
1406            return Ok(None);
1407        };
1408        let (line, column) = self
1409            .executor
1410            .editor()
1411            .line_index()
1412            .char_offset_to_position(anchor.offset);
1413        self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1414        let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1415        Ok(Some(Position::new(line, column)))
1416    }
1417
1418    /// Remove a named mark.
1419    ///
1420    /// Returns `true` if the mark existed.
1421    pub fn clear_mark(&mut self, name: &str) -> bool {
1422        let existed = self.marks.remove(name);
1423        if existed {
1424            self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1425        }
1426        existed
1427    }
1428
1429    /// Return all mark names (deterministic order).
1430    pub fn mark_names(&self) -> Vec<String> {
1431        self.marks.names()
1432    }
1433
1434    /// Clear all marks.
1435    pub fn clear_all_marks(&mut self) {
1436        self.marks.clear();
1437        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1438    }
1439
1440    /// Record the current cursor position as a jump-list location.
1441    ///
1442    /// Typical usage: call this *before* performing a “jump” (go-to-definition, search result,
1443    /// symbol navigation, ...).
1444    pub fn push_jump_location(&mut self) {
1445        let pos = self.executor.editor().cursor_position();
1446        let offset = self
1447            .executor
1448            .editor()
1449            .line_index()
1450            .position_to_char_offset(pos.line, pos.column);
1451        self.jump_list.record(offset);
1452        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1453    }
1454
1455    /// Jump back in the jump list.
1456    ///
1457    /// Returns the new cursor position, or `None` if there is no back entry.
1458    pub fn jump_back(&mut self) -> Result<Option<Position>, CommandError> {
1459        let pos = self.executor.editor().cursor_position();
1460        let current_offset = self
1461            .executor
1462            .editor()
1463            .line_index()
1464            .position_to_char_offset(pos.line, pos.column);
1465
1466        let Some(target) = self.jump_list.back(current_offset) else {
1467            return Ok(None);
1468        };
1469
1470        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1471
1472        let (line, column) = self
1473            .executor
1474            .editor()
1475            .line_index()
1476            .char_offset_to_position(target.offset);
1477        self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1478        let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1479        Ok(Some(Position::new(line, column)))
1480    }
1481
1482    /// Jump forward in the jump list.
1483    ///
1484    /// Returns the new cursor position, or `None` if there is no forward entry.
1485    pub fn jump_forward(&mut self) -> Result<Option<Position>, CommandError> {
1486        let pos = self.executor.editor().cursor_position();
1487        let current_offset = self
1488            .executor
1489            .editor()
1490            .line_index()
1491            .position_to_char_offset(pos.line, pos.column);
1492
1493        let Some(target) = self.jump_list.forward(current_offset) else {
1494            return Ok(None);
1495        };
1496
1497        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1498
1499        let (line, column) = self
1500            .executor
1501            .editor()
1502            .line_index()
1503            .char_offset_to_position(target.offset);
1504        self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1505        let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1506        Ok(Some(Position::new(line, column)))
1507    }
1508
1509    /// Clear the jump list (both back/forward stacks).
1510    pub fn clear_jump_list(&mut self) {
1511        self.jump_list.clear();
1512        self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1513    }
1514
1515    /// Notify all callbacks
1516    fn notify_callbacks(&mut self, change: &StateChange) {
1517        for callback in &mut self.callbacks {
1518            callback(change);
1519        }
1520    }
1521}
1522
1523#[cfg(test)]
1524mod tests {
1525    use super::*;
1526
1527    #[test]
1528    fn test_document_state() {
1529        let manager = EditorStateManager::new("Hello World\nLine 2", 80);
1530        let doc_state = manager.get_document_state();
1531
1532        assert_eq!(doc_state.line_count, 2);
1533        assert_eq!(doc_state.char_count, 18); // Including newline
1534        assert!(!doc_state.is_modified);
1535        assert_eq!(doc_state.version, 0);
1536    }
1537
1538    #[test]
1539    fn test_cursor_state() {
1540        let manager = EditorStateManager::new("Hello World", 80);
1541        let cursor_state = manager.get_cursor_state();
1542
1543        assert_eq!(cursor_state.position, Position::new(0, 0));
1544        assert_eq!(cursor_state.offset, 0);
1545        assert!(cursor_state.selection.is_none());
1546    }
1547
1548    #[test]
1549    fn test_viewport_state() {
1550        let mut manager = EditorStateManager::new("Line 1\nLine 2\nLine 3", 80);
1551        manager.set_viewport_height(10);
1552        manager.set_scroll_top(1);
1553
1554        let viewport_state = manager.get_viewport_state();
1555
1556        assert_eq!(viewport_state.width, 80);
1557        assert_eq!(viewport_state.height, Some(10));
1558        assert_eq!(viewport_state.scroll_top, 1);
1559        assert_eq!(viewport_state.visible_lines, 1..3);
1560    }
1561
1562    #[test]
1563    fn test_folding_state() {
1564        let manager = EditorStateManager::new("Line 1\nLine 2\nLine 3", 80);
1565        let folding_state = manager.get_folding_state();
1566
1567        assert_eq!(folding_state.regions.len(), 0);
1568        assert_eq!(folding_state.collapsed_line_count, 0);
1569        assert_eq!(folding_state.visible_logical_lines, 3);
1570    }
1571
1572    #[test]
1573    fn test_style_state() {
1574        let manager = EditorStateManager::new("Hello World", 80);
1575        let style_state = manager.get_style_state();
1576
1577        assert_eq!(style_state.style_count, 0);
1578    }
1579
1580    #[test]
1581    fn test_full_state() {
1582        let manager = EditorStateManager::new("Test", 80);
1583        let full_state = manager.get_full_state();
1584
1585        assert_eq!(full_state.document.line_count, 1);
1586        assert_eq!(full_state.cursor.position, Position::new(0, 0));
1587        assert_eq!(full_state.viewport.width, 80);
1588    }
1589
1590    #[test]
1591    fn test_version_tracking() {
1592        let mut manager = EditorStateManager::new("Test", 80);
1593
1594        assert_eq!(manager.version(), 0);
1595        assert!(!manager.has_changed_since(0));
1596
1597        manager.mark_modified(StateChangeType::DocumentModified);
1598
1599        assert_eq!(manager.version(), 1);
1600        assert!(manager.has_changed_since(0));
1601        assert!(!manager.has_changed_since(1));
1602    }
1603
1604    #[test]
1605    fn test_modification_tracking() {
1606        let mut manager = EditorStateManager::new("Test", 80);
1607
1608        assert!(!manager.get_document_state().is_modified);
1609
1610        manager.mark_modified(StateChangeType::DocumentModified);
1611        assert!(manager.get_document_state().is_modified);
1612
1613        manager.mark_saved();
1614        assert!(!manager.get_document_state().is_modified);
1615    }
1616
1617    #[test]
1618    fn test_undo_redo_state_and_dirty_tracking() {
1619        let mut manager = EditorStateManager::empty(80);
1620
1621        let state = manager.get_undo_redo_state();
1622        assert!(!state.can_undo);
1623        assert!(!state.can_redo);
1624
1625        manager
1626            .execute(Command::Edit(EditCommand::InsertText {
1627                text: "abc".to_string(),
1628            }))
1629            .unwrap();
1630
1631        assert!(manager.get_document_state().is_modified);
1632        let state = manager.get_undo_redo_state();
1633        assert!(state.can_undo);
1634        assert!(!state.can_redo);
1635        assert_eq!(state.undo_depth, 1);
1636
1637        manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1638        assert!(!manager.get_document_state().is_modified);
1639        let state = manager.get_undo_redo_state();
1640        assert!(!state.can_undo);
1641        assert!(state.can_redo);
1642
1643        manager.execute(Command::Edit(EditCommand::Redo)).unwrap();
1644        assert!(manager.get_document_state().is_modified);
1645        let state = manager.get_undo_redo_state();
1646        assert!(state.can_undo);
1647        assert!(!state.can_redo);
1648    }
1649
1650    #[test]
1651    fn test_insert_tab_undo_restores_clean_state() {
1652        let mut manager = EditorStateManager::empty(80);
1653        assert!(!manager.get_document_state().is_modified);
1654
1655        manager
1656            .execute(Command::Edit(EditCommand::InsertTab))
1657            .unwrap();
1658        assert!(manager.get_document_state().is_modified);
1659
1660        manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1661        assert!(!manager.get_document_state().is_modified);
1662    }
1663
1664    #[test]
1665    fn test_insert_tab_spaces_undo_restores_clean_state() {
1666        let mut manager = EditorStateManager::empty(80);
1667        manager
1668            .execute(Command::View(ViewCommand::SetTabKeyBehavior {
1669                behavior: crate::TabKeyBehavior::Spaces,
1670            }))
1671            .unwrap();
1672
1673        manager
1674            .execute(Command::Edit(EditCommand::InsertTab))
1675            .unwrap();
1676        assert!(manager.get_document_state().is_modified);
1677
1678        manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1679        assert!(!manager.get_document_state().is_modified);
1680    }
1681
1682    #[test]
1683    fn test_state_change_callback() {
1684        use std::sync::{Arc, Mutex};
1685
1686        let mut manager = EditorStateManager::new("Test", 80);
1687
1688        let callback_called = Arc::new(Mutex::new(false));
1689        let callback_called_clone = callback_called.clone();
1690
1691        manager.subscribe(move |_change| {
1692            *callback_called_clone.lock().unwrap() = true;
1693        });
1694
1695        manager.mark_modified(StateChangeType::CursorMoved);
1696
1697        // Verify callback was called
1698        assert!(*callback_called.lock().unwrap());
1699    }
1700
1701    #[test]
1702    fn test_execute_cursor_noop_does_not_bump_version() {
1703        let mut manager = EditorStateManager::new("A", 80);
1704        assert_eq!(manager.version(), 0);
1705
1706        // Continue moving left at the beginning of file (unchanged after clamp), version should not change.
1707        manager
1708            .execute(Command::Cursor(CursorCommand::MoveBy {
1709                delta_line: 0,
1710                delta_column: -1,
1711            }))
1712            .unwrap();
1713        assert_eq!(manager.editor().cursor_position(), Position::new(0, 0));
1714        assert_eq!(manager.version(), 0);
1715
1716        // Move to end of line (changed), version increments.
1717        manager
1718            .execute(Command::Cursor(CursorCommand::MoveTo {
1719                line: 0,
1720                column: usize::MAX,
1721            }))
1722            .unwrap();
1723        assert_eq!(manager.editor().cursor_position(), Position::new(0, 1));
1724        assert_eq!(manager.version(), 1);
1725
1726        // Continue moving right at end of line (unchanged after clamp), version should not change.
1727        let version_before = manager.version();
1728        manager
1729            .execute(Command::Cursor(CursorCommand::MoveBy {
1730                delta_line: 0,
1731                delta_column: 1,
1732            }))
1733            .unwrap();
1734        assert_eq!(manager.editor().cursor_position(), Position::new(0, 1));
1735        assert_eq!(manager.version(), version_before);
1736    }
1737
1738    #[test]
1739    fn test_viewport_height() {
1740        let mut manager = EditorStateManager::new("Test", 80);
1741
1742        assert_eq!(manager.get_viewport_state().height, None);
1743
1744        manager.set_viewport_height(20);
1745        assert_eq!(manager.get_viewport_state().height, Some(20));
1746    }
1747
1748    #[test]
1749    fn test_scroll_position() {
1750        let mut manager = EditorStateManager::new("Line 1\nLine 2\nLine 3\nLine 4", 80);
1751        manager.set_viewport_height(2);
1752
1753        assert_eq!(manager.get_viewport_state().scroll_top, 0);
1754        assert_eq!(manager.get_viewport_state().visible_lines, 0..2);
1755
1756        manager.set_scroll_top(2);
1757        assert_eq!(manager.get_viewport_state().scroll_top, 2);
1758        assert_eq!(manager.get_viewport_state().visible_lines, 2..4);
1759    }
1760
1761    #[test]
1762    fn test_get_styles() {
1763        let mut manager = EditorStateManager::new("Hello World", 80);
1764
1765        // Add style through the controlled editor-core API.
1766        manager
1767            .editor_mut()
1768            .insert_style_interval(crate::intervals::Interval::new(0, 5, 1));
1769
1770        let styles = manager.get_styles_in_range(0, 10);
1771        assert_eq!(styles.len(), 1);
1772        assert_eq!(styles[0], (0, 5, 1));
1773
1774        let styles_at = manager.get_styles_at(3);
1775        assert_eq!(styles_at.len(), 1);
1776        assert_eq!(styles_at[0], 1);
1777    }
1778
1779    #[test]
1780    fn test_replace_style_layer_affects_queries() {
1781        let mut manager = EditorStateManager::new("Hello", 80);
1782
1783        manager.replace_style_layer(
1784            StyleLayerId::SEMANTIC_TOKENS,
1785            vec![Interval::new(0, 1, 100)],
1786        );
1787
1788        assert_eq!(manager.get_styles_at(0), vec![100]);
1789
1790        // Base layer + layered styles are merged.
1791        manager
1792            .editor_mut()
1793            .insert_style_interval(Interval::new(0, 5, 1));
1794
1795        assert_eq!(manager.get_styles_at(0), vec![1, 100]);
1796    }
1797
1798    #[test]
1799    fn test_viewport_content_styled_wraps_and_includes_styles() {
1800        let mut manager = EditorStateManager::new("abcdef", 3);
1801
1802        // Highlight "bcd" across a wrap boundary: "abc" | "def"
1803        manager.replace_style_layer(StyleLayerId::SIMPLE_SYNTAX, vec![Interval::new(1, 4, 7)]);
1804
1805        let grid = manager.get_viewport_content_styled(0, 10);
1806        assert_eq!(grid.actual_line_count(), 2);
1807
1808        let line0 = &grid.lines[0];
1809        assert_eq!(line0.logical_line_index, 0);
1810        assert!(!line0.is_wrapped_part);
1811        assert_eq!(line0.cells.len(), 3);
1812        assert_eq!(line0.cells[0].ch, 'a');
1813        assert_eq!(line0.cells[1].ch, 'b');
1814        assert_eq!(line0.cells[2].ch, 'c');
1815        assert_eq!(line0.cells[0].styles, Vec::<StyleId>::new());
1816        assert_eq!(line0.cells[1].styles, vec![7]);
1817        assert_eq!(line0.cells[2].styles, vec![7]);
1818
1819        let line1 = &grid.lines[1];
1820        assert_eq!(line1.logical_line_index, 0);
1821        assert!(line1.is_wrapped_part);
1822        assert_eq!(line1.cells.len(), 3);
1823        assert_eq!(line1.cells[0].ch, 'd');
1824        assert_eq!(line1.cells[0].styles, vec![7]);
1825        assert_eq!(line1.cells[1].ch, 'e');
1826        assert_eq!(line1.cells[1].styles, Vec::<StyleId>::new());
1827    }
1828
1829    #[test]
1830    fn test_smooth_scroll_state_and_prefetch_lines() {
1831        let mut manager = EditorStateManager::new("a\nb\nc\nd\n", 80);
1832        manager.set_viewport_height(2);
1833        manager.set_scroll_top(1);
1834        manager.set_scroll_sub_row_offset(123);
1835        manager.set_overscan_rows(2);
1836
1837        let smooth = manager.get_smooth_scroll_state();
1838        assert_eq!(
1839            smooth,
1840            SmoothScrollState {
1841                top_visual_row: 1,
1842                sub_row_offset: 123,
1843                overscan_rows: 2
1844            }
1845        );
1846
1847        let viewport = manager.get_viewport_state();
1848        assert_eq!(viewport.visible_lines, 1..3);
1849        assert_eq!(viewport.sub_row_offset, 123);
1850        assert_eq!(viewport.overscan_rows, 2);
1851        assert_eq!(viewport.prefetch_lines, 0..5);
1852        assert_eq!(viewport.total_visual_lines, 5);
1853    }
1854
1855    #[test]
1856    fn test_minimap_content_returns_lightweight_summary() {
1857        let mut manager = EditorStateManager::new("abc def\n", 80);
1858        manager.replace_style_layer(StyleLayerId::SIMPLE_SYNTAX, vec![Interval::new(0, 3, 9)]);
1859
1860        let minimap = manager.get_minimap_content(0, 1);
1861        assert_eq!(minimap.actual_line_count(), 1);
1862        let line = &minimap.lines[0];
1863        assert_eq!(line.logical_line_index, 0);
1864        assert_eq!(line.visual_in_logical, 0);
1865        assert_eq!(line.char_offset_start, 0);
1866        assert_eq!(line.char_offset_end, 7);
1867        assert!(line.total_cells >= line.non_whitespace_cells);
1868        assert_eq!(line.dominant_style, Some(9));
1869        assert!(!line.is_fold_placeholder_appended);
1870    }
1871}