1use 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#[derive(Debug, Clone)]
54pub struct DocumentState {
55 pub line_count: usize,
57 pub char_count: usize,
59 pub byte_count: usize,
61 pub is_modified: bool,
63 pub version: u64,
65}
66
67#[derive(Debug, Clone)]
69pub struct CursorState {
70 pub position: Position,
72 pub offset: usize,
74 pub multi_cursors: Vec<Position>,
76 pub selection: Option<Selection>,
78 pub selections: Vec<Selection>,
80 pub primary_selection_index: usize,
82}
83
84#[derive(Debug, Clone)]
86pub struct ViewportState {
87 pub width: usize,
89 pub height: Option<usize>,
91 pub scroll_top: usize,
93 pub sub_row_offset: u16,
95 pub overscan_rows: usize,
97 pub visible_lines: Range<usize>,
99 pub prefetch_lines: Range<usize>,
101 pub total_visual_lines: usize,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub struct SmoothScrollState {
108 pub top_visual_row: usize,
110 pub sub_row_offset: u16,
112 pub overscan_rows: usize,
114}
115
116#[derive(Debug, Clone)]
118pub struct UndoRedoState {
119 pub can_undo: bool,
121 pub can_redo: bool,
123 pub undo_depth: usize,
125 pub redo_depth: usize,
127 pub redo_branch_count: usize,
129 pub selected_redo_branch_index: Option<usize>,
131 pub current_change_group: Option<usize>,
133}
134
135#[derive(Debug, Clone)]
137pub struct FoldingState {
138 pub regions: Vec<FoldRegion>,
140 pub collapsed_line_count: usize,
142 pub visible_logical_lines: usize,
144 pub total_visual_lines: usize,
146}
147
148#[derive(Debug, Clone)]
150pub struct DiagnosticsState {
151 pub diagnostics_count: usize,
153}
154
155#[derive(Debug, Clone)]
157pub struct DecorationsState {
158 pub layer_count: usize,
160 pub decoration_count: usize,
162}
163
164#[derive(Debug, Clone)]
166pub struct StyleState {
167 pub style_count: usize,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum StateChangeType {
174 DocumentModified,
176 CursorMoved,
178 SelectionChanged,
180 NavigationChanged,
182 ViewportChanged,
184 FoldingChanged,
186 StyleChanged,
188 DecorationsChanged,
190 DiagnosticsChanged,
192 SymbolsChanged,
194}
195
196#[derive(Debug, Clone)]
198pub struct StateChange {
199 pub change_type: StateChangeType,
201 pub old_version: u64,
203 pub new_version: u64,
205 pub affected_region: Option<Range<usize>>,
207 pub text_delta: Option<Arc<TextDelta>>,
209}
210
211impl StateChange {
212 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 pub fn with_region(mut self, region: Range<usize>) -> Self {
225 self.affected_region = Some(region);
226 self
227 }
228
229 pub fn with_text_delta(mut self, delta: Arc<TextDelta>) -> Self {
231 self.text_delta = Some(delta);
232 self
233 }
234}
235
236#[derive(Debug, Clone)]
238pub struct EditorState {
239 pub document: DocumentState,
241 pub cursor: CursorState,
243 pub viewport: ViewportState,
245 pub undo_redo: UndoRedoState,
247 pub folding: FoldingState,
249 pub diagnostics: DiagnosticsState,
251 pub decorations: DecorationsState,
253 pub style: StyleState,
255}
256
257pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
421enum ViewChangeKind {
422 ViewportWidthOnly,
423 Other,
424}
425
426pub struct EditorStateManager {
476 executor: CommandExecutor,
478 state_version: u64,
480 is_modified: bool,
482 callbacks: Vec<StateChangeCallback>,
484 scroll_top: usize,
486 scroll_sub_row_offset: u16,
488 overscan_rows: usize,
490 viewport_height: Option<usize>,
492 last_text_delta: Option<Arc<TextDelta>>,
494 bookmarks: BookmarkSet,
495 marks: MarkSet,
496 jump_list: JumpList,
497}
498
499impl EditorStateManager {
500 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 pub fn empty(viewport_width: usize) -> Self {
520 Self::new("", viewport_width)
521 }
522
523 pub fn editor(&self) -> &EditorCore {
525 self.executor.editor()
526 }
527
528 pub fn editor_mut(&mut self) -> &mut EditorCore {
535 self.executor.editor_mut()
536 }
537
538 pub fn line_ending(&self) -> LineEnding {
540 self.executor.line_ending()
541 }
542
543 pub fn set_line_ending(&mut self, line_ending: LineEnding) {
545 self.executor.set_line_ending(line_ending);
546 }
547
548 pub fn has_active_snippet_session(&self) -> bool {
550 self.executor.has_active_snippet_session()
551 }
552
553 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 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 let command_kind = if matches!(&command, Command::View(ViewCommand::SetViewportWidth { .. }))
574 {
575 ViewChangeKind::ViewportWidthOnly
576 } else {
577 ViewChangeKind::Other
578 };
579
580 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 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 if is_delete_like {
619 char_count_after != char_count_before
620 } else {
621 delta_present
622 }
623 }
624 StateChangeType::NavigationChanged => true,
625 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 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 pub fn version(&self) -> u64 {
716 self.state_version
717 }
718
719 pub fn set_viewport_height(&mut self, height: usize) {
721 self.viewport_height = Some(height);
722 }
723
724 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 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 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 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 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 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 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 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 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 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 pub fn get_folding_state(&self) -> FoldingState {
909 let editor = self.executor.editor();
910 let regions = editor.folding_manager().regions().to_vec();
911 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 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 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 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 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 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 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 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 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 pub fn clear_diagnostics(&mut self) {
1022 self.executor.editor_mut().clear_diagnostics();
1023 self.mark_modified(StateChangeType::DiagnosticsChanged);
1024 }
1025
1026 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 pub fn clear_document_symbols(&mut self) {
1034 self.executor.editor_mut().clear_document_symbols();
1035 self.mark_modified(StateChangeType::SymbolsChanged);
1036 }
1037
1038 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 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 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 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 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 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 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 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 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 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 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 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 pub fn total_visual_lines(&self) -> usize {
1199 self.executor.editor().visual_line_count()
1200 }
1201
1202 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 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 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 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 pub fn has_changed_since(&self, version: u64) -> bool {
1235 self.state_version > version
1236 }
1237
1238 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 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 pub fn mark_saved(&mut self) {
1266 self.executor.mark_clean();
1267 self.is_modified = false;
1268 }
1269
1270 pub fn undo_history_snapshot(&self) -> UndoHistorySnapshot {
1272 self.executor.undo_history_snapshot()
1273 }
1274
1275 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 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 pub fn last_text_delta(&self) -> Option<&TextDelta> {
1298 self.last_text_delta.as_deref()
1299 }
1300
1301 pub fn take_last_text_delta(&mut self) -> Option<Arc<TextDelta>> {
1303 self.last_text_delta.take()
1304 }
1305
1306 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 pub fn bookmark_lines(&self) -> Vec<usize> {
1324 self.bookmarks
1325 .line_numbers(self.executor.editor().line_index())
1326 }
1327
1328 pub fn clear_bookmarks(&mut self) {
1330 self.bookmarks.clear();
1331 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1332 }
1333
1334 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 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 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 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 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 pub fn mark_names(&self) -> Vec<String> {
1431 self.marks.names()
1432 }
1433
1434 pub fn clear_all_marks(&mut self) {
1436 self.marks.clear();
1437 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1438 }
1439
1440 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 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 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 pub fn clear_jump_list(&mut self) {
1511 self.jump_list.clear();
1512 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1513 }
1514
1515 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); 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 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 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 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 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 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 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 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}