Skip to main content

fresh/
state.rs

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/// A marker whose position was displaced by a deletion.
36/// Stored in LogEntry (for single edits) or Event::BulkEdit (for bulk edits).
37/// On undo, the marker is restored to its exact original position.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub enum DisplacedMarker {
40    /// Marker from the main marker_list (virtual text, overlays)
41    Main { id: u64, position: usize },
42    /// Marker from margins.indicator_markers (breakpoints, line indicators)
43    Margin { id: u64, position: usize },
44}
45
46impl DisplacedMarker {
47    /// Encode as (u64, usize) for compact storage. Uses high bit to tag source.
48    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    /// Decode from (u64, usize) compact representation.
56    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/// Display mode for a buffer
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum ViewMode {
74    /// Plain source rendering
75    Source,
76    /// Document-style page view with centered content, concealed markers,
77    /// and plugin-driven word wrapping (previously called "compose mode")
78    PageView,
79}
80
81/// Per-buffer user settings that should be preserved across file reloads (auto-revert).
82///
83/// These are user overrides that apply to a specific buffer, separate from:
84/// - File-derived state (syntax highlighting, language detection)
85/// - View-specific state (scroll position, line wrap - those live in SplitViewState)
86///
87/// TODO: Consider moving view-related settings (line numbers, debug mode) to SplitViewState
88/// to allow per-split preferences. Currently line numbers is in margins (coupled with plugin
89/// gutters), and debug_highlight_mode is in EditorState, but both could arguably be per-view
90/// rather than per-buffer.
91#[derive(Debug, Clone)]
92pub struct BufferSettings {
93    /// Resolved whitespace indicator visibility for this buffer.
94    /// Set based on global + language config; can be toggled per-buffer by user
95    pub whitespace: crate::config::WhitespaceVisibility,
96
97    /// Whether pressing Tab should insert a tab character instead of spaces.
98    /// Set based on language config; can be toggled per-buffer by user
99    pub use_tabs: bool,
100
101    /// Tab size (number of spaces per tab character) for rendering.
102    /// Used for visual display of tab characters and indent calculations.
103    /// Set based on language config; can be changed per-buffer by user
104    pub tab_size: usize,
105
106    /// Whether to auto-close brackets, parentheses, and quotes.
107    /// Set based on global + language config.
108    pub auto_close: bool,
109
110    /// Whether to surround selected text with matching pairs when typing a delimiter.
111    /// Set based on global + language config.
112    pub auto_surround: bool,
113
114    /// Extra characters (beyond alphanumeric + `_`) considered part of
115    /// identifiers for this language. Used by completion providers.
116    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
132/// The complete editor state - everything needed to represent the current editing session
133///
134/// NOTE: Viewport is NOT stored here - it lives in SplitViewState.
135/// This is because viewport is view-specific (each split can view the same buffer
136/// at different scroll positions), while EditorState represents the buffer content.
137pub struct EditorState {
138    /// The text buffer
139    pub buffer: Buffer,
140
141    /// Syntax highlighter (tree-sitter or TextMate based on language)
142    pub highlighter: HighlightEngine,
143
144    /// Auto-indent calculator for smart indentation (RefCell for interior mutability)
145    pub indent_calculator: RefCell<IndentCalculator>,
146
147    /// Overlays for visual decorations (underlines, highlights, etc.)
148    pub overlays: OverlayManager,
149
150    /// Marker list for content-anchored overlay positions
151    pub marker_list: MarkerList,
152
153    /// Virtual text manager for inline hints (type hints, parameter hints, etc.)
154    pub virtual_texts: VirtualTextManager,
155
156    /// Conceal ranges for hiding/replacing byte ranges during rendering
157    pub conceals: ConcealManager,
158
159    /// Soft break points for marker-based line wrapping during rendering
160    pub soft_breaks: SoftBreakManager,
161
162    /// Popups for floating windows (completion, documentation, etc.)
163    pub popups: PopupManager,
164
165    /// Margins for line numbers, annotations, gutter symbols, etc.)
166    pub margins: MarginManager,
167
168    /// Cached line number for primary cursor (0-indexed)
169    /// Maintained incrementally to avoid O(n) scanning on every render
170    pub primary_cursor_line_number: LineNumber,
171
172    /// Current mode (for modal editing, if implemented)
173    pub mode: String,
174
175    /// Text properties for virtual buffers (embedded metadata in text ranges)
176    /// Used by virtual buffers to store location info, severity, etc.
177    pub text_properties: TextPropertyManager,
178
179    /// Whether to show cursors in this buffer (default true)
180    /// Can be set to false for virtual buffers like diagnostics panels
181    pub show_cursors: bool,
182
183    /// Whether editing is disabled for this buffer (default false)
184    /// When true, typing, deletion, cut/paste, undo/redo are blocked
185    /// but navigation, selection, and copy are still allowed
186    pub editing_disabled: bool,
187
188    /// Whether this buffer can be scrolled (default true). Fixed buffer-group
189    /// panels (toolbars, headers, footers) set this to false so the mouse
190    /// wheel is ignored and no scrollbar is drawn.
191    pub scrollable: bool,
192
193    /// Per-buffer user settings (tab size, indentation style, etc.)
194    /// These settings are preserved across file reloads (auto-revert)
195    pub buffer_settings: BufferSettings,
196
197    /// Semantic highlighter for word occurrence highlighting
198    pub reference_highlighter: ReferenceHighlighter,
199
200    /// Whether this buffer is a composite view (e.g., side-by-side diff)
201    pub is_composite_buffer: bool,
202
203    /// Debug mode: reveal highlight/overlay spans (WordPerfect-style)
204    pub debug_highlight_mode: bool,
205
206    /// Debounced semantic highlight cache
207    pub reference_highlight_overlay: ReferenceHighlightOverlay,
208
209    /// Bracket matching highlight overlay
210    pub bracket_highlight_overlay: BracketHighlightOverlay,
211
212    /// Cached LSP semantic tokens (converted to buffer byte ranges)
213    pub semantic_tokens: Option<SemanticTokenStore>,
214
215    /// Last-known LSP folding ranges for this buffer, tracked by byte markers
216    /// so they auto-adjust when content is inserted or deleted around them
217    /// (issue #1571).
218    pub folding_ranges: LspFoldRanges,
219
220    /// The detected language ID for this buffer (e.g., "rust", "csharp", "text").
221    /// Used for LSP config lookup and internal identification.
222    pub language: String,
223
224    /// Human-readable language display name (e.g., "Rust", "C#", "Plain Text").
225    /// Shown in the status bar and Set Language prompt.
226    // TODO: Consider embedding `DetectedLanguage` directly in `EditorState`
227    // instead of copying its fields, to avoid duplication between the two structs.
228    pub display_name: String,
229
230    /// Cached scrollbar visual row counts to avoid O(n) recomputation per frame.
231    /// Invalidated when buffer version, viewport width, or top_byte changes.
232    pub scrollbar_row_cache: ScrollbarRowCache,
233}
234
235/// Cache for scrollbar visual row counts.
236/// Avoids re-wrapping every line in the file on each render frame.
237#[derive(Debug, Clone, Default)]
238pub struct ScrollbarRowCache {
239    /// Buffer version when this cache was computed
240    pub buffer_version: u64,
241    /// Viewport width used for wrapping
242    pub viewport_width: u16,
243    /// Whether wrap indent was enabled
244    pub wrap_indent: bool,
245    /// Cached total visual rows
246    pub total_visual_rows: usize,
247    /// top_byte → top_visual_row mapping from last computation
248    pub top_byte: usize,
249    /// Cached top visual row
250    pub top_visual_row: usize,
251    /// top_view_line_offset used in the computation
252    pub top_view_line_offset: usize,
253    /// Whether the cache has been populated at least once
254    pub valid: bool,
255}
256
257impl EditorState {
258    /// Create a new editor state with an empty buffer
259    ///
260    /// Note: width/height parameters are kept for backward compatibility but
261    /// are no longer used - viewport is now owned by SplitViewState.
262    /// Apply a detected language to this state. This is the single mutation point
263    /// for changing the language of a buffer after creation.
264    pub fn apply_language(&mut self, detected: DetectedLanguage) {
265        self.language = detected.name;
266        self.display_name = detected.display_name;
267        self.highlighter = detected.highlighter;
268        if let Some(lang) = &detected.ts_language {
269            self.reference_highlighter.set_language(lang);
270        }
271    }
272
273    /// Create a new state with a buffer and default (plain text) language.
274    /// All other fields are initialized to their defaults.
275    fn new_from_buffer(buffer: Buffer) -> Self {
276        let mut marker_list = MarkerList::new();
277        if !buffer.is_empty() {
278            marker_list.adjust_for_insert(0, buffer.len());
279        }
280
281        Self {
282            buffer,
283            highlighter: HighlightEngine::None,
284            indent_calculator: RefCell::new(IndentCalculator::new()),
285            overlays: OverlayManager::new(),
286            marker_list,
287            virtual_texts: VirtualTextManager::new(),
288            conceals: ConcealManager::new(),
289            soft_breaks: SoftBreakManager::new(),
290            popups: PopupManager::new(),
291            margins: MarginManager::new(),
292            primary_cursor_line_number: LineNumber::Absolute(0),
293            mode: "insert".to_string(),
294            text_properties: TextPropertyManager::new(),
295            show_cursors: true,
296            editing_disabled: false,
297            scrollable: true,
298            buffer_settings: BufferSettings::default(),
299            reference_highlighter: ReferenceHighlighter::new(),
300            is_composite_buffer: false,
301            debug_highlight_mode: false,
302            reference_highlight_overlay: ReferenceHighlightOverlay::new(),
303            bracket_highlight_overlay: BracketHighlightOverlay::new(),
304            semantic_tokens: None,
305            folding_ranges: LspFoldRanges::new(),
306            language: "text".to_string(),
307            display_name: "Text".to_string(),
308            scrollbar_row_cache: ScrollbarRowCache::default(),
309        }
310    }
311
312    pub fn new(
313        _width: u16,
314        _height: u16,
315        large_file_threshold: usize,
316        fs: Arc<dyn FileSystem + Send + Sync>,
317    ) -> Self {
318        Self::new_from_buffer(Buffer::new(large_file_threshold, fs))
319    }
320
321    /// Create a new editor state with an empty buffer associated with a file path.
322    /// Used for files that don't exist yet — the path is set so saving will create the file.
323    pub fn new_with_path(
324        large_file_threshold: usize,
325        fs: Arc<dyn FileSystem + Send + Sync>,
326        path: std::path::PathBuf,
327    ) -> Self {
328        Self::new_from_buffer(Buffer::new_with_path(large_file_threshold, fs, path))
329    }
330
331    /// Set the syntax highlighting language based on a virtual buffer name.
332    /// Handles names like `*OLD:test.ts*` or `*OURS*.c` by stripping markers
333    /// and detecting language from the cleaned filename.
334    pub fn set_language_from_name(&mut self, name: &str, registry: &GrammarRegistry) {
335        let detected = DetectedLanguage::from_virtual_name(name, registry);
336        tracing::debug!(
337            "Set highlighter for virtual buffer based on name: {} (backend: {}, language: {})",
338            name,
339            detected.highlighter.backend_name(),
340            detected.name
341        );
342        self.apply_language(detected);
343    }
344
345    /// Create an editor state from a file
346    ///
347    /// Note: width/height parameters are kept for backward compatibility but
348    /// are no longer used - viewport is now owned by SplitViewState.
349    pub fn from_file(
350        path: &std::path::Path,
351        _width: u16,
352        _height: u16,
353        large_file_threshold: usize,
354        registry: &GrammarRegistry,
355        fs: Arc<dyn FileSystem + Send + Sync>,
356    ) -> anyhow::Result<Self> {
357        let buffer = Buffer::load_from_file(path, large_file_threshold, fs)?;
358        let first_line = buffer.first_line_lossy();
359        let detected = registry
360            .find_by_path(path, first_line.as_deref())
361            .map(|entry| DetectedLanguage::from_entry(entry, registry))
362            .unwrap_or_else(DetectedLanguage::plain_text);
363        let mut state = Self::new_from_buffer(buffer);
364        state.apply_language(detected);
365        Ok(state)
366    }
367
368    /// Create an editor state from a file with language configuration.
369    ///
370    /// This version uses the provided languages configuration for syntax detection,
371    /// allowing user-configured filename patterns to be respected for highlighting.
372    ///
373    /// Note: width/height parameters are kept for backward compatibility but
374    /// are no longer used - viewport is now owned by SplitViewState.
375    pub fn from_file_with_languages(
376        path: &std::path::Path,
377        _width: u16,
378        _height: u16,
379        large_file_threshold: usize,
380        registry: &GrammarRegistry,
381        languages: &std::collections::HashMap<String, crate::config::LanguageConfig>,
382        fs: Arc<dyn FileSystem + Send + Sync>,
383    ) -> anyhow::Result<Self> {
384        let buffer = Buffer::load_from_file(path, large_file_threshold, fs)?;
385        let first_line = buffer.first_line_lossy();
386        let detected =
387            DetectedLanguage::from_path(path, first_line.as_deref(), registry, languages);
388        let mut state = Self::new_from_buffer(buffer);
389        state.apply_language(detected);
390        Ok(state)
391    }
392
393    /// Create an editor state from a buffer and a pre-built `DetectedLanguage`.
394    ///
395    /// This is useful when you have already loaded a buffer with a specific encoding
396    /// and want to create an EditorState from it.
397    pub fn from_buffer_with_language(buffer: Buffer, detected: DetectedLanguage) -> Self {
398        let mut state = Self::new_from_buffer(buffer);
399        state.apply_language(detected);
400        state
401    }
402
403    /// Handle an Insert event - adjusts markers, buffer, highlighter, cursors, and line numbers
404    fn apply_insert(
405        &mut self,
406        cursors: &mut Cursors,
407        position: usize,
408        text: &str,
409        cursor_id: crate::model::event::CursorId,
410    ) {
411        let newlines_inserted = text.matches('\n').count();
412
413        // CRITICAL: Adjust markers BEFORE modifying buffer
414        self.marker_list.adjust_for_insert(position, text.len());
415        self.margins.adjust_for_insert(position, text.len());
416
417        // Insert text into buffer
418        self.buffer.insert(position, text);
419
420        // Notify highlighter of the insert (adjusts checkpoint marker positions)
421        // and invalidate span cache for the edited range.
422        self.highlighter.notify_insert(position, text.len());
423        self.highlighter
424            .invalidate_range(position..position + text.len());
425
426        // Note: reference_highlight_overlay uses markers that auto-adjust,
427        // so no manual invalidation needed
428
429        // Adjust all cursors after the edit
430        cursors.adjust_for_edit(position, 0, text.len());
431
432        // Move the cursor that made the edit to the end of the insertion
433        if let Some(cursor) = cursors.get_mut(cursor_id) {
434            cursor.position = position + text.len();
435            cursor.clear_selection();
436        }
437
438        // Update primary cursor line number if this was the primary cursor
439        if cursor_id == cursors.primary_id() {
440            self.primary_cursor_line_number = match self.primary_cursor_line_number {
441                LineNumber::Absolute(line) => LineNumber::Absolute(line + newlines_inserted),
442                LineNumber::Relative {
443                    line,
444                    from_cached_line,
445                } => LineNumber::Relative {
446                    line: line + newlines_inserted,
447                    from_cached_line,
448                },
449            };
450        }
451    }
452
453    /// Handle a Delete event - adjusts markers, buffer, highlighter, cursors, and line numbers
454    fn apply_delete(
455        &mut self,
456        cursors: &mut Cursors,
457        range: &std::ops::Range<usize>,
458        cursor_id: crate::model::event::CursorId,
459        deleted_text: &str,
460    ) {
461        let len = range.len();
462
463        // Count newlines deleted BEFORE the primary cursor's original position.
464        // For backspace: cursor was at range.end, so all deleted newlines are before it.
465        // For forward delete: cursor was at range.start, so no deleted newlines are before it.
466        let primary_newlines_removed = if cursor_id == cursors.primary_id() {
467            let cursor_pos = cursors.get(cursor_id).map_or(range.start, |c| c.position);
468            let bytes_before_cursor = cursor_pos.saturating_sub(range.start).min(len);
469            deleted_text[..bytes_before_cursor].matches('\n').count()
470        } else {
471            0
472        };
473
474        // Drop virtual texts whose anchors are being erased. This is what
475        // makes inlay hints disappear immediately when the range containing
476        // them is deleted; without this the marker would just clamp to
477        // range.start and the hint would linger at the wrong position until
478        // the next LSP refresh.
479        self.virtual_texts
480            .remove_in_range(&mut self.marker_list, range.start, range.end);
481
482        // CRITICAL: Adjust markers BEFORE modifying buffer
483        self.marker_list.adjust_for_delete(range.start, len);
484        self.margins.adjust_for_delete(range.start, len);
485
486        // Delete from buffer
487        self.buffer.delete(range.clone());
488
489        // Notify highlighter of the delete (adjusts checkpoint marker positions)
490        // and invalidate span cache for the edited range.
491        self.highlighter.notify_delete(range.start, len);
492        self.highlighter.invalidate_range(range.clone());
493
494        // Note: reference_highlight_overlay uses markers that auto-adjust,
495        // so no manual invalidation needed
496
497        // Adjust all cursors after the edit
498        cursors.adjust_for_edit(range.start, len, 0);
499
500        // Move the cursor that made the edit to the start of deletion
501        if let Some(cursor) = cursors.get_mut(cursor_id) {
502            cursor.position = range.start;
503            cursor.clear_selection();
504        }
505
506        // Update primary cursor line number if this was the primary cursor
507        if cursor_id == cursors.primary_id() && primary_newlines_removed > 0 {
508            self.primary_cursor_line_number = match self.primary_cursor_line_number {
509                LineNumber::Absolute(line) => {
510                    LineNumber::Absolute(line.saturating_sub(primary_newlines_removed))
511                }
512                LineNumber::Relative {
513                    line,
514                    from_cached_line,
515                } => LineNumber::Relative {
516                    line: line.saturating_sub(primary_newlines_removed),
517                    from_cached_line,
518                },
519            };
520        }
521    }
522
523    /// Apply an event to the state - THE ONLY WAY TO MODIFY STATE
524    /// This is the heart of the event-driven architecture
525    pub fn apply(&mut self, cursors: &mut Cursors, event: &Event) {
526        match event {
527            Event::Insert {
528                position,
529                text,
530                cursor_id,
531            } => self.apply_insert(cursors, *position, text, *cursor_id),
532
533            Event::Delete {
534                range,
535                cursor_id,
536                deleted_text,
537            } => self.apply_delete(cursors, range, *cursor_id, deleted_text),
538
539            Event::MoveCursor {
540                cursor_id,
541                new_position,
542                new_anchor,
543                new_sticky_column,
544                ..
545            } => {
546                if let Some(cursor) = cursors.get_mut(*cursor_id) {
547                    cursor.position = *new_position;
548                    cursor.anchor = *new_anchor;
549                    cursor.sticky_column = *new_sticky_column;
550                }
551
552                // Update primary cursor line number if this is the primary cursor
553                // Try to get exact line number from buffer, or estimate for large files
554                if *cursor_id == cursors.primary_id() {
555                    self.primary_cursor_line_number =
556                        match self.buffer.offset_to_position(*new_position) {
557                            Some(pos) => LineNumber::Absolute(pos.line),
558                            None => {
559                                // Large file without line metadata - estimate line number
560                                // Use default estimated_line_length of 80 bytes
561                                let estimated_line = *new_position / 80;
562                                LineNumber::Absolute(estimated_line)
563                            }
564                        };
565                }
566            }
567
568            Event::AddCursor {
569                cursor_id,
570                position,
571                anchor,
572            } => {
573                let cursor = if let Some(anchor) = anchor {
574                    Cursor::with_selection(*anchor, *position)
575                } else {
576                    Cursor::new(*position)
577                };
578
579                // Insert cursor with the specific ID from the event
580                // This is important for undo/redo to work correctly
581                cursors.insert_with_id(*cursor_id, cursor);
582
583                cursors.normalize();
584            }
585
586            Event::RemoveCursor { cursor_id, .. } => {
587                cursors.remove(*cursor_id);
588            }
589
590            // View events (Scroll, SetViewport, Recenter) are now handled at Editor level
591            // via SplitViewState. They should not reach EditorState.apply().
592            Event::Scroll { .. } | Event::SetViewport { .. } | Event::Recenter => {
593                // These events are intercepted in Editor::apply_event_to_active_buffer
594                // and routed to SplitViewState. If we get here, something is wrong.
595                tracing::warn!("View event {:?} reached EditorState.apply() - should be handled by SplitViewState", event);
596            }
597
598            Event::SetAnchor {
599                cursor_id,
600                position,
601            } => {
602                // Set the anchor (selection start) for a specific cursor
603                // Also disable deselect_on_move so movement preserves the selection (Emacs mark mode)
604                if let Some(cursor) = cursors.get_mut(*cursor_id) {
605                    cursor.anchor = Some(*position);
606                    cursor.deselect_on_move = false;
607                }
608            }
609
610            Event::ClearAnchor { cursor_id } => {
611                // Clear the anchor and reset deselect_on_move to cancel mark mode
612                // Also clear block selection if active
613                if let Some(cursor) = cursors.get_mut(*cursor_id) {
614                    cursor.anchor = None;
615                    cursor.deselect_on_move = true;
616                    cursor.clear_block_selection();
617                }
618            }
619
620            Event::ChangeMode { mode } => {
621                self.mode = mode.clone();
622            }
623
624            Event::AddOverlay {
625                namespace,
626                range,
627                face,
628                priority,
629                message,
630                extend_to_line_end,
631                url,
632            } => {
633                tracing::trace!(
634                    "AddOverlay: namespace={:?}, range={:?}, face={:?}, priority={}",
635                    namespace,
636                    range,
637                    face,
638                    priority
639                );
640                // Convert event overlay face to overlay face
641                let overlay_face = convert_event_face_to_overlay_face(face);
642                tracing::trace!("Converted face: {:?}", overlay_face);
643
644                let mut overlay = Overlay::with_priority(
645                    &mut self.marker_list,
646                    range.clone(),
647                    overlay_face,
648                    *priority,
649                );
650                overlay.namespace = namespace.clone();
651                overlay.message = message.clone();
652                overlay.extend_to_line_end = *extend_to_line_end;
653                overlay.url = url.clone();
654
655                let actual_range = overlay.range(&self.marker_list);
656                tracing::trace!(
657                    "Created overlay with markers - actual range: {:?}, handle={:?}",
658                    actual_range,
659                    overlay.handle
660                );
661
662                self.overlays.add(overlay);
663            }
664
665            Event::RemoveOverlay { handle } => {
666                tracing::trace!("RemoveOverlay: handle={:?}", handle);
667                self.overlays
668                    .remove_by_handle(handle, &mut self.marker_list);
669            }
670
671            Event::RemoveOverlaysInRange { range } => {
672                self.overlays.remove_in_range(range, &mut self.marker_list);
673            }
674
675            Event::ClearNamespace { namespace } => {
676                tracing::trace!("ClearNamespace: namespace={:?}", namespace);
677                self.overlays
678                    .clear_namespace(namespace, &mut self.marker_list);
679            }
680
681            Event::ClearOverlays => {
682                self.overlays.clear(&mut self.marker_list);
683            }
684
685            Event::ShowPopup { popup } => {
686                let popup_obj = convert_popup_data_to_popup(popup);
687                self.popups.show_or_replace(popup_obj);
688            }
689
690            Event::HidePopup => {
691                self.popups.hide();
692            }
693
694            Event::ClearPopups => {
695                self.popups.clear();
696            }
697
698            Event::PopupSelectNext => {
699                if let Some(popup) = self.popups.top_mut() {
700                    popup.select_next();
701                }
702            }
703
704            Event::PopupSelectPrev => {
705                if let Some(popup) = self.popups.top_mut() {
706                    popup.select_prev();
707                }
708            }
709
710            Event::PopupPageDown => {
711                if let Some(popup) = self.popups.top_mut() {
712                    popup.page_down();
713                }
714            }
715
716            Event::PopupPageUp => {
717                if let Some(popup) = self.popups.top_mut() {
718                    popup.page_up();
719                }
720            }
721
722            Event::AddMarginAnnotation {
723                line,
724                position,
725                content,
726                annotation_id,
727            } => {
728                let margin_position = convert_margin_position(position);
729                let margin_content = convert_margin_content(content);
730                let annotation = if let Some(id) = annotation_id {
731                    MarginAnnotation::with_id(*line, margin_position, margin_content, id.clone())
732                } else {
733                    MarginAnnotation::new(*line, margin_position, margin_content)
734                };
735                self.margins.add_annotation(annotation);
736            }
737
738            Event::RemoveMarginAnnotation { annotation_id } => {
739                self.margins.remove_by_id(annotation_id);
740            }
741
742            Event::RemoveMarginAnnotationsAtLine { line, position } => {
743                let margin_position = convert_margin_position(position);
744                self.margins.remove_at_line(*line, margin_position);
745            }
746
747            Event::ClearMarginPosition { position } => {
748                let margin_position = convert_margin_position(position);
749                self.margins.clear_position(margin_position);
750            }
751
752            Event::ClearMargins => {
753                self.margins.clear_all();
754            }
755
756            Event::SetLineNumbers { enabled } => {
757                self.margins.configure_for_line_numbers(*enabled);
758            }
759
760            // Split events are handled at the Editor level, not at EditorState level
761            // These are no-ops here as they affect the split layout, not buffer state
762            Event::SplitPane { .. }
763            | Event::CloseSplit { .. }
764            | Event::SetActiveSplit { .. }
765            | Event::AdjustSplitRatio { .. }
766            | Event::NextSplit
767            | Event::PrevSplit => {
768                // No-op: split events are handled by Editor, not EditorState
769            }
770
771            Event::Batch { events, .. } => {
772                // Apply all events in the batch sequentially
773                // This ensures multi-cursor operations are applied atomically
774                for event in events {
775                    self.apply(cursors, event);
776                }
777            }
778
779            Event::BulkEdit {
780                new_snapshot,
781                new_cursors,
782                edits,
783                displaced_markers,
784                ..
785            } => {
786                // Restore the target buffer state (piece tree + buffers) for this event.
787                // - For undo: snapshots are swapped, so new_snapshot is the original state
788                // - For redo: new_snapshot is the state after edits
789                // Restoring buffers alongside the tree is critical because
790                // consolidate_after_save() can replace buffers between snapshot and restore.
791                if let Some(snapshot) = new_snapshot {
792                    self.buffer.restore_buffer_state(snapshot);
793                }
794
795                // Replay marker adjustments from the edit list.
796                // For redo: same adjustments as the forward path.
797                // For undo: inverse() has swapped del/ins, so adjustments are reversed.
798                // Edits are in descending position order — process as-is so later
799                // positions are adjusted first (no cascading shift errors).
800                //
801                // For replacements (del > 0 AND ins > 0 at same position), we only
802                // adjust for the net delta to avoid the marker-at-boundary problem
803                // where sequential delete+insert pushes markers incorrectly.
804                for &(pos, del_len, ins_len) in edits {
805                    if del_len > 0 && ins_len > 0 {
806                        // Replacement: adjust by net delta only
807                        if ins_len > del_len {
808                            let net = ins_len - del_len;
809                            self.marker_list.adjust_for_insert(pos, net);
810                            self.margins.adjust_for_insert(pos, net);
811                        } else if del_len > ins_len {
812                            let net = del_len - ins_len;
813                            self.marker_list.adjust_for_delete(pos, net);
814                            self.margins.adjust_for_delete(pos, net);
815                        }
816                        // If equal: net delta 0, no adjustment needed
817                    } else if del_len > 0 {
818                        self.marker_list.adjust_for_delete(pos, del_len);
819                        self.margins.adjust_for_delete(pos, del_len);
820                    } else if ins_len > 0 {
821                        self.marker_list.adjust_for_insert(pos, ins_len);
822                        self.margins.adjust_for_insert(pos, ins_len);
823                    }
824                }
825
826                // Restore displaced markers to their original positions.
827                // This fixes markers that were inside a deleted range and collapsed
828                // to the deletion boundary — they're now moved back to their exact
829                // original positions after the text has been restored by undo.
830                if !displaced_markers.is_empty() {
831                    self.restore_displaced_markers(displaced_markers);
832                }
833
834                // Clear ephemeral decorations — their source systems will re-push
835                // correct positions after the edit notification.
836                self.virtual_texts.clear(&mut self.marker_list);
837
838                use crate::view::overlay::OverlayNamespace;
839                let namespaces = ["lsp-diagnostic", "reference-highlight", "bracket-highlight"];
840                for ns in &namespaces {
841                    self.overlays.clear_namespace(
842                        &OverlayNamespace::from_string(ns.to_string()),
843                        &mut self.marker_list,
844                    );
845                }
846
847                // Update cursor positions
848                for (cursor_id, position, anchor) in new_cursors {
849                    if let Some(cursor) = cursors.get_mut(*cursor_id) {
850                        cursor.position = *position;
851                        cursor.anchor = *anchor;
852                    }
853                }
854
855                // Invalidate highlight cache for entire buffer
856                self.highlighter.invalidate_all();
857
858                // Update primary cursor line number
859                let primary_pos = cursors.primary().position;
860                self.primary_cursor_line_number = match self.buffer.offset_to_position(primary_pos)
861                {
862                    Some(pos) => crate::model::buffer::LineNumber::Absolute(pos.line),
863                    None => crate::model::buffer::LineNumber::Absolute(0),
864                };
865            }
866        }
867    }
868
869    /// Capture positions of markers strictly inside a deleted range.
870    /// Call this BEFORE applying the delete. Returns encoded displaced markers.
871    pub fn capture_displaced_markers(&self, range: &Range<usize>) -> Vec<(u64, usize)> {
872        let mut displaced = Vec::new();
873        if range.is_empty() {
874            return displaced;
875        }
876        for (marker_id, start, _end) in self.marker_list.query_range(range.start, range.end) {
877            if start > range.start && start < range.end {
878                displaced.push(
879                    DisplacedMarker::Main {
880                        id: marker_id.0,
881                        position: start,
882                    }
883                    .encode(),
884                );
885            }
886        }
887        for (marker_id, start, _end) in self.margins.query_indicator_range(range.start, range.end) {
888            if start > range.start && start < range.end {
889                displaced.push(
890                    DisplacedMarker::Margin {
891                        id: marker_id.0,
892                        position: start,
893                    }
894                    .encode(),
895                );
896            }
897        }
898        displaced
899    }
900
901    /// Capture displaced markers for multiple delete ranges (BulkEdit).
902    pub fn capture_displaced_markers_bulk(
903        &self,
904        edits: &[(usize, usize, String)],
905    ) -> Vec<(u64, usize)> {
906        let mut displaced = Vec::new();
907        for (pos, del_len, _text) in edits {
908            if *del_len > 0 {
909                displaced.extend(self.capture_displaced_markers(&(*pos..*pos + *del_len)));
910            }
911        }
912        displaced
913    }
914
915    /// Restore displaced markers to their exact original positions.
916    pub fn restore_displaced_markers(&mut self, displaced: &[(u64, usize)]) {
917        for &(tagged_id, original_pos) in displaced {
918            let dm = DisplacedMarker::decode(tagged_id, original_pos);
919            match dm {
920                DisplacedMarker::Main { id, position } => {
921                    self.marker_list.set_position(MarkerId(id), position);
922                }
923                DisplacedMarker::Margin { id, position } => {
924                    self.margins.set_indicator_position(MarkerId(id), position);
925                }
926            }
927        }
928    }
929
930    /// Apply multiple events in sequence
931    pub fn apply_many(&mut self, cursors: &mut Cursors, events: &[Event]) {
932        for event in events {
933            self.apply(cursors, event);
934        }
935    }
936
937    /// Called when this buffer loses focus (e.g., switching to another buffer,
938    /// opening a prompt, focusing file explorer, etc.)
939    /// Dismisses transient popups like Hover and Signature Help.
940    pub fn on_focus_lost(&mut self) {
941        if self.popups.dismiss_transient() {
942            tracing::debug!("Dismissed transient popup on buffer focus loss");
943        }
944    }
945}
946
947/// Convert event overlay face to the actual overlay face
948fn convert_event_face_to_overlay_face(event_face: &EventOverlayFace) -> OverlayFace {
949    match event_face {
950        EventOverlayFace::Underline { color, style } => {
951            let underline_style = match style {
952                crate::model::event::UnderlineStyle::Straight => UnderlineStyle::Straight,
953                crate::model::event::UnderlineStyle::Wavy => UnderlineStyle::Wavy,
954                crate::model::event::UnderlineStyle::Dotted => UnderlineStyle::Dotted,
955                crate::model::event::UnderlineStyle::Dashed => UnderlineStyle::Dashed,
956            };
957            OverlayFace::Underline {
958                color: Color::Rgb(color.0, color.1, color.2),
959                style: underline_style,
960            }
961        }
962        EventOverlayFace::Background { color } => OverlayFace::Background {
963            color: Color::Rgb(color.0, color.1, color.2),
964        },
965        EventOverlayFace::Foreground { color } => OverlayFace::Foreground {
966            color: Color::Rgb(color.0, color.1, color.2),
967        },
968        EventOverlayFace::Style { options } => {
969            use crate::view::theme::named_color_from_str;
970            use ratatui::style::Modifier;
971
972            // Build fallback style from RGB values or named colors
973            let mut style = Style::default();
974
975            // Extract foreground color (RGB, named color, or default white)
976            if let Some(ref fg) = options.fg {
977                if let Some((r, g, b)) = fg.as_rgb() {
978                    style = style.fg(Color::Rgb(r, g, b));
979                } else if let Some(key) = fg.as_theme_key() {
980                    if let Some(color) = named_color_from_str(key) {
981                        style = style.fg(color);
982                    }
983                }
984            }
985
986            // Extract background color (RGB, named color, or fallback)
987            if let Some(ref bg) = options.bg {
988                if let Some((r, g, b)) = bg.as_rgb() {
989                    style = style.bg(Color::Rgb(r, g, b));
990                } else if let Some(key) = bg.as_theme_key() {
991                    if let Some(color) = named_color_from_str(key) {
992                        style = style.bg(color);
993                    }
994                }
995            }
996
997            // Apply modifiers
998            let mut modifiers = Modifier::empty();
999            if options.bold {
1000                modifiers |= Modifier::BOLD;
1001            }
1002            if options.italic {
1003                modifiers |= Modifier::ITALIC;
1004            }
1005            if options.underline {
1006                modifiers |= Modifier::UNDERLINED;
1007            }
1008            if options.strikethrough {
1009                modifiers |= Modifier::CROSSED_OUT;
1010            }
1011            if !modifiers.is_empty() {
1012                style = style.add_modifier(modifiers);
1013            }
1014
1015            // Extract theme keys (exclude recognized named colors, already resolved above)
1016            let fg_theme = options
1017                .fg
1018                .as_ref()
1019                .and_then(|c| c.as_theme_key())
1020                .filter(|key| named_color_from_str(key).is_none())
1021                .map(String::from);
1022            let bg_theme = options
1023                .bg
1024                .as_ref()
1025                .and_then(|c| c.as_theme_key())
1026                .filter(|key| named_color_from_str(key).is_none())
1027                .map(String::from);
1028
1029            // If theme keys are provided, use ThemedStyle for runtime resolution
1030            if fg_theme.is_some() || bg_theme.is_some() {
1031                OverlayFace::ThemedStyle {
1032                    fallback_style: style,
1033                    fg_theme,
1034                    bg_theme,
1035                }
1036            } else {
1037                OverlayFace::Style { style }
1038            }
1039        }
1040    }
1041}
1042
1043/// Convert popup data to the actual popup object
1044pub(crate) fn convert_popup_data_to_popup(data: &PopupData) -> Popup {
1045    let content = match &data.content {
1046        crate::model::event::PopupContentData::Text(lines) => PopupContent::Text(lines.clone()),
1047        crate::model::event::PopupContentData::List { items, selected } => PopupContent::List {
1048            items: items
1049                .iter()
1050                .map(|item| PopupListItem {
1051                    text: item.text.clone(),
1052                    detail: item.detail.clone(),
1053                    icon: item.icon.clone(),
1054                    data: item.data.clone(),
1055                    disabled: false,
1056                })
1057                .collect(),
1058            selected: *selected,
1059        },
1060    };
1061
1062    let position = match data.position {
1063        PopupPositionData::AtCursor => PopupPosition::AtCursor,
1064        PopupPositionData::BelowCursor => PopupPosition::BelowCursor,
1065        PopupPositionData::AboveCursor => PopupPosition::AboveCursor,
1066        PopupPositionData::Fixed { x, y } => PopupPosition::Fixed { x, y },
1067        PopupPositionData::Centered => PopupPosition::Centered,
1068        PopupPositionData::BottomRight => PopupPosition::BottomRight,
1069        PopupPositionData::AboveStatusBarAt { x } => PopupPosition::AboveStatusBarAt { x },
1070    };
1071
1072    // Map the explicit kind hint to PopupKind for input handling
1073    let kind = match data.kind {
1074        crate::model::event::PopupKindHint::Completion => PopupKind::Completion,
1075        crate::model::event::PopupKindHint::List => PopupKind::List,
1076        crate::model::event::PopupKindHint::Text => PopupKind::Text,
1077    };
1078
1079    Popup {
1080        kind,
1081        title: data.title.clone(),
1082        description: data.description.clone(),
1083        transient: data.transient,
1084        content,
1085        position,
1086        width: data.width,
1087        max_height: data.max_height,
1088        bordered: data.bordered,
1089        border_style: Style::default().fg(Color::Gray),
1090        background_style: Style::default().bg(Color::Rgb(30, 30, 30)),
1091        scroll_offset: 0,
1092        text_selection: None,
1093        accept_key_hint: None,
1094    }
1095}
1096
1097/// Convert margin position data to the actual margin position
1098fn convert_margin_position(position: &MarginPositionData) -> MarginPosition {
1099    match position {
1100        MarginPositionData::Left => MarginPosition::Left,
1101        MarginPositionData::Right => MarginPosition::Right,
1102    }
1103}
1104
1105/// Convert margin content data to the actual margin content
1106fn convert_margin_content(content: &MarginContentData) -> MarginContent {
1107    match content {
1108        MarginContentData::Text(text) => MarginContent::Text(text.clone()),
1109        MarginContentData::Symbol { text, color } => {
1110            if let Some((r, g, b)) = color {
1111                MarginContent::colored_symbol(text.clone(), Color::Rgb(*r, *g, *b))
1112            } else {
1113                MarginContent::symbol(text.clone(), Style::default())
1114            }
1115        }
1116        MarginContentData::Empty => MarginContent::Empty,
1117    }
1118}
1119
1120impl EditorState {
1121    /// Prepare viewport for rendering (called before frame render)
1122    ///
1123    /// This pre-loads all data that will be needed for rendering the current viewport,
1124    /// ensuring that subsequent read-only access during rendering will succeed.
1125    ///
1126    /// Takes viewport parameters since viewport is now owned by SplitViewState.
1127    pub fn prepare_for_render(&mut self, top_byte: usize, height: u16) -> Result<()> {
1128        self.buffer.prepare_viewport(top_byte, height as usize)?;
1129        Ok(())
1130    }
1131
1132    /// Resolve all plugin-injected soft-break byte positions for this buffer.
1133    ///
1134    /// Returns a sorted slice suitable for passing to `Viewport::scroll_up` /
1135    /// `scroll_down`, which use it to keep their visual-row counting in
1136    /// lock-step with the renderer (which applies these same breaks via
1137    /// `apply_soft_breaks`). Empty when no plugin is wrapping the buffer.
1138    pub fn collect_soft_break_positions(&self) -> Vec<usize> {
1139        if self.soft_breaks.is_empty() {
1140            return Vec::new();
1141        }
1142        // query_viewport already returns positions sorted ascending.
1143        self.soft_breaks
1144            .query_viewport(0, self.buffer.len() + 1, &self.marker_list)
1145            .into_iter()
1146            .map(|(pos, _indent)| pos)
1147            .collect()
1148    }
1149
1150    // ========== DocumentModel Helper Methods ==========
1151    // These methods provide convenient access to DocumentModel functionality
1152    // while maintaining backward compatibility with existing code.
1153
1154    /// Get text in a range, driving lazy loading transparently
1155    ///
1156    /// This is a convenience wrapper around DocumentModel::get_range that:
1157    /// - Drives lazy loading automatically (never fails due to unloaded data)
1158    /// - Uses byte offsets directly
1159    /// - Returns String (not Result) - errors are logged internally
1160    /// - Returns empty string for invalid ranges
1161    ///
1162    /// This is the preferred API for getting text ranges. The caller never needs
1163    /// to worry about lazy loading or buffer preparation.
1164    ///
1165    /// # Example
1166    /// ```ignore
1167    /// let text = state.get_text_range(0, 100);
1168    /// ```
1169    pub fn get_text_range(&mut self, start: usize, end: usize) -> String {
1170        // TextBuffer::get_text_range_mut() handles lazy loading automatically
1171        match self
1172            .buffer
1173            .get_text_range_mut(start, end.saturating_sub(start))
1174        {
1175            Ok(bytes) => String::from_utf8_lossy(&bytes).into_owned(),
1176            Err(e) => {
1177                tracing::warn!("Failed to get text range {}..{}: {}", start, end, e);
1178                String::new()
1179            }
1180        }
1181    }
1182
1183    /// Get the content of a line by its byte offset
1184    ///
1185    /// Returns the line containing the given offset, along with its start position.
1186    /// This uses DocumentModel's viewport functionality for consistent behavior.
1187    ///
1188    /// # Returns
1189    /// `Some((line_start_offset, line_content))` if successful, `None` if offset is invalid
1190    pub fn get_line_at_offset(&mut self, offset: usize) -> Option<(usize, String)> {
1191        use crate::model::document_model::DocumentModel;
1192
1193        // Find the start of the line containing this offset
1194        // Scan backwards to find the previous newline or start of buffer
1195        let mut line_start = offset;
1196        while line_start > 0 {
1197            if let Ok(text) = self.buffer.get_text_range_mut(line_start - 1, 1) {
1198                if text.first() == Some(&b'\n') {
1199                    break;
1200                }
1201                line_start -= 1;
1202            } else {
1203                break;
1204            }
1205        }
1206
1207        // Get a single line viewport starting at the line start
1208        let viewport = self
1209            .get_viewport_content(
1210                crate::model::document_model::DocumentPosition::byte(line_start),
1211                1,
1212            )
1213            .ok()?;
1214
1215        viewport
1216            .lines
1217            .first()
1218            .map(|line| (line.byte_offset, line.content.clone()))
1219    }
1220
1221    /// Get text from current cursor position to end of line
1222    ///
1223    /// This is a common pattern in editing operations. Uses DocumentModel
1224    /// for consistent behavior across file sizes.
1225    pub fn get_text_to_end_of_line(&mut self, cursor_pos: usize) -> Result<String> {
1226        use crate::model::document_model::DocumentModel;
1227
1228        // Get the line containing cursor
1229        let viewport = self.get_viewport_content(
1230            crate::model::document_model::DocumentPosition::byte(cursor_pos),
1231            1,
1232        )?;
1233
1234        if let Some(line) = viewport.lines.first() {
1235            let line_start = line.byte_offset;
1236            let line_end = line_start + line.content.len();
1237
1238            if cursor_pos >= line_start && cursor_pos <= line_end {
1239                let offset_in_line = cursor_pos - line_start;
1240                // Use get() to safely handle potential non-char-boundary offsets
1241                Ok(line.content.get(offset_in_line..).unwrap_or("").to_string())
1242            } else {
1243                Ok(String::new())
1244            }
1245        } else {
1246            Ok(String::new())
1247        }
1248    }
1249
1250    /// Replace cached semantic tokens with a new store.
1251    pub fn set_semantic_tokens(&mut self, store: SemanticTokenStore) {
1252        self.semantic_tokens = Some(store);
1253    }
1254
1255    /// Clear cached semantic tokens (e.g., when tokens are invalidated).
1256    pub fn clear_semantic_tokens(&mut self) {
1257        self.semantic_tokens = None;
1258    }
1259
1260    /// Get the server-provided semantic token result_id if available.
1261    pub fn semantic_tokens_result_id(&self) -> Option<&str> {
1262        self.semantic_tokens
1263            .as_ref()
1264            .and_then(|store| store.result_id.as_deref())
1265    }
1266}
1267
1268/// Implement DocumentModel trait for EditorState
1269///
1270/// This provides a clean abstraction layer between rendering/editing operations
1271/// and the underlying text buffer implementation.
1272impl DocumentModel for EditorState {
1273    fn capabilities(&self) -> DocumentCapabilities {
1274        let line_count = self.buffer.line_count();
1275        DocumentCapabilities {
1276            has_line_index: line_count.is_some(),
1277            uses_lazy_loading: false, // TODO: add large file detection
1278            byte_length: self.buffer.len(),
1279            approximate_line_count: line_count.unwrap_or_else(|| {
1280                // Estimate assuming ~80 bytes per line
1281                self.buffer.len() / 80
1282            }),
1283        }
1284    }
1285
1286    fn get_viewport_content(
1287        &mut self,
1288        start_pos: DocumentPosition,
1289        max_lines: usize,
1290    ) -> Result<ViewportContent> {
1291        // Convert to byte offset
1292        let start_offset = self.position_to_offset(start_pos)?;
1293
1294        // Use new efficient line iteration that tracks line numbers during iteration
1295        // by accumulating line_feed_cnt from pieces (single source of truth)
1296        let line_iter = self.buffer.iter_lines_from(start_offset, max_lines)?;
1297        let has_more = line_iter.has_more;
1298
1299        let lines = line_iter
1300            .map(|line_data| ViewportLine {
1301                byte_offset: line_data.byte_offset,
1302                content: line_data.content,
1303                has_newline: line_data.has_newline,
1304                approximate_line_number: line_data.line_number,
1305            })
1306            .collect();
1307
1308        Ok(ViewportContent {
1309            start_position: DocumentPosition::ByteOffset(start_offset),
1310            lines,
1311            has_more,
1312        })
1313    }
1314
1315    fn position_to_offset(&self, pos: DocumentPosition) -> Result<usize> {
1316        match pos {
1317            DocumentPosition::ByteOffset(offset) => Ok(offset),
1318            DocumentPosition::LineColumn { line, column } => {
1319                if !self.has_line_index() {
1320                    anyhow::bail!("Line indexing not available for this document");
1321                }
1322                // Use piece tree's position conversion
1323                let position = crate::model::piece_tree::Position { line, column };
1324                Ok(self.buffer.position_to_offset(position))
1325            }
1326        }
1327    }
1328
1329    fn offset_to_position(&self, offset: usize) -> DocumentPosition {
1330        if self.has_line_index() {
1331            if let Some(pos) = self.buffer.offset_to_position(offset) {
1332                DocumentPosition::LineColumn {
1333                    line: pos.line,
1334                    column: pos.column,
1335                }
1336            } else {
1337                // Line index exists but metadata unavailable - fall back to byte offset
1338                DocumentPosition::ByteOffset(offset)
1339            }
1340        } else {
1341            DocumentPosition::ByteOffset(offset)
1342        }
1343    }
1344
1345    fn get_range(&mut self, start: DocumentPosition, end: DocumentPosition) -> Result<String> {
1346        let start_offset = self.position_to_offset(start)?;
1347        let end_offset = self.position_to_offset(end)?;
1348
1349        if start_offset > end_offset {
1350            anyhow::bail!(
1351                "Invalid range: start offset {} > end offset {}",
1352                start_offset,
1353                end_offset
1354            );
1355        }
1356
1357        let bytes = self
1358            .buffer
1359            .get_text_range_mut(start_offset, end_offset - start_offset)?;
1360
1361        Ok(String::from_utf8_lossy(&bytes).into_owned())
1362    }
1363
1364    fn get_line_content(&mut self, line_number: usize) -> Option<String> {
1365        if !self.has_line_index() {
1366            return None;
1367        }
1368
1369        // Convert line number to byte offset
1370        let line_start_offset = self.buffer.line_start_offset(line_number)?;
1371
1372        // Get line content using iterator
1373        let mut iter = self.buffer.line_iterator(line_start_offset, 80);
1374        if let Some((_start, content)) = iter.next_line() {
1375            let has_newline = content.ends_with('\n');
1376            let line_content = if has_newline {
1377                content[..content.len() - 1].to_string()
1378            } else {
1379                content
1380            };
1381            Some(line_content)
1382        } else {
1383            None
1384        }
1385    }
1386
1387    fn get_chunk_at_offset(&mut self, offset: usize, size: usize) -> Result<(usize, String)> {
1388        let bytes = self.buffer.get_text_range_mut(offset, size)?;
1389
1390        Ok((offset, String::from_utf8_lossy(&bytes).into_owned()))
1391    }
1392
1393    fn insert(&mut self, pos: DocumentPosition, text: &str) -> Result<usize> {
1394        let offset = self.position_to_offset(pos)?;
1395        self.buffer.insert_bytes(offset, text.as_bytes().to_vec());
1396        Ok(text.len())
1397    }
1398
1399    fn delete(&mut self, start: DocumentPosition, end: DocumentPosition) -> Result<()> {
1400        let start_offset = self.position_to_offset(start)?;
1401        let end_offset = self.position_to_offset(end)?;
1402
1403        if start_offset > end_offset {
1404            anyhow::bail!(
1405                "Invalid range: start offset {} > end offset {}",
1406                start_offset,
1407                end_offset
1408            );
1409        }
1410
1411        self.buffer.delete(start_offset..end_offset);
1412        Ok(())
1413    }
1414
1415    fn replace(
1416        &mut self,
1417        start: DocumentPosition,
1418        end: DocumentPosition,
1419        text: &str,
1420    ) -> Result<()> {
1421        // Delete then insert
1422        self.delete(start, end)?;
1423        self.insert(start, text)?;
1424        Ok(())
1425    }
1426
1427    fn find_matches(
1428        &mut self,
1429        pattern: &str,
1430        search_range: Option<(DocumentPosition, DocumentPosition)>,
1431    ) -> Result<Vec<usize>> {
1432        let (start_offset, end_offset) = if let Some((start, end)) = search_range {
1433            (
1434                self.position_to_offset(start)?,
1435                self.position_to_offset(end)?,
1436            )
1437        } else {
1438            (0, self.buffer.len())
1439        };
1440
1441        // Get text in range
1442        let bytes = self
1443            .buffer
1444            .get_text_range_mut(start_offset, end_offset - start_offset)?;
1445        let text = String::from_utf8_lossy(&bytes);
1446
1447        // Find all matches (simple substring search for now)
1448        let mut matches = Vec::new();
1449        let mut search_offset = 0;
1450        while let Some(pos) = text[search_offset..].find(pattern) {
1451            matches.push(start_offset + search_offset + pos);
1452            search_offset += pos + pattern.len();
1453        }
1454
1455        Ok(matches)
1456    }
1457}
1458
1459/// Cached semantic tokens for a buffer.
1460#[derive(Clone, Debug)]
1461pub struct SemanticTokenStore {
1462    /// Buffer version the tokens correspond to.
1463    pub version: u64,
1464    /// Server-provided result identifier (if any).
1465    pub result_id: Option<String>,
1466    /// Raw semantic token data (u32 array, 5 integers per token).
1467    pub data: Vec<u32>,
1468    /// All semantic token spans resolved to byte ranges.
1469    pub tokens: Vec<SemanticTokenSpan>,
1470}
1471
1472/// A semantic token span resolved to buffer byte offsets.
1473#[derive(Clone, Debug)]
1474pub struct SemanticTokenSpan {
1475    pub range: Range<usize>,
1476    pub token_type: String,
1477    pub modifiers: Vec<String>,
1478}
1479
1480#[cfg(test)]
1481mod tests {
1482    use crate::model::filesystem::StdFileSystem;
1483    use std::sync::Arc;
1484
1485    fn test_fs() -> Arc<dyn crate::model::filesystem::FileSystem + Send + Sync> {
1486        Arc::new(StdFileSystem)
1487    }
1488    use super::*;
1489    use crate::model::event::CursorId;
1490
1491    #[test]
1492    fn test_state_new() {
1493        let state = EditorState::new(
1494            80,
1495            24,
1496            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1497            test_fs(),
1498        );
1499        assert!(state.buffer.is_empty());
1500    }
1501
1502    #[test]
1503    fn test_apply_insert() {
1504        let mut state = EditorState::new(
1505            80,
1506            24,
1507            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1508            test_fs(),
1509        );
1510        let mut cursors = Cursors::new();
1511        let cursor_id = cursors.primary_id();
1512
1513        state.apply(
1514            &mut cursors,
1515            &Event::Insert {
1516                position: 0,
1517                text: "hello".to_string(),
1518                cursor_id,
1519            },
1520        );
1521
1522        assert_eq!(state.buffer.to_string().unwrap(), "hello");
1523        assert_eq!(cursors.primary().position, 5);
1524        assert!(state.buffer.is_modified());
1525    }
1526
1527    #[test]
1528    fn test_apply_delete() {
1529        let mut state = EditorState::new(
1530            80,
1531            24,
1532            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1533            test_fs(),
1534        );
1535        let mut cursors = Cursors::new();
1536        let cursor_id = cursors.primary_id();
1537
1538        // Insert then delete
1539        state.apply(
1540            &mut cursors,
1541            &Event::Insert {
1542                position: 0,
1543                text: "hello world".to_string(),
1544                cursor_id,
1545            },
1546        );
1547
1548        state.apply(
1549            &mut cursors,
1550            &Event::Delete {
1551                range: 5..11,
1552                deleted_text: " world".to_string(),
1553                cursor_id,
1554            },
1555        );
1556
1557        assert_eq!(state.buffer.to_string().unwrap(), "hello");
1558        assert_eq!(cursors.primary().position, 5);
1559    }
1560
1561    #[test]
1562    fn test_apply_move_cursor() {
1563        let mut state = EditorState::new(
1564            80,
1565            24,
1566            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1567            test_fs(),
1568        );
1569        let mut cursors = Cursors::new();
1570        let cursor_id = cursors.primary_id();
1571
1572        state.apply(
1573            &mut cursors,
1574            &Event::Insert {
1575                position: 0,
1576                text: "hello".to_string(),
1577                cursor_id,
1578            },
1579        );
1580
1581        state.apply(
1582            &mut cursors,
1583            &Event::MoveCursor {
1584                cursor_id,
1585                old_position: 5,
1586                new_position: 2,
1587                old_anchor: None,
1588                new_anchor: None,
1589                old_sticky_column: 0,
1590                new_sticky_column: 0,
1591            },
1592        );
1593
1594        assert_eq!(cursors.primary().position, 2);
1595    }
1596
1597    #[test]
1598    fn test_apply_add_cursor() {
1599        let mut state = EditorState::new(
1600            80,
1601            24,
1602            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1603            test_fs(),
1604        );
1605        let mut cursors = Cursors::new();
1606        let cursor_id = CursorId(1);
1607
1608        state.apply(
1609            &mut cursors,
1610            &Event::AddCursor {
1611                cursor_id,
1612                position: 5,
1613                anchor: None,
1614            },
1615        );
1616
1617        assert_eq!(cursors.count(), 2);
1618    }
1619
1620    #[test]
1621    fn test_apply_many() {
1622        let mut state = EditorState::new(
1623            80,
1624            24,
1625            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1626            test_fs(),
1627        );
1628        let mut cursors = Cursors::new();
1629        let cursor_id = cursors.primary_id();
1630
1631        let events = vec![
1632            Event::Insert {
1633                position: 0,
1634                text: "hello ".to_string(),
1635                cursor_id,
1636            },
1637            Event::Insert {
1638                position: 6,
1639                text: "world".to_string(),
1640                cursor_id,
1641            },
1642        ];
1643
1644        state.apply_many(&mut cursors, &events);
1645
1646        assert_eq!(state.buffer.to_string().unwrap(), "hello world");
1647    }
1648
1649    #[test]
1650    fn test_cursor_adjustment_after_insert() {
1651        let mut state = EditorState::new(
1652            80,
1653            24,
1654            crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1655            test_fs(),
1656        );
1657        let mut cursors = Cursors::new();
1658        let cursor_id = cursors.primary_id();
1659
1660        // Add a second cursor at position 5
1661        state.apply(
1662            &mut cursors,
1663            &Event::AddCursor {
1664                cursor_id: CursorId(1),
1665                position: 5,
1666                anchor: None,
1667            },
1668        );
1669
1670        // Insert at position 0 - should push second cursor forward
1671        state.apply(
1672            &mut cursors,
1673            &Event::Insert {
1674                position: 0,
1675                text: "abc".to_string(),
1676                cursor_id,
1677            },
1678        );
1679
1680        // Second cursor should be at position 5 + 3 = 8
1681        if let Some(cursor) = cursors.get(CursorId(1)) {
1682            assert_eq!(cursor.position, 8);
1683        }
1684    }
1685
1686    // DocumentModel trait tests
1687    mod document_model_tests {
1688        use super::*;
1689        use crate::model::document_model::{DocumentModel, DocumentPosition};
1690
1691        #[test]
1692        fn test_capabilities_small_file() {
1693            let mut state = EditorState::new(
1694                80,
1695                24,
1696                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1697                test_fs(),
1698            );
1699            state.buffer = Buffer::from_str_test("line1\nline2\nline3");
1700
1701            let caps = state.capabilities();
1702            assert!(caps.has_line_index, "Small file should have line index");
1703            assert_eq!(caps.byte_length, "line1\nline2\nline3".len());
1704            assert_eq!(caps.approximate_line_count, 3, "Should have 3 lines");
1705        }
1706
1707        #[test]
1708        fn test_position_conversions() {
1709            let mut state = EditorState::new(
1710                80,
1711                24,
1712                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1713                test_fs(),
1714            );
1715            state.buffer = Buffer::from_str_test("hello\nworld\ntest");
1716
1717            // Test ByteOffset -> offset
1718            let pos1 = DocumentPosition::ByteOffset(6);
1719            let offset1 = state.position_to_offset(pos1).unwrap();
1720            assert_eq!(offset1, 6);
1721
1722            // Test LineColumn -> offset
1723            let pos2 = DocumentPosition::LineColumn { line: 1, column: 0 };
1724            let offset2 = state.position_to_offset(pos2).unwrap();
1725            assert_eq!(offset2, 6, "Line 1, column 0 should be at byte 6");
1726
1727            // Test offset -> position (should return LineColumn for small files)
1728            let converted = state.offset_to_position(6);
1729            match converted {
1730                DocumentPosition::LineColumn { line, column } => {
1731                    assert_eq!(line, 1);
1732                    assert_eq!(column, 0);
1733                }
1734                _ => panic!("Expected LineColumn for small file"),
1735            }
1736        }
1737
1738        #[test]
1739        fn test_get_viewport_content() {
1740            let mut state = EditorState::new(
1741                80,
1742                24,
1743                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1744                test_fs(),
1745            );
1746            state.buffer = Buffer::from_str_test("line1\nline2\nline3\nline4\nline5");
1747
1748            let content = state
1749                .get_viewport_content(DocumentPosition::ByteOffset(0), 3)
1750                .unwrap();
1751
1752            assert_eq!(content.lines.len(), 3);
1753            assert_eq!(content.lines[0].content, "line1");
1754            assert_eq!(content.lines[1].content, "line2");
1755            assert_eq!(content.lines[2].content, "line3");
1756            assert!(content.has_more);
1757        }
1758
1759        #[test]
1760        fn test_get_range() {
1761            let mut state = EditorState::new(
1762                80,
1763                24,
1764                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1765                test_fs(),
1766            );
1767            state.buffer = Buffer::from_str_test("hello world");
1768
1769            let text = state
1770                .get_range(
1771                    DocumentPosition::ByteOffset(0),
1772                    DocumentPosition::ByteOffset(5),
1773                )
1774                .unwrap();
1775            assert_eq!(text, "hello");
1776
1777            let text2 = state
1778                .get_range(
1779                    DocumentPosition::ByteOffset(6),
1780                    DocumentPosition::ByteOffset(11),
1781                )
1782                .unwrap();
1783            assert_eq!(text2, "world");
1784        }
1785
1786        #[test]
1787        fn test_get_line_content() {
1788            let mut state = EditorState::new(
1789                80,
1790                24,
1791                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1792                test_fs(),
1793            );
1794            state.buffer = Buffer::from_str_test("line1\nline2\nline3");
1795
1796            let line0 = state.get_line_content(0).unwrap();
1797            assert_eq!(line0, "line1");
1798
1799            let line1 = state.get_line_content(1).unwrap();
1800            assert_eq!(line1, "line2");
1801
1802            let line2 = state.get_line_content(2).unwrap();
1803            assert_eq!(line2, "line3");
1804        }
1805
1806        #[test]
1807        fn test_insert_delete() {
1808            let mut state = EditorState::new(
1809                80,
1810                24,
1811                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1812                test_fs(),
1813            );
1814            state.buffer = Buffer::from_str_test("hello world");
1815
1816            // Insert text
1817            let bytes_inserted = state
1818                .insert(DocumentPosition::ByteOffset(6), "beautiful ")
1819                .unwrap();
1820            assert_eq!(bytes_inserted, 10);
1821            assert_eq!(state.buffer.to_string().unwrap(), "hello beautiful world");
1822
1823            // Delete text
1824            state
1825                .delete(
1826                    DocumentPosition::ByteOffset(6),
1827                    DocumentPosition::ByteOffset(16),
1828                )
1829                .unwrap();
1830            assert_eq!(state.buffer.to_string().unwrap(), "hello world");
1831        }
1832
1833        #[test]
1834        fn test_replace() {
1835            let mut state = EditorState::new(
1836                80,
1837                24,
1838                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1839                test_fs(),
1840            );
1841            state.buffer = Buffer::from_str_test("hello world");
1842
1843            state
1844                .replace(
1845                    DocumentPosition::ByteOffset(0),
1846                    DocumentPosition::ByteOffset(5),
1847                    "hi",
1848                )
1849                .unwrap();
1850            assert_eq!(state.buffer.to_string().unwrap(), "hi world");
1851        }
1852
1853        #[test]
1854        fn test_find_matches() {
1855            let mut state = EditorState::new(
1856                80,
1857                24,
1858                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1859                test_fs(),
1860            );
1861            state.buffer = Buffer::from_str_test("hello world hello");
1862
1863            let matches = state.find_matches("hello", None).unwrap();
1864            assert_eq!(matches.len(), 2);
1865            assert_eq!(matches[0], 0);
1866            assert_eq!(matches[1], 12);
1867        }
1868
1869        #[test]
1870        fn test_prepare_for_render() {
1871            let mut state = EditorState::new(
1872                80,
1873                24,
1874                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1875                test_fs(),
1876            );
1877            state.buffer = Buffer::from_str_test("line1\nline2\nline3\nline4\nline5");
1878
1879            // Should not panic - pass top_byte=0 and height=24 (typical viewport params)
1880            state.prepare_for_render(0, 24).unwrap();
1881        }
1882
1883        #[test]
1884        fn test_helper_get_text_range() {
1885            let mut state = EditorState::new(
1886                80,
1887                24,
1888                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1889                test_fs(),
1890            );
1891            state.buffer = Buffer::from_str_test("hello world");
1892
1893            // Test normal range
1894            let text = state.get_text_range(0, 5);
1895            assert_eq!(text, "hello");
1896
1897            // Test middle range
1898            let text2 = state.get_text_range(6, 11);
1899            assert_eq!(text2, "world");
1900        }
1901
1902        #[test]
1903        fn test_helper_get_line_at_offset() {
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");
1911
1912            // Get first line (offset 0)
1913            let (offset, content) = state.get_line_at_offset(0).unwrap();
1914            assert_eq!(offset, 0);
1915            assert_eq!(content, "line1");
1916
1917            // Get second line (offset in middle of line)
1918            let (offset2, content2) = state.get_line_at_offset(8).unwrap();
1919            assert_eq!(offset2, 6); // Line starts at byte 6
1920            assert_eq!(content2, "line2");
1921
1922            // Get last line
1923            let (offset3, content3) = state.get_line_at_offset(12).unwrap();
1924            assert_eq!(offset3, 12);
1925            assert_eq!(content3, "line3");
1926        }
1927
1928        #[test]
1929        fn test_helper_get_text_to_end_of_line() {
1930            let mut state = EditorState::new(
1931                80,
1932                24,
1933                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1934                test_fs(),
1935            );
1936            state.buffer = Buffer::from_str_test("hello world\nline2");
1937
1938            // From beginning of line
1939            let text = state.get_text_to_end_of_line(0).unwrap();
1940            assert_eq!(text, "hello world");
1941
1942            // From middle of line
1943            let text2 = state.get_text_to_end_of_line(6).unwrap();
1944            assert_eq!(text2, "world");
1945
1946            // From end of line
1947            let text3 = state.get_text_to_end_of_line(11).unwrap();
1948            assert_eq!(text3, "");
1949
1950            // From second line
1951            let text4 = state.get_text_to_end_of_line(12).unwrap();
1952            assert_eq!(text4, "line2");
1953        }
1954    }
1955
1956    // Virtual text integration tests
1957    mod virtual_text_integration_tests {
1958        use super::*;
1959        use crate::view::virtual_text::VirtualTextPosition;
1960        use ratatui::style::Style;
1961
1962        #[test]
1963        fn test_virtual_text_add_and_query() {
1964            let mut state = EditorState::new(
1965                80,
1966                24,
1967                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
1968                test_fs(),
1969            );
1970            state.buffer = Buffer::from_str_test("hello world");
1971
1972            // Initialize marker list for buffer
1973            if !state.buffer.is_empty() {
1974                state.marker_list.adjust_for_insert(0, state.buffer.len());
1975            }
1976
1977            // Add virtual text at position 5 (after 'hello')
1978            let vtext_id = state.virtual_texts.add(
1979                &mut state.marker_list,
1980                5,
1981                ": string".to_string(),
1982                Style::default(),
1983                VirtualTextPosition::AfterChar,
1984                0,
1985            );
1986
1987            // Query should return the virtual text
1988            let results = state.virtual_texts.query_range(&state.marker_list, 0, 11);
1989            assert_eq!(results.len(), 1);
1990            assert_eq!(results[0].0, 5); // Position
1991            assert_eq!(results[0].1.text, ": string");
1992
1993            // Build lookup should work
1994            let lookup = state.virtual_texts.build_lookup(&state.marker_list, 0, 11);
1995            assert!(lookup.contains_key(&5));
1996            assert_eq!(lookup[&5].len(), 1);
1997            assert_eq!(lookup[&5][0].text, ": string");
1998
1999            // Clean up
2000            state.virtual_texts.remove(&mut state.marker_list, vtext_id);
2001            assert!(state.virtual_texts.is_empty());
2002        }
2003
2004        #[test]
2005        fn test_virtual_text_position_tracking_on_insert() {
2006            let mut state = EditorState::new(
2007                80,
2008                24,
2009                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2010                test_fs(),
2011            );
2012            state.buffer = Buffer::from_str_test("hello world");
2013
2014            // Initialize marker list for buffer
2015            if !state.buffer.is_empty() {
2016                state.marker_list.adjust_for_insert(0, state.buffer.len());
2017            }
2018
2019            // Add virtual text at position 6 (the 'w' in 'world')
2020            let _vtext_id = state.virtual_texts.add(
2021                &mut state.marker_list,
2022                6,
2023                "/*param*/".to_string(),
2024                Style::default(),
2025                VirtualTextPosition::BeforeChar,
2026                0,
2027            );
2028
2029            // Insert "beautiful " at position 6 using Event
2030            let mut cursors = Cursors::new();
2031            let cursor_id = cursors.primary_id();
2032            state.apply(
2033                &mut cursors,
2034                &Event::Insert {
2035                    position: 6,
2036                    text: "beautiful ".to_string(),
2037                    cursor_id,
2038                },
2039            );
2040
2041            // Virtual text should now be at position 16 (6 + 10)
2042            let results = state.virtual_texts.query_range(&state.marker_list, 0, 30);
2043            assert_eq!(results.len(), 1);
2044            assert_eq!(results[0].0, 16); // Position should have moved
2045            assert_eq!(results[0].1.text, "/*param*/");
2046        }
2047
2048        #[test]
2049        fn test_virtual_text_position_tracking_on_delete() {
2050            let mut state = EditorState::new(
2051                80,
2052                24,
2053                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2054                test_fs(),
2055            );
2056            state.buffer = Buffer::from_str_test("hello beautiful world");
2057
2058            // Initialize marker list for buffer
2059            if !state.buffer.is_empty() {
2060                state.marker_list.adjust_for_insert(0, state.buffer.len());
2061            }
2062
2063            // Add virtual text at position 16 (the 'w' in 'world')
2064            let _vtext_id = state.virtual_texts.add(
2065                &mut state.marker_list,
2066                16,
2067                ": string".to_string(),
2068                Style::default(),
2069                VirtualTextPosition::AfterChar,
2070                0,
2071            );
2072
2073            // Delete "beautiful " (positions 6-16) using Event
2074            let mut cursors = Cursors::new();
2075            let cursor_id = cursors.primary_id();
2076            state.apply(
2077                &mut cursors,
2078                &Event::Delete {
2079                    range: 6..16,
2080                    deleted_text: "beautiful ".to_string(),
2081                    cursor_id,
2082                },
2083            );
2084
2085            // Virtual text should now be at position 6
2086            let results = state.virtual_texts.query_range(&state.marker_list, 0, 20);
2087            assert_eq!(results.len(), 1);
2088            assert_eq!(results[0].0, 6); // Position should have moved back
2089            assert_eq!(results[0].1.text, ": string");
2090        }
2091
2092        #[test]
2093        fn test_multiple_virtual_texts_with_priorities() {
2094            let mut state = EditorState::new(
2095                80,
2096                24,
2097                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2098                test_fs(),
2099            );
2100            state.buffer = Buffer::from_str_test("let x = 5");
2101
2102            // Initialize marker list for buffer
2103            if !state.buffer.is_empty() {
2104                state.marker_list.adjust_for_insert(0, state.buffer.len());
2105            }
2106
2107            // Add type hint after 'x' (position 5)
2108            state.virtual_texts.add(
2109                &mut state.marker_list,
2110                5,
2111                ": i32".to_string(),
2112                Style::default(),
2113                VirtualTextPosition::AfterChar,
2114                0, // Lower priority - renders first
2115            );
2116
2117            // Add another hint at same position with higher priority
2118            state.virtual_texts.add(
2119                &mut state.marker_list,
2120                5,
2121                " /* inferred */".to_string(),
2122                Style::default(),
2123                VirtualTextPosition::AfterChar,
2124                10, // Higher priority - renders second
2125            );
2126
2127            // Build lookup - should have both, sorted by priority (lower first)
2128            let lookup = state.virtual_texts.build_lookup(&state.marker_list, 0, 10);
2129            assert!(lookup.contains_key(&5));
2130            let vtexts = &lookup[&5];
2131            assert_eq!(vtexts.len(), 2);
2132            // Lower priority first (like layer ordering)
2133            assert_eq!(vtexts[0].text, ": i32");
2134            assert_eq!(vtexts[1].text, " /* inferred */");
2135        }
2136
2137        #[test]
2138        fn test_virtual_text_clear() {
2139            let mut state = EditorState::new(
2140                80,
2141                24,
2142                crate::config::LARGE_FILE_THRESHOLD_BYTES as usize,
2143                test_fs(),
2144            );
2145            state.buffer = Buffer::from_str_test("test");
2146
2147            // Initialize marker list for buffer
2148            if !state.buffer.is_empty() {
2149                state.marker_list.adjust_for_insert(0, state.buffer.len());
2150            }
2151
2152            // Add multiple virtual texts
2153            state.virtual_texts.add(
2154                &mut state.marker_list,
2155                0,
2156                "hint1".to_string(),
2157                Style::default(),
2158                VirtualTextPosition::BeforeChar,
2159                0,
2160            );
2161            state.virtual_texts.add(
2162                &mut state.marker_list,
2163                2,
2164                "hint2".to_string(),
2165                Style::default(),
2166                VirtualTextPosition::AfterChar,
2167                0,
2168            );
2169
2170            assert_eq!(state.virtual_texts.len(), 2);
2171
2172            // Clear all
2173            state.virtual_texts.clear(&mut state.marker_list);
2174            assert!(state.virtual_texts.is_empty());
2175
2176            // Query should return nothing
2177            let results = state.virtual_texts.query_range(&state.marker_list, 0, 10);
2178            assert!(results.is_empty());
2179        }
2180    }
2181}