1use crate::model::buffer::{Buffer, LineNumber};
2use crate::model::cursor::{Cursor, Cursors};
3use crate::model::document_model::{
4 DocumentCapabilities, DocumentModel, DocumentPosition, ViewportContent, ViewportLine,
5};
6use crate::model::event::{
7 Event, MarginContentData, MarginPositionData, OverlayFace as EventOverlayFace, PopupData,
8 PopupPositionData,
9};
10use crate::model::filesystem::FileSystem;
11use crate::model::marker::{MarkerId, MarkerList};
12use crate::primitives::detected_language::DetectedLanguage;
13use crate::primitives::grammar::GrammarRegistry;
14use crate::primitives::highlight_engine::HighlightEngine;
15use crate::primitives::indent::IndentCalculator;
16use crate::primitives::reference_highlighter::ReferenceHighlighter;
17use crate::primitives::text_property::TextPropertyManager;
18use crate::view::bracket_highlight_overlay::BracketHighlightOverlay;
19use crate::view::conceal::ConcealManager;
20use crate::view::folding::LspFoldRanges;
21use crate::view::margin::{MarginAnnotation, MarginContent, MarginManager, MarginPosition};
22use crate::view::overlay::{Overlay, OverlayFace, OverlayManager, UnderlineStyle};
23use crate::view::popup::{
24 Popup, PopupContent, PopupKind, PopupListItem, PopupManager, PopupPosition,
25};
26use crate::view::reference_highlight_overlay::ReferenceHighlightOverlay;
27use crate::view::soft_break::SoftBreakManager;
28use crate::view::virtual_text::VirtualTextManager;
29use anyhow::Result;
30use ratatui::style::{Color, Style};
31use std::cell::RefCell;
32use std::ops::Range;
33use std::sync::Arc;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub enum DisplacedMarker {
40 Main { id: u64, position: usize },
42 Margin { id: u64, position: usize },
44}
45
46impl DisplacedMarker {
47 pub fn encode(&self) -> (u64, usize) {
49 match self {
50 Self::Main { id, position } => (*id, *position),
51 Self::Margin { id, position } => (*id | (1u64 << 63), *position),
52 }
53 }
54
55 pub fn decode(tagged_id: u64, position: usize) -> Self {
57 if (tagged_id >> 63) == 1 {
58 Self::Margin {
59 id: tagged_id & !(1u64 << 63),
60 position,
61 }
62 } else {
63 Self::Main {
64 id: tagged_id,
65 position,
66 }
67 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum ViewMode {
74 Source,
76 PageView,
79}
80
81#[derive(Debug, Clone)]
92pub struct BufferSettings {
93 pub whitespace: crate::config::WhitespaceVisibility,
96
97 pub use_tabs: bool,
100
101 pub tab_size: usize,
105
106 pub auto_close: bool,
109
110 pub auto_surround: bool,
113
114 pub word_characters: String,
117}
118
119impl Default for BufferSettings {
120 fn default() -> Self {
121 Self {
122 whitespace: crate::config::WhitespaceVisibility::default(),
123 use_tabs: false,
124 tab_size: 4,
125 auto_close: true,
126 auto_surround: true,
127 word_characters: String::new(),
128 }
129 }
130}
131
132pub struct EditorState {
138 pub buffer: Buffer,
140
141 pub highlighter: HighlightEngine,
143
144 pub indent_calculator: RefCell<IndentCalculator>,
146
147 pub overlays: OverlayManager,
149
150 pub marker_list: MarkerList,
152
153 pub virtual_texts: VirtualTextManager,
155
156 pub conceals: ConcealManager,
158
159 pub soft_breaks: SoftBreakManager,
161
162 pub popups: PopupManager,
164
165 pub margins: MarginManager,
167
168 pub primary_cursor_line_number: LineNumber,
171
172 pub mode: String,
174
175 pub text_properties: TextPropertyManager,
178
179 pub show_cursors: bool,
182
183 pub editing_disabled: bool,
187
188 pub scrollable: bool,
192
193 pub buffer_settings: BufferSettings,
196
197 pub reference_highlighter: ReferenceHighlighter,
199
200 pub is_composite_buffer: bool,
202
203 pub debug_highlight_mode: bool,
205
206 pub reference_highlight_overlay: ReferenceHighlightOverlay,
208
209 pub bracket_highlight_overlay: BracketHighlightOverlay,
211
212 pub semantic_tokens: Option<SemanticTokenStore>,
214
215 pub folding_ranges: LspFoldRanges,
219
220 pub language: String,
223
224 pub display_name: String,
229
230 pub line_wrap_cache: crate::view::line_wrap_cache::LineWrapCache,
237
238 pub visual_row_index: crate::view::visual_row_index::VisualRowIndex,
247}
248
249impl EditorState {
250 pub fn apply_language(&mut self, detected: DetectedLanguage) {
257 self.language = detected.name;
258 self.display_name = detected.display_name;
259 self.highlighter = detected.highlighter;
260 if let Some(lang) = &detected.ts_language {
261 self.reference_highlighter.set_language(lang);
262 }
263 }
264
265 fn new_from_buffer(buffer: Buffer) -> Self {
268 let mut marker_list = MarkerList::new();
269 if !buffer.is_empty() {
270 marker_list.adjust_for_insert(0, buffer.len());
271 }
272
273 Self {
274 buffer,
275 highlighter: HighlightEngine::None,
276 indent_calculator: RefCell::new(IndentCalculator::new()),
277 overlays: OverlayManager::new(),
278 marker_list,
279 virtual_texts: VirtualTextManager::new(),
280 conceals: ConcealManager::new(),
281 soft_breaks: SoftBreakManager::new(),
282 popups: PopupManager::new(),
283 margins: MarginManager::new(),
284 primary_cursor_line_number: LineNumber::Absolute(0),
285 mode: "insert".to_string(),
286 text_properties: TextPropertyManager::new(),
287 show_cursors: true,
288 editing_disabled: false,
289 scrollable: true,
290 buffer_settings: BufferSettings::default(),
291 reference_highlighter: ReferenceHighlighter::new(),
292 is_composite_buffer: false,
293 debug_highlight_mode: false,
294 reference_highlight_overlay: ReferenceHighlightOverlay::new(),
295 bracket_highlight_overlay: BracketHighlightOverlay::new(),
296 semantic_tokens: None,
297 folding_ranges: LspFoldRanges::new(),
298 language: "text".to_string(),
299 display_name: "Text".to_string(),
300 line_wrap_cache: crate::view::line_wrap_cache::LineWrapCache::default(),
301 visual_row_index: crate::view::visual_row_index::VisualRowIndex::default(),
302 }
303 }
304
305 pub fn new(
306 _width: u16,
307 _height: u16,
308 large_file_threshold: usize,
309 fs: Arc<dyn FileSystem + Send + Sync>,
310 ) -> Self {
311 Self::new_from_buffer(Buffer::new(large_file_threshold, fs))
312 }
313
314 pub fn new_with_path(
317 large_file_threshold: usize,
318 fs: Arc<dyn FileSystem + Send + Sync>,
319 path: std::path::PathBuf,
320 ) -> Self {
321 Self::new_from_buffer(Buffer::new_with_path(large_file_threshold, fs, path))
322 }
323
324 pub fn set_language_from_name(&mut self, name: &str, registry: &GrammarRegistry) {
328 let detected = DetectedLanguage::from_virtual_name(name, registry);
329 tracing::debug!(
330 "Set highlighter for virtual buffer based on name: {} (backend: {}, language: {})",
331 name,
332 detected.highlighter.backend_name(),
333 detected.name
334 );
335 self.apply_language(detected);
336 }
337
338 pub fn from_file(
343 path: &std::path::Path,
344 _width: u16,
345 _height: u16,
346 large_file_threshold: usize,
347 registry: &GrammarRegistry,
348 fs: Arc<dyn FileSystem + Send + Sync>,
349 ) -> anyhow::Result<Self> {
350 let buffer = Buffer::load_from_file(path, large_file_threshold, fs)?;
351 let first_line = buffer.first_line_lossy();
352 let detected = registry
353 .find_by_path(path, first_line.as_deref())
354 .map(|entry| DetectedLanguage::from_entry(entry, registry))
355 .unwrap_or_else(DetectedLanguage::plain_text);
356 let mut state = Self::new_from_buffer(buffer);
357 state.apply_language(detected);
358 Ok(state)
359 }
360
361 pub fn from_file_with_languages(
369 path: &std::path::Path,
370 _width: u16,
371 _height: u16,
372 large_file_threshold: usize,
373 registry: &GrammarRegistry,
374 languages: &std::collections::HashMap<String, crate::config::LanguageConfig>,
375 fs: Arc<dyn FileSystem + Send + Sync>,
376 ) -> anyhow::Result<Self> {
377 let buffer = Buffer::load_from_file(path, large_file_threshold, fs)?;
378 let first_line = buffer.first_line_lossy();
379 let detected =
380 DetectedLanguage::from_path(path, first_line.as_deref(), registry, languages);
381 let mut state = Self::new_from_buffer(buffer);
382 state.apply_language(detected);
383 Ok(state)
384 }
385
386 pub fn from_buffer_with_language(buffer: Buffer, detected: DetectedLanguage) -> Self {
391 let mut state = Self::new_from_buffer(buffer);
392 state.apply_language(detected);
393 state
394 }
395
396 fn apply_insert(
398 &mut self,
399 cursors: &mut Cursors,
400 position: usize,
401 text: &str,
402 cursor_id: crate::model::event::CursorId,
403 ) {
404 let newlines_inserted = text.matches('\n').count();
405
406 self.marker_list.adjust_for_insert(position, text.len());
408 self.margins.adjust_for_insert(position, text.len());
409
410 self.buffer.insert(position, text);
412
413 self.highlighter.notify_insert(position, text.len());
416 self.highlighter
417 .invalidate_range(position..position + text.len());
418
419 cursors.adjust_for_edit(position, 0, text.len());
424
425 if let Some(cursor) = cursors.get_mut(cursor_id) {
427 cursor.position = position + text.len();
428 cursor.clear_selection();
429 }
430
431 if cursor_id == cursors.primary_id() {
433 self.primary_cursor_line_number = match self.primary_cursor_line_number {
434 LineNumber::Absolute(line) => LineNumber::Absolute(line + newlines_inserted),
435 LineNumber::Relative {
436 line,
437 from_cached_line,
438 } => LineNumber::Relative {
439 line: line + newlines_inserted,
440 from_cached_line,
441 },
442 };
443 }
444 }
445
446 fn apply_delete(
448 &mut self,
449 cursors: &mut Cursors,
450 range: &std::ops::Range<usize>,
451 cursor_id: crate::model::event::CursorId,
452 deleted_text: &str,
453 ) {
454 let len = range.len();
455
456 let primary_newlines_removed = if cursor_id == cursors.primary_id() {
460 let cursor_pos = cursors.get(cursor_id).map_or(range.start, |c| c.position);
461 let bytes_before_cursor = cursor_pos.saturating_sub(range.start).min(len);
462 deleted_text[..bytes_before_cursor].matches('\n').count()
463 } else {
464 0
465 };
466
467 self.virtual_texts
473 .remove_in_range(&mut self.marker_list, range.start, range.end);
474
475 self.marker_list.adjust_for_delete(range.start, len);
477 self.margins.adjust_for_delete(range.start, len);
478
479 self.buffer.delete(range.clone());
481
482 self.highlighter.notify_delete(range.start, len);
485 self.highlighter.invalidate_range(range.clone());
486
487 cursors.adjust_for_edit(range.start, len, 0);
492
493 if let Some(cursor) = cursors.get_mut(cursor_id) {
495 cursor.position = range.start;
496 cursor.clear_selection();
497 }
498
499 if cursor_id == cursors.primary_id() && primary_newlines_removed > 0 {
501 self.primary_cursor_line_number = match self.primary_cursor_line_number {
502 LineNumber::Absolute(line) => {
503 LineNumber::Absolute(line.saturating_sub(primary_newlines_removed))
504 }
505 LineNumber::Relative {
506 line,
507 from_cached_line,
508 } => LineNumber::Relative {
509 line: line.saturating_sub(primary_newlines_removed),
510 from_cached_line,
511 },
512 };
513 }
514 }
515
516 pub fn apply(&mut self, cursors: &mut Cursors, event: &Event) {
519 match event {
520 Event::Insert {
521 position,
522 text,
523 cursor_id,
524 } => self.apply_insert(cursors, *position, text, *cursor_id),
525
526 Event::Delete {
527 range,
528 cursor_id,
529 deleted_text,
530 } => self.apply_delete(cursors, range, *cursor_id, deleted_text),
531
532 Event::MoveCursor {
533 cursor_id,
534 new_position,
535 new_anchor,
536 new_sticky_column,
537 ..
538 } => {
539 if let Some(cursor) = cursors.get_mut(*cursor_id) {
540 cursor.position = *new_position;
541 cursor.anchor = *new_anchor;
542 cursor.sticky_column = *new_sticky_column;
543 }
544
545 if *cursor_id == cursors.primary_id() {
548 self.primary_cursor_line_number =
549 match self.buffer.offset_to_position(*new_position) {
550 Some(pos) => LineNumber::Absolute(pos.line),
551 None => {
552 let estimated_line = *new_position / 80;
555 LineNumber::Absolute(estimated_line)
556 }
557 };
558 }
559 }
560
561 Event::AddCursor {
562 cursor_id,
563 position,
564 anchor,
565 } => {
566 let cursor = if let Some(anchor) = anchor {
567 Cursor::with_selection(*anchor, *position)
568 } else {
569 Cursor::new(*position)
570 };
571
572 cursors.insert_with_id(*cursor_id, cursor);
575
576 cursors.normalize();
577 }
578
579 Event::RemoveCursor { cursor_id, .. } => {
580 cursors.remove(*cursor_id);
581 }
582
583 Event::Scroll { .. } | Event::SetViewport { .. } | Event::Recenter => {
586 tracing::warn!("View event {:?} reached EditorState.apply() - should be handled by SplitViewState", event);
589 }
590
591 Event::SetAnchor {
592 cursor_id,
593 position,
594 } => {
595 if let Some(cursor) = cursors.get_mut(*cursor_id) {
598 cursor.anchor = Some(*position);
599 cursor.deselect_on_move = false;
600 }
601 }
602
603 Event::ClearAnchor { cursor_id } => {
604 if let Some(cursor) = cursors.get_mut(*cursor_id) {
607 cursor.anchor = None;
608 cursor.deselect_on_move = true;
609 cursor.clear_block_selection();
610 }
611 }
612
613 Event::ChangeMode { mode } => {
614 self.mode = mode.clone();
615 }
616
617 Event::AddOverlay {
618 namespace,
619 range,
620 face,
621 priority,
622 message,
623 extend_to_line_end,
624 url,
625 } => {
626 tracing::trace!(
627 "AddOverlay: namespace={:?}, range={:?}, face={:?}, priority={}",
628 namespace,
629 range,
630 face,
631 priority
632 );
633 let overlay_face = convert_event_face_to_overlay_face(face);
635 tracing::trace!("Converted face: {:?}", overlay_face);
636
637 let mut overlay = Overlay::with_priority(
638 &mut self.marker_list,
639 range.clone(),
640 overlay_face,
641 *priority,
642 );
643 overlay.namespace = namespace.clone();
644 overlay.message = message.clone();
645 overlay.extend_to_line_end = *extend_to_line_end;
646 overlay.url = url.clone();
647
648 let actual_range = overlay.range(&self.marker_list);
649 tracing::trace!(
650 "Created overlay with markers - actual range: {:?}, handle={:?}",
651 actual_range,
652 overlay.handle
653 );
654
655 self.overlays.add(overlay);
656 }
657
658 Event::RemoveOverlay { handle } => {
659 tracing::trace!("RemoveOverlay: handle={:?}", handle);
660 self.overlays
661 .remove_by_handle(handle, &mut self.marker_list);
662 }
663
664 Event::RemoveOverlaysInRange { range } => {
665 self.overlays.remove_in_range(range, &mut self.marker_list);
666 }
667
668 Event::ClearNamespace { namespace } => {
669 tracing::trace!("ClearNamespace: namespace={:?}", namespace);
670 self.overlays
671 .clear_namespace(namespace, &mut self.marker_list);
672 }
673
674 Event::ClearOverlays => {
675 self.overlays.clear(&mut self.marker_list);
676 }
677
678 Event::ShowPopup { popup } => {
679 let popup_obj = convert_popup_data_to_popup(popup);
680 self.popups.show_or_replace(popup_obj);
681 }
682
683 Event::HidePopup => {
684 self.popups.hide();
685 }
686
687 Event::ClearPopups => {
688 self.popups.clear();
689 }
690
691 Event::PopupSelectNext => {
692 if let Some(popup) = self.popups.top_mut() {
693 popup.select_next();
694 }
695 }
696
697 Event::PopupSelectPrev => {
698 if let Some(popup) = self.popups.top_mut() {
699 popup.select_prev();
700 }
701 }
702
703 Event::PopupPageDown => {
704 if let Some(popup) = self.popups.top_mut() {
705 popup.page_down();
706 }
707 }
708
709 Event::PopupPageUp => {
710 if let Some(popup) = self.popups.top_mut() {
711 popup.page_up();
712 }
713 }
714
715 Event::AddMarginAnnotation {
716 line,
717 position,
718 content,
719 annotation_id,
720 } => {
721 let margin_position = convert_margin_position(position);
722 let margin_content = convert_margin_content(content);
723 let annotation = if let Some(id) = annotation_id {
724 MarginAnnotation::with_id(*line, margin_position, margin_content, id.clone())
725 } else {
726 MarginAnnotation::new(*line, margin_position, margin_content)
727 };
728 self.margins.add_annotation(annotation);
729 }
730
731 Event::RemoveMarginAnnotation { annotation_id } => {
732 self.margins.remove_by_id(annotation_id);
733 }
734
735 Event::RemoveMarginAnnotationsAtLine { line, position } => {
736 let margin_position = convert_margin_position(position);
737 self.margins.remove_at_line(*line, margin_position);
738 }
739
740 Event::ClearMarginPosition { position } => {
741 let margin_position = convert_margin_position(position);
742 self.margins.clear_position(margin_position);
743 }
744
745 Event::ClearMargins => {
746 self.margins.clear_all();
747 }
748
749 Event::SetLineNumbers { enabled } => {
750 self.margins.configure_for_line_numbers(*enabled);
751 }
752
753 Event::SplitPane { .. }
756 | Event::CloseSplit { .. }
757 | Event::SetActiveSplit { .. }
758 | Event::AdjustSplitRatio { .. }
759 | Event::NextSplit
760 | Event::PrevSplit => {
761 }
763
764 Event::Batch { events, .. } => {
765 for event in events {
768 self.apply(cursors, event);
769 }
770 }
771
772 Event::BulkEdit {
773 new_snapshot,
774 new_cursors,
775 edits,
776 displaced_markers,
777 ..
778 } => {
779 if let Some(snapshot) = new_snapshot {
785 self.buffer.restore_buffer_state(snapshot);
786 }
787
788 for &(pos, del_len, ins_len) in edits {
798 if del_len > 0 && ins_len > 0 {
799 if ins_len > del_len {
801 let net = ins_len - del_len;
802 self.marker_list.adjust_for_insert(pos, net);
803 self.margins.adjust_for_insert(pos, net);
804 } else if del_len > ins_len {
805 let net = del_len - ins_len;
806 self.marker_list.adjust_for_delete(pos, net);
807 self.margins.adjust_for_delete(pos, net);
808 }
809 } else if del_len > 0 {
811 self.marker_list.adjust_for_delete(pos, del_len);
812 self.margins.adjust_for_delete(pos, del_len);
813 } else if ins_len > 0 {
814 self.marker_list.adjust_for_insert(pos, ins_len);
815 self.margins.adjust_for_insert(pos, ins_len);
816 }
817 }
818
819 if !displaced_markers.is_empty() {
824 self.restore_displaced_markers(displaced_markers);
825 }
826
827 self.virtual_texts.clear(&mut self.marker_list);
830
831 use crate::view::overlay::OverlayNamespace;
832 let namespaces = ["lsp-diagnostic", "reference-highlight", "bracket-highlight"];
833 for ns in &namespaces {
834 self.overlays.clear_namespace(
835 &OverlayNamespace::from_string(ns.to_string()),
836 &mut self.marker_list,
837 );
838 }
839
840 for (cursor_id, position, anchor) in new_cursors {
842 if let Some(cursor) = cursors.get_mut(*cursor_id) {
843 cursor.position = *position;
844 cursor.anchor = *anchor;
845 }
846 }
847
848 self.highlighter.invalidate_all();
850
851 let primary_pos = cursors.primary().position;
853 self.primary_cursor_line_number = match self.buffer.offset_to_position(primary_pos)
854 {
855 Some(pos) => crate::model::buffer::LineNumber::Absolute(pos.line),
856 None => crate::model::buffer::LineNumber::Absolute(0),
857 };
858 }
859 }
860 }
861
862 pub fn capture_displaced_markers(&self, range: &Range<usize>) -> Vec<(u64, usize)> {
865 let mut displaced = Vec::new();
866 if range.is_empty() {
867 return displaced;
868 }
869 for (marker_id, start, _end) in self.marker_list.query_range(range.start, range.end) {
870 if start > range.start && start < range.end {
871 displaced.push(
872 DisplacedMarker::Main {
873 id: marker_id.0,
874 position: start,
875 }
876 .encode(),
877 );
878 }
879 }
880 for (marker_id, start, _end) in self.margins.query_indicator_range(range.start, range.end) {
881 if start > range.start && start < range.end {
882 displaced.push(
883 DisplacedMarker::Margin {
884 id: marker_id.0,
885 position: start,
886 }
887 .encode(),
888 );
889 }
890 }
891 displaced
892 }
893
894 pub fn capture_displaced_markers_bulk(
896 &self,
897 edits: &[(usize, usize, String)],
898 ) -> Vec<(u64, usize)> {
899 let mut displaced = Vec::new();
900 for (pos, del_len, _text) in edits {
901 if *del_len > 0 {
902 displaced.extend(self.capture_displaced_markers(&(*pos..*pos + *del_len)));
903 }
904 }
905 displaced
906 }
907
908 pub fn restore_displaced_markers(&mut self, displaced: &[(u64, usize)]) {
910 for &(tagged_id, original_pos) in displaced {
911 let dm = DisplacedMarker::decode(tagged_id, original_pos);
912 match dm {
913 DisplacedMarker::Main { id, position } => {
914 self.marker_list.set_position(MarkerId(id), position);
915 }
916 DisplacedMarker::Margin { id, position } => {
917 self.margins.set_indicator_position(MarkerId(id), position);
918 }
919 }
920 }
921 }
922
923 pub fn apply_many(&mut self, cursors: &mut Cursors, events: &[Event]) {
925 for event in events {
926 self.apply(cursors, event);
927 }
928 }
929
930 pub fn on_focus_lost(&mut self) {
934 if self.popups.dismiss_transient() {
935 tracing::debug!("Dismissed transient popup on buffer focus loss");
936 }
937 }
938}
939
940fn convert_event_face_to_overlay_face(event_face: &EventOverlayFace) -> OverlayFace {
942 match event_face {
943 EventOverlayFace::Underline { color, style } => {
944 let underline_style = match style {
945 crate::model::event::UnderlineStyle::Straight => UnderlineStyle::Straight,
946 crate::model::event::UnderlineStyle::Wavy => UnderlineStyle::Wavy,
947 crate::model::event::UnderlineStyle::Dotted => UnderlineStyle::Dotted,
948 crate::model::event::UnderlineStyle::Dashed => UnderlineStyle::Dashed,
949 };
950 OverlayFace::Underline {
951 color: Color::Rgb(color.0, color.1, color.2),
952 style: underline_style,
953 }
954 }
955 EventOverlayFace::Background { color } => OverlayFace::Background {
956 color: Color::Rgb(color.0, color.1, color.2),
957 },
958 EventOverlayFace::Foreground { color } => OverlayFace::Foreground {
959 color: Color::Rgb(color.0, color.1, color.2),
960 },
961 EventOverlayFace::Style { options } => {
962 use crate::view::theme::named_color_from_str;
963 use ratatui::style::Modifier;
964
965 let mut style = Style::default();
967
968 if let Some(ref fg) = options.fg {
970 if let Some((r, g, b)) = fg.as_rgb() {
971 style = style.fg(Color::Rgb(r, g, b));
972 } else if let Some(key) = fg.as_theme_key() {
973 if let Some(color) = named_color_from_str(key) {
974 style = style.fg(color);
975 }
976 }
977 }
978
979 if let Some(ref bg) = options.bg {
981 if let Some((r, g, b)) = bg.as_rgb() {
982 style = style.bg(Color::Rgb(r, g, b));
983 } else if let Some(key) = bg.as_theme_key() {
984 if let Some(color) = named_color_from_str(key) {
985 style = style.bg(color);
986 }
987 }
988 }
989
990 let mut modifiers = Modifier::empty();
992 if options.bold {
993 modifiers |= Modifier::BOLD;
994 }
995 if options.italic {
996 modifiers |= Modifier::ITALIC;
997 }
998 if options.underline {
999 modifiers |= Modifier::UNDERLINED;
1000 }
1001 if options.strikethrough {
1002 modifiers |= Modifier::CROSSED_OUT;
1003 }
1004 if !modifiers.is_empty() {
1005 style = style.add_modifier(modifiers);
1006 }
1007
1008 let fg_theme = options
1010 .fg
1011 .as_ref()
1012 .and_then(|c| c.as_theme_key())
1013 .filter(|key| named_color_from_str(key).is_none())
1014 .map(String::from);
1015 let bg_theme = options
1016 .bg
1017 .as_ref()
1018 .and_then(|c| c.as_theme_key())
1019 .filter(|key| named_color_from_str(key).is_none())
1020 .map(String::from);
1021
1022 if fg_theme.is_some() || bg_theme.is_some() {
1024 OverlayFace::ThemedStyle {
1025 fallback_style: style,
1026 fg_theme,
1027 bg_theme,
1028 }
1029 } else {
1030 OverlayFace::Style { style }
1031 }
1032 }
1033 }
1034}
1035
1036pub(crate) fn convert_popup_data_to_popup(data: &PopupData) -> Popup {
1038 let content = match &data.content {
1039 crate::model::event::PopupContentData::Text(lines) => PopupContent::Text(lines.clone()),
1040 crate::model::event::PopupContentData::List { items, selected } => PopupContent::List {
1041 items: items
1042 .iter()
1043 .map(|item| PopupListItem {
1044 text: item.text.clone(),
1045 detail: item.detail.clone(),
1046 icon: item.icon.clone(),
1047 data: item.data.clone(),
1048 disabled: false,
1049 })
1050 .collect(),
1051 selected: *selected,
1052 },
1053 };
1054
1055 let position = match data.position {
1056 PopupPositionData::AtCursor => PopupPosition::AtCursor,
1057 PopupPositionData::BelowCursor => PopupPosition::BelowCursor,
1058 PopupPositionData::AboveCursor => PopupPosition::AboveCursor,
1059 PopupPositionData::Fixed { x, y } => PopupPosition::Fixed { x, y },
1060 PopupPositionData::Centered => PopupPosition::Centered,
1061 PopupPositionData::BottomRight => PopupPosition::BottomRight,
1062 PopupPositionData::AboveStatusBarAt { x } => PopupPosition::AboveStatusBarAt { x },
1063 };
1064
1065 let kind = match data.kind {
1067 crate::model::event::PopupKindHint::Completion => PopupKind::Completion,
1068 crate::model::event::PopupKindHint::List => PopupKind::List,
1069 crate::model::event::PopupKindHint::Text => PopupKind::Text,
1070 };
1071
1072 let resolver = match kind {
1079 PopupKind::Completion => crate::view::popup::PopupResolver::Completion,
1080 _ => crate::view::popup::PopupResolver::None,
1081 };
1082
1083 Popup {
1084 kind,
1085 title: data.title.clone(),
1086 description: data.description.clone(),
1087 transient: data.transient,
1088 content,
1089 position,
1090 width: data.width,
1091 max_height: data.max_height,
1092 bordered: data.bordered,
1093 border_style: Style::default().fg(Color::Gray),
1094 background_style: Style::default().bg(Color::Rgb(30, 30, 30)),
1095 scroll_offset: 0,
1096 text_selection: None,
1097 accept_key_hint: None,
1098 resolver,
1099 }
1100}
1101
1102fn convert_margin_position(position: &MarginPositionData) -> MarginPosition {
1104 match position {
1105 MarginPositionData::Left => MarginPosition::Left,
1106 MarginPositionData::Right => MarginPosition::Right,
1107 }
1108}
1109
1110fn convert_margin_content(content: &MarginContentData) -> MarginContent {
1112 match content {
1113 MarginContentData::Text(text) => MarginContent::Text(text.clone()),
1114 MarginContentData::Symbol { text, color } => {
1115 if let Some((r, g, b)) = color {
1116 MarginContent::colored_symbol(text.clone(), Color::Rgb(*r, *g, *b))
1117 } else {
1118 MarginContent::symbol(text.clone(), Style::default())
1119 }
1120 }
1121 MarginContentData::Empty => MarginContent::Empty,
1122 }
1123}
1124
1125impl EditorState {
1126 pub fn prepare_for_render(&mut self, top_byte: usize, height: u16) -> Result<()> {
1133 self.buffer.prepare_viewport(top_byte, height as usize)?;
1134 Ok(())
1135 }
1136
1137 pub fn collect_virtual_line_positions(&self) -> Vec<usize> {
1149 if self.virtual_texts.is_empty() {
1150 return Vec::new();
1151 }
1152 let mut v: Vec<usize> = self
1153 .virtual_texts
1154 .query_lines_in_range(&self.marker_list, 0, self.buffer.len() + 1)
1155 .into_iter()
1156 .map(|(pos, _vt)| pos)
1157 .collect();
1158 v.sort_unstable();
1159 v
1160 }
1161
1162 pub fn collect_soft_break_positions(&self) -> Vec<(usize, u16)> {
1175 if self.soft_breaks.is_empty() {
1176 return Vec::new();
1177 }
1178 self.soft_breaks
1180 .query_viewport(0, self.buffer.len() + 1, &self.marker_list)
1181 }
1182
1183 pub fn get_text_range(&mut self, start: usize, end: usize) -> String {
1203 match self
1205 .buffer
1206 .get_text_range_mut(start, end.saturating_sub(start))
1207 {
1208 Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
1209 Err(e) => {
1210 tracing::warn!("Failed to get text range {}..{}: {}", start, end, e);
1211 String::new()
1212 }
1213 }
1214 }
1215
1216 pub fn get_line_at_offset(&mut self, offset: usize) -> Option<(usize, String)> {
1224 use crate::model::document_model::DocumentModel;
1225
1226 let mut line_start = offset;
1229 while line_start > 0 {
1230 if let Ok(text) = self.buffer.get_text_range_mut(line_start - 1, 1) {
1231 if text.first() == Some(&b'\n') {
1232 break;
1233 }
1234 line_start -= 1;
1235 } else {
1236 break;
1237 }
1238 }
1239
1240 let viewport = self
1242 .get_viewport_content(
1243 crate::model::document_model::DocumentPosition::byte(line_start),
1244 1,
1245 )
1246 .ok()?;
1247
1248 viewport
1249 .lines
1250 .first()
1251 .map(|line| (line.byte_offset, line.content.clone()))
1252 }
1253
1254 pub fn get_text_to_end_of_line(&mut self, cursor_pos: usize) -> Result<String> {
1259 use crate::model::document_model::DocumentModel;
1260
1261 let viewport = self.get_viewport_content(
1263 crate::model::document_model::DocumentPosition::byte(cursor_pos),
1264 1,
1265 )?;
1266
1267 if let Some(line) = viewport.lines.first() {
1268 let line_start = line.byte_offset;
1269 let line_end = line_start + line.content.len();
1270
1271 if cursor_pos >= line_start && cursor_pos <= line_end {
1272 let offset_in_line = cursor_pos - line_start;
1273 Ok(line.content.get(offset_in_line..).unwrap_or("").to_string())
1275 } else {
1276 Ok(String::new())
1277 }
1278 } else {
1279 Ok(String::new())
1280 }
1281 }
1282
1283 pub fn set_semantic_tokens(&mut self, store: SemanticTokenStore) {
1285 self.semantic_tokens = Some(store);
1286 }
1287
1288 pub fn clear_semantic_tokens(&mut self) {
1290 self.semantic_tokens = None;
1291 }
1292
1293 pub fn semantic_tokens_result_id(&self) -> Option<&str> {
1295 self.semantic_tokens
1296 .as_ref()
1297 .and_then(|store| store.result_id.as_deref())
1298 }
1299}
1300
1301impl DocumentModel for EditorState {
1306 fn capabilities(&self) -> DocumentCapabilities {
1307 let line_count = self.buffer.line_count();
1308 DocumentCapabilities {
1309 has_line_index: line_count.is_some(),
1310 uses_lazy_loading: false, byte_length: self.buffer.len(),
1312 approximate_line_count: line_count.unwrap_or_else(|| {
1313 self.buffer.len() / 80
1315 }),
1316 }
1317 }
1318
1319 fn get_viewport_content(
1320 &mut self,
1321 start_pos: DocumentPosition,
1322 max_lines: usize,
1323 ) -> Result<ViewportContent> {
1324 let start_offset = self.position_to_offset(start_pos)?;
1326
1327 let line_iter = self.buffer.iter_lines_from(start_offset, max_lines)?;
1330 let has_more = line_iter.has_more;
1331
1332 let lines = line_iter
1333 .map(|line_data| ViewportLine {
1334 byte_offset: line_data.byte_offset,
1335 content: line_data.content,
1336 has_newline: line_data.has_newline,
1337 approximate_line_number: line_data.line_number,
1338 })
1339 .collect();
1340
1341 Ok(ViewportContent {
1342 start_position: DocumentPosition::ByteOffset(start_offset),
1343 lines,
1344 has_more,
1345 })
1346 }
1347
1348 fn position_to_offset(&self, pos: DocumentPosition) -> Result<usize> {
1349 match pos {
1350 DocumentPosition::ByteOffset(offset) => Ok(offset),
1351 DocumentPosition::LineColumn { line, column } => {
1352 if !self.has_line_index() {
1353 anyhow::bail!("Line indexing not available for this document");
1354 }
1355 let position = crate::model::piece_tree::Position { line, column };
1357 Ok(self.buffer.position_to_offset(position))
1358 }
1359 }
1360 }
1361
1362 fn offset_to_position(&self, offset: usize) -> DocumentPosition {
1363 if self.has_line_index() {
1364 if let Some(pos) = self.buffer.offset_to_position(offset) {
1365 DocumentPosition::LineColumn {
1366 line: pos.line,
1367 column: pos.column,
1368 }
1369 } else {
1370 DocumentPosition::ByteOffset(offset)
1372 }
1373 } else {
1374 DocumentPosition::ByteOffset(offset)
1375 }
1376 }
1377
1378 fn get_range(&mut self, start: DocumentPosition, end: DocumentPosition) -> Result<String> {
1379 let start_offset = self.position_to_offset(start)?;
1380 let end_offset = self.position_to_offset(end)?;
1381
1382 if start_offset > end_offset {
1383 anyhow::bail!(
1384 "Invalid range: start offset {} > end offset {}",
1385 start_offset,
1386 end_offset
1387 );
1388 }
1389
1390 let bytes = self
1391 .buffer
1392 .get_text_range_mut(start_offset, end_offset - start_offset)?;
1393
1394 Ok(String::from_utf8_lossy(&bytes).into_owned())
1395 }
1396
1397 fn get_line_content(&mut self, line_number: usize) -> Option<String> {
1398 if !self.has_line_index() {
1399 return None;
1400 }
1401
1402 let line_start_offset = self.buffer.line_start_offset(line_number)?;
1404
1405 let mut iter = self.buffer.line_iterator(line_start_offset, 80);
1407 if let Some((_start, content)) = iter.next_line() {
1408 let has_newline = content.ends_with('\n');
1409 let line_content = if has_newline {
1410 content[..content.len() - 1].to_string()
1411 } else {
1412 content
1413 };
1414 Some(line_content)
1415 } else {
1416 None
1417 }
1418 }
1419
1420 fn get_chunk_at_offset(&mut self, offset: usize, size: usize) -> Result<(usize, String)> {
1421 let bytes = self.buffer.get_text_range_mut(offset, size)?;
1422
1423 Ok((offset, String::from_utf8_lossy(&bytes).into_owned()))
1424 }
1425
1426 fn insert(&mut self, pos: DocumentPosition, text: &str) -> Result<usize> {
1427 let offset = self.position_to_offset(pos)?;
1428 self.buffer.insert_bytes(offset, text.as_bytes().to_vec());
1429 Ok(text.len())
1430 }
1431
1432 fn delete(&mut self, start: DocumentPosition, end: DocumentPosition) -> Result<()> {
1433 let start_offset = self.position_to_offset(start)?;
1434 let end_offset = self.position_to_offset(end)?;
1435
1436 if start_offset > end_offset {
1437 anyhow::bail!(
1438 "Invalid range: start offset {} > end offset {}",
1439 start_offset,
1440 end_offset
1441 );
1442 }
1443
1444 self.buffer.delete(start_offset..end_offset);
1445 Ok(())
1446 }
1447
1448 fn replace(
1449 &mut self,
1450 start: DocumentPosition,
1451 end: DocumentPosition,
1452 text: &str,
1453 ) -> Result<()> {
1454 self.delete(start, end)?;
1456 self.insert(start, text)?;
1457 Ok(())
1458 }
1459
1460 fn find_matches(
1461 &mut self,
1462 pattern: &str,
1463 search_range: Option<(DocumentPosition, DocumentPosition)>,
1464 ) -> Result<Vec<usize>> {
1465 let (start_offset, end_offset) = if let Some((start, end)) = search_range {
1466 (
1467 self.position_to_offset(start)?,
1468 self.position_to_offset(end)?,
1469 )
1470 } else {
1471 (0, self.buffer.len())
1472 };
1473
1474 let bytes = self
1476 .buffer
1477 .get_text_range_mut(start_offset, end_offset - start_offset)?;
1478 let text = String::from_utf8_lossy(&bytes);
1479
1480 let mut matches = Vec::new();
1482 let mut search_offset = 0;
1483 while let Some(pos) = text[search_offset..].find(pattern) {
1484 matches.push(start_offset + search_offset + pos);
1485 search_offset += pos + pattern.len();
1486 }
1487
1488 Ok(matches)
1489 }
1490}
1491
1492#[derive(Clone, Debug)]
1494pub struct SemanticTokenStore {
1495 pub version: u64,
1497 pub result_id: Option<String>,
1499 pub data: Vec<u32>,
1501 pub tokens: Vec<SemanticTokenSpan>,
1503}
1504
1505#[derive(Clone, Debug)]
1507pub struct SemanticTokenSpan {
1508 pub range: Range<usize>,
1509 pub token_type: String,
1510 pub modifiers: Vec<String>,
1511}
1512
1513#[cfg(test)]
1514mod tests {
1515 use crate::model::filesystem::StdFileSystem;
1516 use std::sync::Arc;
1517
1518 fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
1519 Arc::new(StdFileSystem)
1520 }
1521 use super::*;
1522 use crate::model::event::CursorId;
1523
1524 #[test]
1525 fn test_state_new() {
1526 let state = EditorState::new(
1527 80,
1528 24,
1529 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1530 test_fs(),
1531 );
1532 assert!(state.buffer.is_empty());
1533 }
1534
1535 #[test]
1536 fn test_apply_insert() {
1537 let mut state = EditorState::new(
1538 80,
1539 24,
1540 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1541 test_fs(),
1542 );
1543 let mut cursors = Cursors::new();
1544 let cursor_id = cursors.primary_id();
1545
1546 state.apply(
1547 &mut cursors,
1548 &Event::Insert {
1549 position: 0,
1550 text: "hello".to_string(),
1551 cursor_id,
1552 },
1553 );
1554
1555 assert_eq!(state.buffer.to_string().unwrap(), "hello");
1556 assert_eq!(cursors.primary().position, 5);
1557 assert!(state.buffer.is_modified());
1558 }
1559
1560 #[test]
1561 fn test_apply_delete() {
1562 let mut state = EditorState::new(
1563 80,
1564 24,
1565 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1566 test_fs(),
1567 );
1568 let mut cursors = Cursors::new();
1569 let cursor_id = cursors.primary_id();
1570
1571 state.apply(
1573 &mut cursors,
1574 &Event::Insert {
1575 position: 0,
1576 text: "hello world".to_string(),
1577 cursor_id,
1578 },
1579 );
1580
1581 state.apply(
1582 &mut cursors,
1583 &Event::Delete {
1584 range: 5..11,
1585 deleted_text: " world".to_string(),
1586 cursor_id,
1587 },
1588 );
1589
1590 assert_eq!(state.buffer.to_string().unwrap(), "hello");
1591 assert_eq!(cursors.primary().position, 5);
1592 }
1593
1594 #[test]
1595 fn test_apply_move_cursor() {
1596 let mut state = EditorState::new(
1597 80,
1598 24,
1599 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1600 test_fs(),
1601 );
1602 let mut cursors = Cursors::new();
1603 let cursor_id = cursors.primary_id();
1604
1605 state.apply(
1606 &mut cursors,
1607 &Event::Insert {
1608 position: 0,
1609 text: "hello".to_string(),
1610 cursor_id,
1611 },
1612 );
1613
1614 state.apply(
1615 &mut cursors,
1616 &Event::MoveCursor {
1617 cursor_id,
1618 old_position: 5,
1619 new_position: 2,
1620 old_anchor: None,
1621 new_anchor: None,
1622 old_sticky_column: 0,
1623 new_sticky_column: 0,
1624 },
1625 );
1626
1627 assert_eq!(cursors.primary().position, 2);
1628 }
1629
1630 #[test]
1631 fn test_apply_add_cursor() {
1632 let mut state = EditorState::new(
1633 80,
1634 24,
1635 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1636 test_fs(),
1637 );
1638 let mut cursors = Cursors::new();
1639 let cursor_id = CursorId(1);
1640
1641 state.apply(
1642 &mut cursors,
1643 &Event::AddCursor {
1644 cursor_id,
1645 position: 5,
1646 anchor: None,
1647 },
1648 );
1649
1650 assert_eq!(cursors.count(), 2);
1651 }
1652
1653 #[test]
1654 fn test_apply_many() {
1655 let mut state = EditorState::new(
1656 80,
1657 24,
1658 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1659 test_fs(),
1660 );
1661 let mut cursors = Cursors::new();
1662 let cursor_id = cursors.primary_id();
1663
1664 let events = vec![
1665 Event::Insert {
1666 position: 0,
1667 text: "hello ".to_string(),
1668 cursor_id,
1669 },
1670 Event::Insert {
1671 position: 6,
1672 text: "world".to_string(),
1673 cursor_id,
1674 },
1675 ];
1676
1677 state.apply_many(&mut cursors, &events);
1678
1679 assert_eq!(state.buffer.to_string().unwrap(), "hello world");
1680 }
1681
1682 #[test]
1683 fn test_cursor_adjustment_after_insert() {
1684 let mut state = EditorState::new(
1685 80,
1686 24,
1687 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1688 test_fs(),
1689 );
1690 let mut cursors = Cursors::new();
1691 let cursor_id = cursors.primary_id();
1692
1693 state.apply(
1695 &mut cursors,
1696 &Event::AddCursor {
1697 cursor_id: CursorId(1),
1698 position: 5,
1699 anchor: None,
1700 },
1701 );
1702
1703 state.apply(
1705 &mut cursors,
1706 &Event::Insert {
1707 position: 0,
1708 text: "abc".to_string(),
1709 cursor_id,
1710 },
1711 );
1712
1713 if let Some(cursor) = cursors.get(CursorId(1)) {
1715 assert_eq!(cursor.position, 8);
1716 }
1717 }
1718
1719 mod document_model_tests {
1721 use super::*;
1722 use crate::model::document_model::{DocumentModel, DocumentPosition};
1723
1724 #[test]
1725 fn test_capabilities_small_file() {
1726 let mut state = EditorState::new(
1727 80,
1728 24,
1729 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1730 test_fs(),
1731 );
1732 state.buffer = Buffer::from_str_test("line1\nline2\nline3");
1733
1734 let caps = state.capabilities();
1735 assert!(caps.has_line_index, "Small file should have line index");
1736 assert_eq!(caps.byte_length, "line1\nline2\nline3".len());
1737 assert_eq!(caps.approximate_line_count, 3, "Should have 3 lines");
1738 }
1739
1740 #[test]
1741 fn test_position_conversions() {
1742 let mut state = EditorState::new(
1743 80,
1744 24,
1745 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1746 test_fs(),
1747 );
1748 state.buffer = Buffer::from_str_test("hello\nworld\ntest");
1749
1750 let pos1 = DocumentPosition::ByteOffset(6);
1752 let offset1 = state.position_to_offset(pos1).unwrap();
1753 assert_eq!(offset1, 6);
1754
1755 let pos2 = DocumentPosition::LineColumn { line: 1, column: 0 };
1757 let offset2 = state.position_to_offset(pos2).unwrap();
1758 assert_eq!(offset2, 6, "Line 1, column 0 should be at byte 6");
1759
1760 let converted = state.offset_to_position(6);
1762 match converted {
1763 DocumentPosition::LineColumn { line, column } => {
1764 assert_eq!(line, 1);
1765 assert_eq!(column, 0);
1766 }
1767 _ => panic!("Expected LineColumn for small file"),
1768 }
1769 }
1770
1771 #[test]
1772 fn test_get_viewport_content() {
1773 let mut state = EditorState::new(
1774 80,
1775 24,
1776 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1777 test_fs(),
1778 );
1779 state.buffer = Buffer::from_str_test("line1\nline2\nline3\nline4\nline5");
1780
1781 let content = state
1782 .get_viewport_content(DocumentPosition::ByteOffset(0), 3)
1783 .unwrap();
1784
1785 assert_eq!(content.lines.len(), 3);
1786 assert_eq!(content.lines[0].content, "line1");
1787 assert_eq!(content.lines[1].content, "line2");
1788 assert_eq!(content.lines[2].content, "line3");
1789 assert!(content.has_more);
1790 }
1791
1792 #[test]
1793 fn test_get_range() {
1794 let mut state = EditorState::new(
1795 80,
1796 24,
1797 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1798 test_fs(),
1799 );
1800 state.buffer = Buffer::from_str_test("hello world");
1801
1802 let text = state
1803 .get_range(
1804 DocumentPosition::ByteOffset(0),
1805 DocumentPosition::ByteOffset(5),
1806 )
1807 .unwrap();
1808 assert_eq!(text, "hello");
1809
1810 let text2 = state
1811 .get_range(
1812 DocumentPosition::ByteOffset(6),
1813 DocumentPosition::ByteOffset(11),
1814 )
1815 .unwrap();
1816 assert_eq!(text2, "world");
1817 }
1818
1819 #[test]
1820 fn test_get_line_content() {
1821 let mut state = EditorState::new(
1822 80,
1823 24,
1824 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1825 test_fs(),
1826 );
1827 state.buffer = Buffer::from_str_test("line1\nline2\nline3");
1828
1829 let line0 = state.get_line_content(0).unwrap();
1830 assert_eq!(line0, "line1");
1831
1832 let line1 = state.get_line_content(1).unwrap();
1833 assert_eq!(line1, "line2");
1834
1835 let line2 = state.get_line_content(2).unwrap();
1836 assert_eq!(line2, "line3");
1837 }
1838
1839 #[test]
1840 fn test_insert_delete() {
1841 let mut state = EditorState::new(
1842 80,
1843 24,
1844 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1845 test_fs(),
1846 );
1847 state.buffer = Buffer::from_str_test("hello world");
1848
1849 let bytes_inserted = state
1851 .insert(DocumentPosition::ByteOffset(6), "beautiful ")
1852 .unwrap();
1853 assert_eq!(bytes_inserted, 10);
1854 assert_eq!(state.buffer.to_string().unwrap(), "hello beautiful world");
1855
1856 state
1858 .delete(
1859 DocumentPosition::ByteOffset(6),
1860 DocumentPosition::ByteOffset(16),
1861 )
1862 .unwrap();
1863 assert_eq!(state.buffer.to_string().unwrap(), "hello world");
1864 }
1865
1866 #[test]
1867 fn test_replace() {
1868 let mut state = EditorState::new(
1869 80,
1870 24,
1871 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1872 test_fs(),
1873 );
1874 state.buffer = Buffer::from_str_test("hello world");
1875
1876 state
1877 .replace(
1878 DocumentPosition::ByteOffset(0),
1879 DocumentPosition::ByteOffset(5),
1880 "hi",
1881 )
1882 .unwrap();
1883 assert_eq!(state.buffer.to_string().unwrap(), "hi world");
1884 }
1885
1886 #[test]
1887 fn test_find_matches() {
1888 let mut state = EditorState::new(
1889 80,
1890 24,
1891 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1892 test_fs(),
1893 );
1894 state.buffer = Buffer::from_str_test("hello world hello");
1895
1896 let matches = state.find_matches("hello", None).unwrap();
1897 assert_eq!(matches.len(), 2);
1898 assert_eq!(matches[0], 0);
1899 assert_eq!(matches[1], 12);
1900 }
1901
1902 #[test]
1903 fn test_prepare_for_render() {
1904 let mut state = EditorState::new(
1905 80,
1906 24,
1907 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1908 test_fs(),
1909 );
1910 state.buffer = Buffer::from_str_test("line1\nline2\nline3\nline4\nline5");
1911
1912 state.prepare_for_render(0, 24).unwrap();
1914 }
1915
1916 #[test]
1917 fn test_helper_get_text_range() {
1918 let mut state = EditorState::new(
1919 80,
1920 24,
1921 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1922 test_fs(),
1923 );
1924 state.buffer = Buffer::from_str_test("hello world");
1925
1926 let text = state.get_text_range(0, 5);
1928 assert_eq!(text, "hello");
1929
1930 let text2 = state.get_text_range(6, 11);
1932 assert_eq!(text2, "world");
1933 }
1934
1935 #[test]
1936 fn test_helper_get_line_at_offset() {
1937 let mut state = EditorState::new(
1938 80,
1939 24,
1940 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1941 test_fs(),
1942 );
1943 state.buffer = Buffer::from_str_test("line1\nline2\nline3");
1944
1945 let (offset, content) = state.get_line_at_offset(0).unwrap();
1947 assert_eq!(offset, 0);
1948 assert_eq!(content, "line1");
1949
1950 let (offset2, content2) = state.get_line_at_offset(8).unwrap();
1952 assert_eq!(offset2, 6); assert_eq!(content2, "line2");
1954
1955 let (offset3, content3) = state.get_line_at_offset(12).unwrap();
1957 assert_eq!(offset3, 12);
1958 assert_eq!(content3, "line3");
1959 }
1960
1961 #[test]
1962 fn test_helper_get_text_to_end_of_line() {
1963 let mut state = EditorState::new(
1964 80,
1965 24,
1966 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1967 test_fs(),
1968 );
1969 state.buffer = Buffer::from_str_test("hello world\nline2");
1970
1971 let text = state.get_text_to_end_of_line(0).unwrap();
1973 assert_eq!(text, "hello world");
1974
1975 let text2 = state.get_text_to_end_of_line(6).unwrap();
1977 assert_eq!(text2, "world");
1978
1979 let text3 = state.get_text_to_end_of_line(11).unwrap();
1981 assert_eq!(text3, "");
1982
1983 let text4 = state.get_text_to_end_of_line(12).unwrap();
1985 assert_eq!(text4, "line2");
1986 }
1987 }
1988
1989 mod virtual_text_integration_tests {
1991 use super::*;
1992 use crate::view::virtual_text::VirtualTextPosition;
1993 use ratatui::style::Style;
1994
1995 #[test]
1996 fn test_virtual_text_add_and_query() {
1997 let mut state = EditorState::new(
1998 80,
1999 24,
2000 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2001 test_fs(),
2002 );
2003 state.buffer = Buffer::from_str_test("hello world");
2004
2005 if !state.buffer.is_empty() {
2007 state.marker_list.adjust_for_insert(0, state.buffer.len());
2008 }
2009
2010 let vtext_id = state.virtual_texts.add(
2012 &mut state.marker_list,
2013 5,
2014 ": string".to_string(),
2015 Style::default(),
2016 VirtualTextPosition::AfterChar,
2017 0,
2018 );
2019
2020 let results = state.virtual_texts.query_range(&state.marker_list, 0, 11);
2022 assert_eq!(results.len(), 1);
2023 assert_eq!(results[0].0, 5); assert_eq!(results[0].1.text, ": string");
2025
2026 let lookup = state.virtual_texts.build_lookup(&state.marker_list, 0, 11);
2028 assert!(lookup.contains_key(&5));
2029 assert_eq!(lookup[&5].len(), 1);
2030 assert_eq!(lookup[&5][0].text, ": string");
2031
2032 state.virtual_texts.remove(&mut state.marker_list, vtext_id);
2034 assert!(state.virtual_texts.is_empty());
2035 }
2036
2037 #[test]
2038 fn test_virtual_text_position_tracking_on_insert() {
2039 let mut state = EditorState::new(
2040 80,
2041 24,
2042 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2043 test_fs(),
2044 );
2045 state.buffer = Buffer::from_str_test("hello world");
2046
2047 if !state.buffer.is_empty() {
2049 state.marker_list.adjust_for_insert(0, state.buffer.len());
2050 }
2051
2052 let _vtext_id = state.virtual_texts.add(
2054 &mut state.marker_list,
2055 6,
2056 "/*param*/".to_string(),
2057 Style::default(),
2058 VirtualTextPosition::BeforeChar,
2059 0,
2060 );
2061
2062 let mut cursors = Cursors::new();
2064 let cursor_id = cursors.primary_id();
2065 state.apply(
2066 &mut cursors,
2067 &Event::Insert {
2068 position: 6,
2069 text: "beautiful ".to_string(),
2070 cursor_id,
2071 },
2072 );
2073
2074 let results = state.virtual_texts.query_range(&state.marker_list, 0, 30);
2076 assert_eq!(results.len(), 1);
2077 assert_eq!(results[0].0, 16); assert_eq!(results[0].1.text, "/*param*/");
2079 }
2080
2081 #[test]
2082 fn test_virtual_text_position_tracking_on_delete() {
2083 let mut state = EditorState::new(
2084 80,
2085 24,
2086 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2087 test_fs(),
2088 );
2089 state.buffer = Buffer::from_str_test("hello beautiful world");
2090
2091 if !state.buffer.is_empty() {
2093 state.marker_list.adjust_for_insert(0, state.buffer.len());
2094 }
2095
2096 let _vtext_id = state.virtual_texts.add(
2098 &mut state.marker_list,
2099 16,
2100 ": string".to_string(),
2101 Style::default(),
2102 VirtualTextPosition::AfterChar,
2103 0,
2104 );
2105
2106 let mut cursors = Cursors::new();
2108 let cursor_id = cursors.primary_id();
2109 state.apply(
2110 &mut cursors,
2111 &Event::Delete {
2112 range: 6..16,
2113 deleted_text: "beautiful ".to_string(),
2114 cursor_id,
2115 },
2116 );
2117
2118 let results = state.virtual_texts.query_range(&state.marker_list, 0, 20);
2120 assert_eq!(results.len(), 1);
2121 assert_eq!(results[0].0, 6); assert_eq!(results[0].1.text, ": string");
2123 }
2124
2125 #[test]
2126 fn test_multiple_virtual_texts_with_priorities() {
2127 let mut state = EditorState::new(
2128 80,
2129 24,
2130 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2131 test_fs(),
2132 );
2133 state.buffer = Buffer::from_str_test("let x = 5");
2134
2135 if !state.buffer.is_empty() {
2137 state.marker_list.adjust_for_insert(0, state.buffer.len());
2138 }
2139
2140 state.virtual_texts.add(
2142 &mut state.marker_list,
2143 5,
2144 ": i32".to_string(),
2145 Style::default(),
2146 VirtualTextPosition::AfterChar,
2147 0, );
2149
2150 state.virtual_texts.add(
2152 &mut state.marker_list,
2153 5,
2154 " /* inferred */".to_string(),
2155 Style::default(),
2156 VirtualTextPosition::AfterChar,
2157 10, );
2159
2160 let lookup = state.virtual_texts.build_lookup(&state.marker_list, 0, 10);
2162 assert!(lookup.contains_key(&5));
2163 let vtexts = &lookup[&5];
2164 assert_eq!(vtexts.len(), 2);
2165 assert_eq!(vtexts[0].text, ": i32");
2167 assert_eq!(vtexts[1].text, " /* inferred */");
2168 }
2169
2170 #[test]
2171 fn test_virtual_text_clear() {
2172 let mut state = EditorState::new(
2173 80,
2174 24,
2175 crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2176 test_fs(),
2177 );
2178 state.buffer = Buffer::from_str_test("test");
2179
2180 if !state.buffer.is_empty() {
2182 state.marker_list.adjust_for_insert(0, state.buffer.len());
2183 }
2184
2185 state.virtual_texts.add(
2187 &mut state.marker_list,
2188 0,
2189 "hint1".to_string(),
2190 Style::default(),
2191 VirtualTextPosition::BeforeChar,
2192 0,
2193 );
2194 state.virtual_texts.add(
2195 &mut state.marker_list,
2196 2,
2197 "hint2".to_string(),
2198 Style::default(),
2199 VirtualTextPosition::AfterChar,
2200 0,
2201 );
2202
2203 assert_eq!(state.virtual_texts.len(), 2);
2204
2205 state.virtual_texts.clear(&mut state.marker_list);
2207 assert!(state.virtual_texts.is_empty());
2208
2209 let results = state.virtual_texts.query_range(&state.marker_list, 0, 10);
2211 assert!(results.is_empty());
2212 }
2213 }
2214}