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!(
574 &command,
575 Command::View(ViewCommand::SetViewportWidth { .. })
576 ) {
577 ViewChangeKind::ViewportWidthOnly
578 } else {
579 ViewChangeKind::Other
580 };
581
582 let cursor_before = self.executor.editor().cursor_position();
584 let selection_before = self.executor.editor().selection().cloned();
585 let secondary_before = self.executor.editor().secondary_selections().to_vec();
586 let viewport_width_before = self.executor.editor().viewport_width();
587 let char_count_before = self.executor.editor().char_count();
588
589 let result = self.executor.execute(command)?;
590 let char_count_after = self.executor.editor().char_count();
591 let delta_present = self.executor.last_text_delta().is_some();
592
593 if let Some(change_type) = change_type {
594 let changed = match change_type {
595 StateChangeType::CursorMoved => {
596 self.executor.editor().cursor_position() != cursor_before
597 || self.executor.editor().secondary_selections()
598 != secondary_before.as_slice()
599 }
600 StateChangeType::SelectionChanged => {
601 self.executor.editor().cursor_position() != cursor_before
602 || self.executor.editor().selection().cloned() != selection_before
603 || self.executor.editor().secondary_selections()
604 != secondary_before.as_slice()
605 }
606 StateChangeType::ViewportChanged => {
607 if matches!(command_kind, ViewChangeKind::ViewportWidthOnly) {
612 self.executor.editor().viewport_width() != viewport_width_before
613 } else {
614 true
615 }
616 }
617 StateChangeType::DocumentModified => {
618 if is_delete_like {
621 char_count_after != char_count_before
622 } else {
623 delta_present
624 }
625 }
626 StateChangeType::NavigationChanged => true,
627 StateChangeType::FoldingChanged
629 | StateChangeType::StyleChanged
630 | StateChangeType::DecorationsChanged
631 | StateChangeType::DiagnosticsChanged
632 | StateChangeType::SymbolsChanged => true,
633 };
634
635 if changed {
636 if matches!(change_type, StateChangeType::DocumentModified) {
637 let is_modified = !self.executor.is_clean();
638 let delta = self.executor.take_last_text_delta().map(Arc::new);
639 if let Some(ref delta) = delta {
640 self.bookmarks.apply_delta(delta);
641 self.marks.apply_delta(delta);
642 self.jump_list.apply_delta(delta);
643 }
644 self.last_text_delta = delta.clone();
645 self.mark_modified_internal(change_type, Some(is_modified), delta);
646 } else {
647 self.mark_modified_internal(change_type, None, None);
648 }
649 }
650 }
651
652 Ok(result)
653 }
654
655 fn change_type_for_command(command: &Command) -> Option<StateChangeType> {
656 match command {
657 Command::Edit(EditCommand::Delete { length: 0, .. }) => None,
658 Command::Edit(EditCommand::Replace {
659 length: 0, text, ..
660 }) if text.is_empty() => None,
661 Command::Edit(EditCommand::EndUndoGroup) => None,
662 Command::Edit(_) => Some(StateChangeType::DocumentModified),
663 Command::Cursor(
664 CursorCommand::MoveTo { .. }
665 | CursorCommand::MoveBy { .. }
666 | CursorCommand::MoveVisualBy { .. }
667 | CursorCommand::MoveToVisual { .. }
668 | CursorCommand::MoveToLineStart
669 | CursorCommand::MoveToLineEnd
670 | CursorCommand::MoveToVisualLineStart
671 | CursorCommand::MoveToVisualLineEnd
672 | CursorCommand::MoveGraphemeLeft
673 | CursorCommand::MoveGraphemeRight
674 | CursorCommand::MoveWordLeft
675 | CursorCommand::MoveWordRight
676 | CursorCommand::MoveToMatchingBracket,
677 ) => Some(StateChangeType::CursorMoved),
678 Command::Cursor(
679 CursorCommand::SetSelection { .. }
680 | CursorCommand::ExtendSelection { .. }
681 | CursorCommand::ClearSelection
682 | CursorCommand::SetSelections { .. }
683 | CursorCommand::ClearSecondarySelections
684 | CursorCommand::SetRectSelection { .. }
685 | CursorCommand::SelectLine
686 | CursorCommand::SelectWord
687 | CursorCommand::ExpandSelection
688 | CursorCommand::ExpandSelectionBy { .. }
689 | CursorCommand::SnippetNextPlaceholder
690 | CursorCommand::SnippetPrevPlaceholder
691 | CursorCommand::AddCursorAbove
692 | CursorCommand::AddCursorBelow
693 | CursorCommand::AddNextOccurrence { .. }
694 | CursorCommand::AddAllOccurrences { .. }
695 | CursorCommand::FindNext { .. }
696 | CursorCommand::FindPrev { .. },
697 ) => Some(StateChangeType::SelectionChanged),
698 Command::View(ViewCommand::ScrollTo { .. } | ViewCommand::GetViewport { .. }) => None,
703 Command::View(_) => Some(StateChangeType::ViewportChanged),
704 Command::Style(
705 StyleCommand::AddStyle { .. }
706 | StyleCommand::RemoveStyle { .. }
707 | StyleCommand::UpdateBracketMatchHighlights
708 | StyleCommand::ClearBracketMatchHighlights,
709 ) => Some(StateChangeType::StyleChanged),
710 Command::Style(
711 StyleCommand::Fold { .. } | StyleCommand::Unfold { .. } | StyleCommand::UnfoldAll,
712 ) => Some(StateChangeType::FoldingChanged),
713 }
714 }
715
716 pub fn version(&self) -> u64 {
718 self.state_version
719 }
720
721 pub fn set_viewport_height(&mut self, height: usize) {
723 self.viewport_height = Some(height);
724 }
725
726 pub fn set_scroll_top(&mut self, scroll_top: usize) {
728 let old_scroll = self.scroll_top;
729 self.scroll_top = scroll_top;
730
731 if old_scroll != scroll_top {
732 self.notify_change(StateChangeType::ViewportChanged);
733 }
734 }
735
736 pub fn set_scroll_sub_row_offset(&mut self, sub_row_offset: u16) {
738 let old = self.scroll_sub_row_offset;
739 self.scroll_sub_row_offset = sub_row_offset;
740 if old != sub_row_offset {
741 self.notify_change(StateChangeType::ViewportChanged);
742 }
743 }
744
745 pub fn set_overscan_rows(&mut self, overscan_rows: usize) {
747 let old = self.overscan_rows;
748 self.overscan_rows = overscan_rows;
749 if old != overscan_rows {
750 self.notify_change(StateChangeType::ViewportChanged);
751 }
752 }
753
754 pub fn set_smooth_scroll_state(&mut self, state: SmoothScrollState) {
756 let mut changed = false;
757 if self.scroll_top != state.top_visual_row {
758 self.scroll_top = state.top_visual_row;
759 changed = true;
760 }
761 if self.scroll_sub_row_offset != state.sub_row_offset {
762 self.scroll_sub_row_offset = state.sub_row_offset;
763 changed = true;
764 }
765 if self.overscan_rows != state.overscan_rows {
766 self.overscan_rows = state.overscan_rows;
767 changed = true;
768 }
769 if changed {
770 self.notify_change(StateChangeType::ViewportChanged);
771 }
772 }
773
774 pub fn get_smooth_scroll_state(&self) -> SmoothScrollState {
776 SmoothScrollState {
777 top_visual_row: self.scroll_top,
778 sub_row_offset: self.scroll_sub_row_offset,
779 overscan_rows: self.overscan_rows,
780 }
781 }
782
783 pub fn get_full_state(&self) -> EditorState {
785 EditorState {
786 document: self.get_document_state(),
787 cursor: self.get_cursor_state(),
788 viewport: self.get_viewport_state(),
789 undo_redo: self.get_undo_redo_state(),
790 folding: self.get_folding_state(),
791 diagnostics: self.get_diagnostics_state(),
792 decorations: self.get_decorations_state(),
793 style: self.get_style_state(),
794 }
795 }
796
797 pub fn get_document_state(&self) -> DocumentState {
799 let editor = self.executor.editor();
800 DocumentState {
801 line_count: editor.line_count(),
802 char_count: editor.char_count(),
803 byte_count: editor.get_text().len(),
804 is_modified: self.is_modified,
805 version: self.state_version,
806 }
807 }
808
809 pub fn get_cursor_state(&self) -> CursorState {
811 let editor = self.executor.editor();
812 let mut selections: Vec<Selection> =
813 Vec::with_capacity(1 + editor.secondary_selections().len());
814
815 let primary = editor.selection().cloned().unwrap_or(Selection {
816 start: editor.cursor_position(),
817 end: editor.cursor_position(),
818 direction: SelectionDirection::Forward,
819 });
820 selections.push(primary);
821 selections.extend(editor.secondary_selections().iter().cloned());
822
823 let (selections, primary_selection_index) =
824 crate::selection_set::normalize_selections(selections, 0);
825 let primary = selections
826 .get(primary_selection_index)
827 .cloned()
828 .unwrap_or(Selection {
829 start: editor.cursor_position(),
830 end: editor.cursor_position(),
831 direction: SelectionDirection::Forward,
832 });
833
834 let position = primary.end;
835 let offset = editor
836 .line_index()
837 .position_to_char_offset(position.line, position.column);
838
839 let selection = if primary.start == primary.end {
840 None
841 } else {
842 Some(primary)
843 };
844
845 let multi_cursors: Vec<Position> = selections
846 .iter()
847 .enumerate()
848 .filter_map(|(idx, sel)| {
849 if idx == primary_selection_index {
850 None
851 } else {
852 Some(sel.end)
853 }
854 })
855 .collect();
856
857 CursorState {
858 position,
859 offset,
860 multi_cursors,
861 selection,
862 selections,
863 primary_selection_index,
864 }
865 }
866
867 pub fn get_viewport_state(&self) -> ViewportState {
869 let editor = self.executor.editor();
870 let total_visual_lines = editor.visual_line_count();
871 let clamped_top = self.scroll_top.min(total_visual_lines);
872 let visible_end = if let Some(height) = self.viewport_height {
873 clamped_top.saturating_add(height)
874 } else {
875 total_visual_lines
876 };
877 let visible_lines = clamped_top..visible_end.min(total_visual_lines);
878 let prefetch_start = visible_lines.start.saturating_sub(self.overscan_rows);
879 let prefetch_end = visible_lines
880 .end
881 .saturating_add(self.overscan_rows)
882 .min(total_visual_lines);
883
884 ViewportState {
885 width: editor.viewport_width(),
886 height: self.viewport_height,
887 scroll_top: clamped_top,
888 sub_row_offset: self.scroll_sub_row_offset,
889 overscan_rows: self.overscan_rows,
890 visible_lines,
891 prefetch_lines: prefetch_start..prefetch_end,
892 total_visual_lines,
893 }
894 }
895
896 pub fn get_undo_redo_state(&self) -> UndoRedoState {
898 UndoRedoState {
899 can_undo: self.executor.can_undo(),
900 can_redo: self.executor.can_redo(),
901 undo_depth: self.executor.undo_depth(),
902 redo_depth: self.executor.redo_depth(),
903 redo_branch_count: self.executor.redo_branch_count(),
904 selected_redo_branch_index: self.executor.selected_redo_branch_index(),
905 current_change_group: self.executor.current_change_group(),
906 }
907 }
908
909 pub fn get_folding_state(&self) -> FoldingState {
911 let editor = self.executor.editor();
912 let regions = editor.folding_manager().regions().to_vec();
913 let collapsed_line_count = editor.folding_manager().collapsed_hidden_line_count();
916
917 let visible_logical_lines = editor.line_count().saturating_sub(collapsed_line_count);
918
919 FoldingState {
920 regions,
921 collapsed_line_count,
922 visible_logical_lines,
923 total_visual_lines: editor.visual_line_count(),
924 }
925 }
926
927 pub fn get_style_state(&self) -> StyleState {
929 let editor = self.executor.editor();
930 let layered_count: usize = editor.style_layers().values().map(|t| t.len()).sum();
931 StyleState {
932 style_count: editor.interval_tree().len() + layered_count,
933 }
934 }
935
936 pub fn get_diagnostics_state(&self) -> DiagnosticsState {
938 let editor = self.executor.editor();
939 DiagnosticsState {
940 diagnostics_count: editor.diagnostics().len(),
941 }
942 }
943
944 pub fn get_decorations_state(&self) -> DecorationsState {
946 let editor = self.executor.editor();
947 let decoration_count: usize = editor.decorations().values().map(|d| d.len()).sum();
948 DecorationsState {
949 layer_count: editor.decorations().len(),
950 decoration_count,
951 }
952 }
953
954 pub fn get_styles_in_range(&self, start: usize, end: usize) -> Vec<(usize, usize, StyleId)> {
956 let editor = self.executor.editor();
957 let mut result: Vec<(usize, usize, StyleId)> = editor
958 .interval_tree()
959 .query_range(start, end)
960 .iter()
961 .map(|interval| (interval.start, interval.end, interval.style_id))
962 .collect();
963
964 for tree in editor.style_layers().values() {
965 result.extend(
966 tree.query_range(start, end)
967 .iter()
968 .map(|interval| (interval.start, interval.end, interval.style_id)),
969 );
970 }
971
972 result.sort_unstable_by_key(|(s, e, id)| (*s, *e, *id));
973 result
974 }
975
976 pub fn get_styles_at(&self, offset: usize) -> Vec<StyleId> {
978 let editor = self.executor.editor();
979 let mut styles: Vec<StyleId> = editor
980 .interval_tree()
981 .query_point(offset)
982 .iter()
983 .map(|interval| interval.style_id)
984 .collect();
985
986 for tree in editor.style_layers().values() {
987 styles.extend(
988 tree.query_point(offset)
989 .iter()
990 .map(|interval| interval.style_id),
991 );
992 }
993
994 styles.sort_unstable();
995 styles.dedup();
996 styles
997 }
998
999 pub fn replace_style_layer(&mut self, layer: StyleLayerId, intervals: Vec<Interval>) {
1004 self.executor
1005 .editor_mut()
1006 .replace_style_layer(layer, intervals);
1007 self.mark_modified(StateChangeType::StyleChanged);
1008 }
1009
1010 pub fn clear_style_layer(&mut self, layer: StyleLayerId) {
1012 self.executor.editor_mut().clear_style_layer(layer);
1013 self.mark_modified(StateChangeType::StyleChanged);
1014 }
1015
1016 pub fn replace_diagnostics(&mut self, diagnostics: Vec<Diagnostic>) {
1018 self.executor.editor_mut().replace_diagnostics(diagnostics);
1019 self.mark_modified(StateChangeType::DiagnosticsChanged);
1020 }
1021
1022 pub fn clear_diagnostics(&mut self) {
1024 self.executor.editor_mut().clear_diagnostics();
1025 self.mark_modified(StateChangeType::DiagnosticsChanged);
1026 }
1027
1028 pub fn replace_document_symbols(&mut self, symbols: crate::DocumentOutline) {
1030 self.executor.editor_mut().replace_document_symbols(symbols);
1031 self.mark_modified(StateChangeType::SymbolsChanged);
1032 }
1033
1034 pub fn clear_document_symbols(&mut self) {
1036 self.executor.editor_mut().clear_document_symbols();
1037 self.mark_modified(StateChangeType::SymbolsChanged);
1038 }
1039
1040 pub fn replace_decorations(&mut self, layer: DecorationLayerId, decorations: Vec<Decoration>) {
1042 self.executor
1043 .editor_mut()
1044 .replace_decorations(layer, decorations);
1045 self.mark_modified(StateChangeType::DecorationsChanged);
1046 }
1047
1048 pub fn clear_decorations(&mut self, layer: DecorationLayerId) {
1050 self.executor.editor_mut().clear_decorations(layer);
1051 self.mark_modified(StateChangeType::DecorationsChanged);
1052 }
1053
1054 pub fn replace_folding_regions(&mut self, regions: Vec<FoldRegion>, preserve_collapsed: bool) {
1059 self.executor
1060 .editor_mut()
1061 .replace_folding_regions(regions, preserve_collapsed);
1062 self.mark_modified(StateChangeType::FoldingChanged);
1063 }
1064
1065 pub fn clear_folding_regions(&mut self) {
1067 self.executor.editor_mut().clear_derived_folding_regions();
1068 self.mark_modified(StateChangeType::FoldingChanged);
1069 }
1070
1071 pub fn toggle_fold_at_current_line(&mut self) -> bool {
1073 let line = self.executor.editor().cursor_position().line;
1074 let toggled = self.executor.editor_mut().toggle_fold_at_line(line);
1075 if toggled {
1076 self.mark_modified(StateChangeType::FoldingChanged);
1077 }
1078 toggled
1079 }
1080
1081 pub fn expand_all_folds(&mut self) {
1083 let had_collapsed = self
1084 .executor
1085 .editor()
1086 .folding_manager()
1087 .regions()
1088 .iter()
1089 .any(|region| region.is_collapsed);
1090 self.executor.editor_mut().expand_all_folds();
1091 if had_collapsed {
1092 self.mark_modified(StateChangeType::FoldingChanged);
1093 }
1094 }
1095
1096 pub fn apply_processing_edits<I>(&mut self, edits: I)
1098 where
1099 I: IntoIterator<Item = ProcessingEdit>,
1100 {
1101 for edit in edits {
1102 match edit {
1103 ProcessingEdit::ReplaceStyleLayer { layer, intervals } => {
1104 self.replace_style_layer(layer, intervals);
1105 }
1106 ProcessingEdit::ClearStyleLayer { layer } => {
1107 self.clear_style_layer(layer);
1108 }
1109 ProcessingEdit::ReplaceFoldingRegions {
1110 regions,
1111 preserve_collapsed,
1112 } => {
1113 self.replace_folding_regions(regions, preserve_collapsed);
1114 }
1115 ProcessingEdit::ClearFoldingRegions => {
1116 self.clear_folding_regions();
1117 }
1118 ProcessingEdit::ReplaceDiagnostics { diagnostics } => {
1119 self.replace_diagnostics(diagnostics);
1120 }
1121 ProcessingEdit::ClearDiagnostics => {
1122 self.clear_diagnostics();
1123 }
1124 ProcessingEdit::ReplaceDecorations { layer, decorations } => {
1125 self.replace_decorations(layer, decorations);
1126 }
1127 ProcessingEdit::ClearDecorations { layer } => {
1128 self.clear_decorations(layer);
1129 }
1130 ProcessingEdit::ReplaceDocumentSymbols { symbols } => {
1131 self.replace_document_symbols(symbols);
1132 }
1133 ProcessingEdit::ClearDocumentSymbols => {
1134 self.clear_document_symbols();
1135 }
1136 }
1137 }
1138 }
1139
1140 pub fn apply_processor<P>(&mut self, processor: &mut P) -> Result<(), P::Error>
1142 where
1143 P: DocumentProcessor,
1144 {
1145 let edits = processor.process(self)?;
1146 self.apply_processing_edits(edits);
1147 Ok(())
1148 }
1149
1150 pub fn get_viewport_content(&self, start_row: usize, count: usize) -> HeadlessGrid {
1152 let editor = self.executor.editor();
1153 let text = editor.get_text();
1154 let generator = crate::SnapshotGenerator::from_text_with_layout_options(
1155 &text,
1156 editor.viewport_width(),
1157 editor.layout_engine().tab_width(),
1158 editor.layout_engine().wrap_mode(),
1159 editor.layout_engine().wrap_indent(),
1160 );
1161 generator.get_headless_grid(start_row, count)
1162 }
1163
1164 pub fn get_viewport_content_styled(
1169 &self,
1170 start_visual_row: usize,
1171 count: usize,
1172 ) -> HeadlessGrid {
1173 self.executor
1174 .editor()
1175 .get_headless_grid_styled(start_visual_row, count)
1176 }
1177
1178 pub fn get_minimap_content(&self, start_visual_row: usize, count: usize) -> crate::MinimapGrid {
1180 self.executor
1181 .editor()
1182 .get_minimap_grid(start_visual_row, count)
1183 }
1184
1185 pub fn get_viewport_content_composed(
1190 &self,
1191 start_visual_row: usize,
1192 count: usize,
1193 ) -> ComposedGrid {
1194 self.executor
1195 .editor()
1196 .get_headless_grid_composed(start_visual_row, count)
1197 }
1198
1199 pub fn total_visual_lines(&self) -> usize {
1201 self.executor.editor().visual_line_count()
1202 }
1203
1204 pub fn visual_to_logical_line(&self, visual_row: usize) -> (usize, usize) {
1206 self.executor.editor().visual_to_logical_line(visual_row)
1207 }
1208
1209 pub fn logical_position_to_visual(&self, line: usize, column: usize) -> Option<(usize, usize)> {
1211 self.executor
1212 .editor()
1213 .logical_position_to_visual(line, column)
1214 }
1215
1216 pub fn visual_position_to_logical(
1218 &self,
1219 visual_row: usize,
1220 x_cells: usize,
1221 ) -> Option<Position> {
1222 self.executor
1223 .editor()
1224 .visual_position_to_logical(visual_row, x_cells)
1225 }
1226
1227 pub fn subscribe<F>(&mut self, callback: F)
1229 where
1230 F: FnMut(&StateChange) + Send + 'static,
1231 {
1232 self.callbacks.push(Box::new(callback));
1233 }
1234
1235 pub fn has_changed_since(&self, version: u64) -> bool {
1237 self.state_version > version
1238 }
1239
1240 pub fn mark_modified(&mut self, change_type: StateChangeType) {
1242 self.mark_modified_internal(change_type, None, None);
1243 }
1244
1245 fn mark_modified_internal(
1246 &mut self,
1247 change_type: StateChangeType,
1248 is_modified_override: Option<bool>,
1249 delta: Option<Arc<TextDelta>>,
1250 ) {
1251 let old_version = self.state_version;
1252 self.state_version += 1;
1253
1254 if matches!(change_type, StateChangeType::DocumentModified) {
1256 self.is_modified = is_modified_override.unwrap_or(true);
1257 }
1258
1259 let mut change = StateChange::new(change_type, old_version, self.state_version);
1260 if let Some(delta) = delta {
1261 change = change.with_text_delta(delta);
1262 }
1263 self.notify_callbacks(&change);
1264 }
1265
1266 pub fn mark_saved(&mut self) {
1268 self.executor.mark_clean();
1269 self.is_modified = false;
1270 }
1271
1272 pub fn undo_history_snapshot(&self) -> UndoHistorySnapshot {
1274 self.executor.undo_history_snapshot()
1275 }
1276
1277 pub fn restore_undo_history(
1283 &mut self,
1284 snapshot: UndoHistorySnapshot,
1285 ) -> Result<(), UndoHistoryRestoreError> {
1286 self.last_text_delta = None;
1287 self.executor.restore_undo_history(snapshot)?;
1288 self.is_modified = !self.executor.is_clean();
1289 Ok(())
1290 }
1291
1292 fn notify_change(&mut self, change_type: StateChangeType) {
1294 let change = StateChange::new(change_type, self.state_version, self.state_version);
1295 self.notify_callbacks(&change);
1296 }
1297
1298 pub fn last_text_delta(&self) -> Option<&TextDelta> {
1300 self.last_text_delta.as_deref()
1301 }
1302
1303 pub fn take_last_text_delta(&mut self) -> Option<Arc<TextDelta>> {
1305 self.last_text_delta.take()
1306 }
1307
1308 pub fn toggle_bookmark_at_cursor_line(&mut self) -> bool {
1313 let line = self.executor.editor().cursor_position().line;
1314 let line_start = self
1315 .executor
1316 .editor()
1317 .line_index()
1318 .position_to_char_offset(line, 0);
1319 let added = self.bookmarks.toggle_line_start(line_start);
1320 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1321 added
1322 }
1323
1324 pub fn bookmark_lines(&self) -> Vec<usize> {
1326 self.bookmarks
1327 .line_numbers(self.executor.editor().line_index())
1328 }
1329
1330 pub fn clear_bookmarks(&mut self) {
1332 self.bookmarks.clear();
1333 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1334 }
1335
1336 pub fn goto_next_bookmark(&mut self) -> Result<Option<Position>, CommandError> {
1340 let line = self.executor.editor().cursor_position().line;
1341 let current_line_start = self
1342 .executor
1343 .editor()
1344 .line_index()
1345 .position_to_char_offset(line, 0);
1346
1347 let Some(target) = self.bookmarks.next_after_line_start(current_line_start) else {
1348 return Ok(None);
1349 };
1350
1351 let (line, column) = self
1352 .executor
1353 .editor()
1354 .line_index()
1355 .char_offset_to_position(target.offset);
1356 self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1357 let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1358 Ok(Some(Position::new(line, column)))
1359 }
1360
1361 pub fn goto_prev_bookmark(&mut self) -> Result<Option<Position>, CommandError> {
1365 let line = self.executor.editor().cursor_position().line;
1366 let current_line_start = self
1367 .executor
1368 .editor()
1369 .line_index()
1370 .position_to_char_offset(line, 0);
1371
1372 let Some(target) = self.bookmarks.prev_before_line_start(current_line_start) else {
1373 return Ok(None);
1374 };
1375
1376 let (line, column) = self
1377 .executor
1378 .editor()
1379 .line_index()
1380 .char_offset_to_position(target.offset);
1381 self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1382 let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1383 Ok(Some(Position::new(line, column)))
1384 }
1385
1386 pub fn set_mark_at_cursor(&mut self, name: String) -> Result<(), CommandError> {
1388 if name.trim().is_empty() {
1389 return Err(CommandError::Other("Mark name cannot be empty".to_string()));
1390 }
1391
1392 let pos = self.executor.editor().cursor_position();
1393 let offset = self
1394 .executor
1395 .editor()
1396 .line_index()
1397 .position_to_char_offset(pos.line, pos.column);
1398 self.marks.set(name, offset);
1399 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1400 Ok(())
1401 }
1402
1403 pub fn goto_mark(&mut self, name: &str) -> Result<Option<Position>, CommandError> {
1407 let Some(anchor) = self.marks.get(name) else {
1408 return Ok(None);
1409 };
1410 let (line, column) = self
1411 .executor
1412 .editor()
1413 .line_index()
1414 .char_offset_to_position(anchor.offset);
1415 self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1416 let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1417 Ok(Some(Position::new(line, column)))
1418 }
1419
1420 pub fn clear_mark(&mut self, name: &str) -> bool {
1424 let existed = self.marks.remove(name);
1425 if existed {
1426 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1427 }
1428 existed
1429 }
1430
1431 pub fn mark_names(&self) -> Vec<String> {
1433 self.marks.names()
1434 }
1435
1436 pub fn clear_all_marks(&mut self) {
1438 self.marks.clear();
1439 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1440 }
1441
1442 pub fn push_jump_location(&mut self) {
1447 let pos = self.executor.editor().cursor_position();
1448 let offset = self
1449 .executor
1450 .editor()
1451 .line_index()
1452 .position_to_char_offset(pos.line, pos.column);
1453 self.jump_list.record(offset);
1454 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1455 }
1456
1457 pub fn jump_back(&mut self) -> Result<Option<Position>, CommandError> {
1461 let pos = self.executor.editor().cursor_position();
1462 let current_offset = self
1463 .executor
1464 .editor()
1465 .line_index()
1466 .position_to_char_offset(pos.line, pos.column);
1467
1468 let Some(target) = self.jump_list.back(current_offset) else {
1469 return Ok(None);
1470 };
1471
1472 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1473
1474 let (line, column) = self
1475 .executor
1476 .editor()
1477 .line_index()
1478 .char_offset_to_position(target.offset);
1479 self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1480 let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1481 Ok(Some(Position::new(line, column)))
1482 }
1483
1484 pub fn jump_forward(&mut self) -> Result<Option<Position>, CommandError> {
1488 let pos = self.executor.editor().cursor_position();
1489 let current_offset = self
1490 .executor
1491 .editor()
1492 .line_index()
1493 .position_to_char_offset(pos.line, pos.column);
1494
1495 let Some(target) = self.jump_list.forward(current_offset) else {
1496 return Ok(None);
1497 };
1498
1499 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1500
1501 let (line, column) = self
1502 .executor
1503 .editor()
1504 .line_index()
1505 .char_offset_to_position(target.offset);
1506 self.execute(Command::Cursor(CursorCommand::MoveTo { line, column }))?;
1507 let _ = self.execute(Command::Cursor(CursorCommand::ClearSelection))?;
1508 Ok(Some(Position::new(line, column)))
1509 }
1510
1511 pub fn clear_jump_list(&mut self) {
1513 self.jump_list.clear();
1514 self.mark_modified_internal(StateChangeType::NavigationChanged, None, None);
1515 }
1516
1517 fn notify_callbacks(&mut self, change: &StateChange) {
1519 for callback in &mut self.callbacks {
1520 callback(change);
1521 }
1522 }
1523}
1524
1525#[cfg(test)]
1526mod tests {
1527 use super::*;
1528
1529 #[test]
1530 fn test_document_state() {
1531 let manager = EditorStateManager::new("Hello World\nLine 2", 80);
1532 let doc_state = manager.get_document_state();
1533
1534 assert_eq!(doc_state.line_count, 2);
1535 assert_eq!(doc_state.char_count, 18); assert!(!doc_state.is_modified);
1537 assert_eq!(doc_state.version, 0);
1538 }
1539
1540 #[test]
1541 fn test_cursor_state() {
1542 let manager = EditorStateManager::new("Hello World", 80);
1543 let cursor_state = manager.get_cursor_state();
1544
1545 assert_eq!(cursor_state.position, Position::new(0, 0));
1546 assert_eq!(cursor_state.offset, 0);
1547 assert!(cursor_state.selection.is_none());
1548 }
1549
1550 #[test]
1551 fn test_viewport_state() {
1552 let mut manager = EditorStateManager::new("Line 1\nLine 2\nLine 3", 80);
1553 manager.set_viewport_height(10);
1554 manager.set_scroll_top(1);
1555
1556 let viewport_state = manager.get_viewport_state();
1557
1558 assert_eq!(viewport_state.width, 80);
1559 assert_eq!(viewport_state.height, Some(10));
1560 assert_eq!(viewport_state.scroll_top, 1);
1561 assert_eq!(viewport_state.visible_lines, 1..3);
1562 }
1563
1564 #[test]
1565 fn test_folding_state() {
1566 let manager = EditorStateManager::new("Line 1\nLine 2\nLine 3", 80);
1567 let folding_state = manager.get_folding_state();
1568
1569 assert_eq!(folding_state.regions.len(), 0);
1570 assert_eq!(folding_state.collapsed_line_count, 0);
1571 assert_eq!(folding_state.visible_logical_lines, 3);
1572 }
1573
1574 #[test]
1575 fn test_style_state() {
1576 let manager = EditorStateManager::new("Hello World", 80);
1577 let style_state = manager.get_style_state();
1578
1579 assert_eq!(style_state.style_count, 0);
1580 }
1581
1582 #[test]
1583 fn test_full_state() {
1584 let manager = EditorStateManager::new("Test", 80);
1585 let full_state = manager.get_full_state();
1586
1587 assert_eq!(full_state.document.line_count, 1);
1588 assert_eq!(full_state.cursor.position, Position::new(0, 0));
1589 assert_eq!(full_state.viewport.width, 80);
1590 }
1591
1592 #[test]
1593 fn test_version_tracking() {
1594 let mut manager = EditorStateManager::new("Test", 80);
1595
1596 assert_eq!(manager.version(), 0);
1597 assert!(!manager.has_changed_since(0));
1598
1599 manager.mark_modified(StateChangeType::DocumentModified);
1600
1601 assert_eq!(manager.version(), 1);
1602 assert!(manager.has_changed_since(0));
1603 assert!(!manager.has_changed_since(1));
1604 }
1605
1606 #[test]
1607 fn test_modification_tracking() {
1608 let mut manager = EditorStateManager::new("Test", 80);
1609
1610 assert!(!manager.get_document_state().is_modified);
1611
1612 manager.mark_modified(StateChangeType::DocumentModified);
1613 assert!(manager.get_document_state().is_modified);
1614
1615 manager.mark_saved();
1616 assert!(!manager.get_document_state().is_modified);
1617 }
1618
1619 #[test]
1620 fn test_undo_redo_state_and_dirty_tracking() {
1621 let mut manager = EditorStateManager::empty(80);
1622
1623 let state = manager.get_undo_redo_state();
1624 assert!(!state.can_undo);
1625 assert!(!state.can_redo);
1626
1627 manager
1628 .execute(Command::Edit(EditCommand::InsertText {
1629 text: "abc".to_string(),
1630 }))
1631 .unwrap();
1632
1633 assert!(manager.get_document_state().is_modified);
1634 let state = manager.get_undo_redo_state();
1635 assert!(state.can_undo);
1636 assert!(!state.can_redo);
1637 assert_eq!(state.undo_depth, 1);
1638
1639 manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1640 assert!(!manager.get_document_state().is_modified);
1641 let state = manager.get_undo_redo_state();
1642 assert!(!state.can_undo);
1643 assert!(state.can_redo);
1644
1645 manager.execute(Command::Edit(EditCommand::Redo)).unwrap();
1646 assert!(manager.get_document_state().is_modified);
1647 let state = manager.get_undo_redo_state();
1648 assert!(state.can_undo);
1649 assert!(!state.can_redo);
1650 }
1651
1652 #[test]
1653 fn test_insert_tab_undo_restores_clean_state() {
1654 let mut manager = EditorStateManager::empty(80);
1655 assert!(!manager.get_document_state().is_modified);
1656
1657 manager
1658 .execute(Command::Edit(EditCommand::InsertTab))
1659 .unwrap();
1660 assert!(manager.get_document_state().is_modified);
1661
1662 manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1663 assert!(!manager.get_document_state().is_modified);
1664 }
1665
1666 #[test]
1667 fn test_insert_tab_spaces_undo_restores_clean_state() {
1668 let mut manager = EditorStateManager::empty(80);
1669 manager
1670 .execute(Command::View(ViewCommand::SetTabKeyBehavior {
1671 behavior: crate::TabKeyBehavior::Spaces,
1672 }))
1673 .unwrap();
1674
1675 manager
1676 .execute(Command::Edit(EditCommand::InsertTab))
1677 .unwrap();
1678 assert!(manager.get_document_state().is_modified);
1679
1680 manager.execute(Command::Edit(EditCommand::Undo)).unwrap();
1681 assert!(!manager.get_document_state().is_modified);
1682 }
1683
1684 #[test]
1685 fn test_state_change_callback() {
1686 use std::sync::{Arc, Mutex};
1687
1688 let mut manager = EditorStateManager::new("Test", 80);
1689
1690 let callback_called = Arc::new(Mutex::new(false));
1691 let callback_called_clone = callback_called.clone();
1692
1693 manager.subscribe(move |_change| {
1694 *callback_called_clone.lock().unwrap() = true;
1695 });
1696
1697 manager.mark_modified(StateChangeType::CursorMoved);
1698
1699 assert!(*callback_called.lock().unwrap());
1701 }
1702
1703 #[test]
1704 fn test_execute_cursor_noop_does_not_bump_version() {
1705 let mut manager = EditorStateManager::new("A", 80);
1706 assert_eq!(manager.version(), 0);
1707
1708 manager
1710 .execute(Command::Cursor(CursorCommand::MoveBy {
1711 delta_line: 0,
1712 delta_column: -1,
1713 }))
1714 .unwrap();
1715 assert_eq!(manager.editor().cursor_position(), Position::new(0, 0));
1716 assert_eq!(manager.version(), 0);
1717
1718 manager
1720 .execute(Command::Cursor(CursorCommand::MoveTo {
1721 line: 0,
1722 column: usize::MAX,
1723 }))
1724 .unwrap();
1725 assert_eq!(manager.editor().cursor_position(), Position::new(0, 1));
1726 assert_eq!(manager.version(), 1);
1727
1728 let version_before = manager.version();
1730 manager
1731 .execute(Command::Cursor(CursorCommand::MoveBy {
1732 delta_line: 0,
1733 delta_column: 1,
1734 }))
1735 .unwrap();
1736 assert_eq!(manager.editor().cursor_position(), Position::new(0, 1));
1737 assert_eq!(manager.version(), version_before);
1738 }
1739
1740 #[test]
1741 fn test_viewport_height() {
1742 let mut manager = EditorStateManager::new("Test", 80);
1743
1744 assert_eq!(manager.get_viewport_state().height, None);
1745
1746 manager.set_viewport_height(20);
1747 assert_eq!(manager.get_viewport_state().height, Some(20));
1748 }
1749
1750 #[test]
1751 fn test_scroll_position() {
1752 let mut manager = EditorStateManager::new("Line 1\nLine 2\nLine 3\nLine 4", 80);
1753 manager.set_viewport_height(2);
1754
1755 assert_eq!(manager.get_viewport_state().scroll_top, 0);
1756 assert_eq!(manager.get_viewport_state().visible_lines, 0..2);
1757
1758 manager.set_scroll_top(2);
1759 assert_eq!(manager.get_viewport_state().scroll_top, 2);
1760 assert_eq!(manager.get_viewport_state().visible_lines, 2..4);
1761 }
1762
1763 #[test]
1764 fn test_get_styles() {
1765 let mut manager = EditorStateManager::new("Hello World", 80);
1766
1767 manager
1769 .editor_mut()
1770 .insert_style_interval(crate::intervals::Interval::new(0, 5, 1));
1771
1772 let styles = manager.get_styles_in_range(0, 10);
1773 assert_eq!(styles.len(), 1);
1774 assert_eq!(styles[0], (0, 5, 1));
1775
1776 let styles_at = manager.get_styles_at(3);
1777 assert_eq!(styles_at.len(), 1);
1778 assert_eq!(styles_at[0], 1);
1779 }
1780
1781 #[test]
1782 fn test_replace_style_layer_affects_queries() {
1783 let mut manager = EditorStateManager::new("Hello", 80);
1784
1785 manager.replace_style_layer(
1786 StyleLayerId::SEMANTIC_TOKENS,
1787 vec![Interval::new(0, 1, 100)],
1788 );
1789
1790 assert_eq!(manager.get_styles_at(0), vec![100]);
1791
1792 manager
1794 .editor_mut()
1795 .insert_style_interval(Interval::new(0, 5, 1));
1796
1797 assert_eq!(manager.get_styles_at(0), vec![1, 100]);
1798 }
1799
1800 #[test]
1801 fn test_viewport_content_styled_wraps_and_includes_styles() {
1802 let mut manager = EditorStateManager::new("abcdef", 3);
1803
1804 manager.replace_style_layer(StyleLayerId::SIMPLE_SYNTAX, vec![Interval::new(1, 4, 7)]);
1806
1807 let grid = manager.get_viewport_content_styled(0, 10);
1808 assert_eq!(grid.actual_line_count(), 2);
1809
1810 let line0 = &grid.lines[0];
1811 assert_eq!(line0.logical_line_index, 0);
1812 assert!(!line0.is_wrapped_part);
1813 assert_eq!(line0.cells.len(), 3);
1814 assert_eq!(line0.cells[0].ch, 'a');
1815 assert_eq!(line0.cells[1].ch, 'b');
1816 assert_eq!(line0.cells[2].ch, 'c');
1817 assert_eq!(line0.cells[0].styles, Vec::<StyleId>::new());
1818 assert_eq!(line0.cells[1].styles, vec![7]);
1819 assert_eq!(line0.cells[2].styles, vec![7]);
1820
1821 let line1 = &grid.lines[1];
1822 assert_eq!(line1.logical_line_index, 0);
1823 assert!(line1.is_wrapped_part);
1824 assert_eq!(line1.cells.len(), 3);
1825 assert_eq!(line1.cells[0].ch, 'd');
1826 assert_eq!(line1.cells[0].styles, vec![7]);
1827 assert_eq!(line1.cells[1].ch, 'e');
1828 assert_eq!(line1.cells[1].styles, Vec::<StyleId>::new());
1829 }
1830
1831 #[test]
1832 fn test_smooth_scroll_state_and_prefetch_lines() {
1833 let mut manager = EditorStateManager::new("a\nb\nc\nd\n", 80);
1834 manager.set_viewport_height(2);
1835 manager.set_scroll_top(1);
1836 manager.set_scroll_sub_row_offset(123);
1837 manager.set_overscan_rows(2);
1838
1839 let smooth = manager.get_smooth_scroll_state();
1840 assert_eq!(
1841 smooth,
1842 SmoothScrollState {
1843 top_visual_row: 1,
1844 sub_row_offset: 123,
1845 overscan_rows: 2
1846 }
1847 );
1848
1849 let viewport = manager.get_viewport_state();
1850 assert_eq!(viewport.visible_lines, 1..3);
1851 assert_eq!(viewport.sub_row_offset, 123);
1852 assert_eq!(viewport.overscan_rows, 2);
1853 assert_eq!(viewport.prefetch_lines, 0..5);
1854 assert_eq!(viewport.total_visual_lines, 5);
1855 }
1856
1857 #[test]
1858 fn test_minimap_content_returns_lightweight_summary() {
1859 let mut manager = EditorStateManager::new("abc def\n", 80);
1860 manager.replace_style_layer(StyleLayerId::SIMPLE_SYNTAX, vec![Interval::new(0, 3, 9)]);
1861
1862 let minimap = manager.get_minimap_content(0, 1);
1863 assert_eq!(minimap.actual_line_count(), 1);
1864 let line = &minimap.lines[0];
1865 assert_eq!(line.logical_line_index, 0);
1866 assert_eq!(line.visual_in_logical, 0);
1867 assert_eq!(line.char_offset_start, 0);
1868 assert_eq!(line.char_offset_end, 7);
1869 assert!(line.total_cells >= line.non_whitespace_cells);
1870 assert_eq!(line.dominant_style, Some(9));
1871 assert!(!line.is_fold_placeholder_appended);
1872 }
1873}