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    /// Per-logical-line visual-row-count cache (pipeline-output).
231    /// Populated by both the renderer (as a side effect of rendering a
232    /// visible frame) and the scroll-math miss handler.  Entries are
233    /// keyed on every pipeline input; mutations to any input produce a
234    /// different key so stale entries are never returned — see
235    /// `docs/internal/line-wrap-cache-plan.md`.
236    pub line_wrap_cache: crate::view::line_wrap_cache::LineWrapCache,
237
238    /// Whole-buffer prefix-sum index over per-line visual row counts.
239    /// Sits one tier above `line_wrap_cache`: answers
240    /// "what visual row contains byte B?" / "what byte sits at row R?"
241    /// in O(log N_lines) for scrollbar drag, scrollbar render, and
242    /// `ensure_visible` wrapped scrolling.  Built lazily from
243    /// `line_wrap_cache`; same invalidation source (pipeline-input
244    /// version + geometry).  See
245    /// `crate::view::visual_row_index` for invariants.
246    pub visual_row_index: crate::view::visual_row_index::VisualRowIndex,
247}
248
249impl EditorState {
250    /// Create a new editor state with an empty buffer
251    ///
252    /// Note: width/height parameters are kept for backward compatibility but
253    /// are no longer used - viewport is now owned by SplitViewState.
254    /// Apply a detected language to this state. This is the single mutation point
255    /// for changing the language of a buffer after creation.
256    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    /// Create a new state with a buffer and default (plain text) language.
266    /// All other fields are initialized to their defaults.
267    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    /// Create a new editor state with an empty buffer associated with a file path.
315    /// Used for files that don't exist yet — the path is set so saving will create the file.
316    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    /// Set the syntax highlighting language based on a virtual buffer name.
325    /// Handles names like `*OLD:test.ts*` or `*OURS*.c` by stripping markers
326    /// and detecting language from the cleaned filename.
327    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    /// Create an editor state from a file
339    ///
340    /// Note: width/height parameters are kept for backward compatibility but
341    /// are no longer used - viewport is now owned by SplitViewState.
342    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    /// Create an editor state from a file with language configuration.
362    ///
363    /// This version uses the provided languages configuration for syntax detection,
364    /// allowing user-configured filename patterns to be respected for highlighting.
365    ///
366    /// Note: width/height parameters are kept for backward compatibility but
367    /// are no longer used - viewport is now owned by SplitViewState.
368    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    /// Create an editor state from a buffer and a pre-built `DetectedLanguage`.
387    ///
388    /// This is useful when you have already loaded a buffer with a specific encoding
389    /// and want to create an EditorState from it.
390    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    /// Handle an Insert event - adjusts markers, buffer, highlighter, cursors, and line numbers
397    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        // CRITICAL: Adjust markers BEFORE modifying buffer
407        self.marker_list.adjust_for_insert(position, text.len());
408        self.margins.adjust_for_insert(position, text.len());
409
410        // Insert text into buffer
411        self.buffer.insert(position, text);
412
413        // Notify highlighter of the insert (adjusts checkpoint marker positions)
414        // and invalidate span cache for the edited range.
415        self.highlighter.notify_insert(position, text.len());
416        self.highlighter
417            .invalidate_range(position..position + text.len());
418
419        // Note: reference_highlight_overlay uses markers that auto-adjust,
420        // so no manual invalidation needed
421
422        // Adjust all cursors after the edit
423        cursors.adjust_for_edit(position, 0, text.len());
424
425        // Move the cursor that made the edit to the end of the insertion
426        if let Some(cursor) = cursors.get_mut(cursor_id) {
427            cursor.position = position + text.len();
428            cursor.clear_selection();
429        }
430
431        // Update primary cursor line number if this was the primary cursor
432        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    /// Handle a Delete event - adjusts markers, buffer, highlighter, cursors, and line numbers
447    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        // Count newlines deleted BEFORE the primary cursor's original position.
457        // For backspace: cursor was at range.end, so all deleted newlines are before it.
458        // For forward delete: cursor was at range.start, so no deleted newlines are before it.
459        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        // Drop virtual texts whose anchors are being erased. This is what
468        // makes inlay hints disappear immediately when the range containing
469        // them is deleted; without this the marker would just clamp to
470        // range.start and the hint would linger at the wrong position until
471        // the next LSP refresh.
472        self.virtual_texts
473            .remove_in_range(&mut self.marker_list, range.start, range.end);
474
475        // CRITICAL: Adjust markers BEFORE modifying buffer
476        self.marker_list.adjust_for_delete(range.start, len);
477        self.margins.adjust_for_delete(range.start, len);
478
479        // Delete from buffer
480        self.buffer.delete(range.clone());
481
482        // Notify highlighter of the delete (adjusts checkpoint marker positions)
483        // and invalidate span cache for the edited range.
484        self.highlighter.notify_delete(range.start, len);
485        self.highlighter.invalidate_range(range.clone());
486
487        // Note: reference_highlight_overlay uses markers that auto-adjust,
488        // so no manual invalidation needed
489
490        // Adjust all cursors after the edit
491        cursors.adjust_for_edit(range.start, len, 0);
492
493        // Move the cursor that made the edit to the start of deletion
494        if let Some(cursor) = cursors.get_mut(cursor_id) {
495            cursor.position = range.start;
496            cursor.clear_selection();
497        }
498
499        // Update primary cursor line number if this was the primary cursor
500        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    /// Apply an event to the state - THE ONLY WAY TO MODIFY STATE
517    /// This is the heart of the event-driven architecture
518    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                // Update primary cursor line number if this is the primary cursor
546                // Try to get exact line number from buffer, or estimate for large files
547                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                                // Large file without line metadata - estimate line number
553                                // Use default estimated_line_length of 80 bytes
554                                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                // Insert cursor with the specific ID from the event
573                // This is important for undo/redo to work correctly
574                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            // View events (Scroll, SetViewport, Recenter) are now handled at Editor level
584            // via SplitViewState. They should not reach EditorState.apply().
585            Event::Scroll { .. } | Event::SetViewport { .. } | Event::Recenter => {
586                // These events are intercepted in Editor::apply_event_to_active_buffer
587                // and routed to SplitViewState. If we get here, something is wrong.
588                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                // Set the anchor (selection start) for a specific cursor
596                // Also disable deselect_on_move so movement preserves the selection (Emacs mark mode)
597                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                // Clear the anchor and reset deselect_on_move to cancel mark mode
605                // Also clear block selection if active
606                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                // Convert event overlay face to overlay face
634                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            // Split events are handled at the Editor level, not at EditorState level
754            // These are no-ops here as they affect the split layout, not buffer state
755            Event::SplitPane { .. }
756            | Event::CloseSplit { .. }
757            | Event::SetActiveSplit { .. }
758            | Event::AdjustSplitRatio { .. }
759            | Event::NextSplit
760            | Event::PrevSplit => {
761                // No-op: split events are handled by Editor, not EditorState
762            }
763
764            Event::Batch { events, .. } => {
765                // Apply all events in the batch sequentially
766                // This ensures multi-cursor operations are applied atomically
767                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                // Restore the target buffer state (piece tree + buffers) for this event.
780                // - For undo: snapshots are swapped, so new_snapshot is the original state
781                // - For redo: new_snapshot is the state after edits
782                // Restoring buffers alongside the tree is critical because
783                // consolidate_after_save() can replace buffers between snapshot and restore.
784                if let Some(snapshot) = new_snapshot {
785                    self.buffer.restore_buffer_state(snapshot);
786                }
787
788                // Replay marker adjustments from the edit list.
789                // For redo: same adjustments as the forward path.
790                // For undo: inverse() has swapped del/ins, so adjustments are reversed.
791                // Edits are in descending position order — process as-is so later
792                // positions are adjusted first (no cascading shift errors).
793                //
794                // For replacements (del > 0 AND ins > 0 at same position), we only
795                // adjust for the net delta to avoid the marker-at-boundary problem
796                // where sequential delete+insert pushes markers incorrectly.
797                for &(pos, del_len, ins_len) in edits {
798                    if del_len > 0 && ins_len > 0 {
799                        // Replacement: adjust by net delta only
800                        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                        // If equal: net delta 0, no adjustment needed
810                    } 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                // Restore displaced markers to their original positions.
820                // This fixes markers that were inside a deleted range and collapsed
821                // to the deletion boundary — they're now moved back to their exact
822                // original positions after the text has been restored by undo.
823                if !displaced_markers.is_empty() {
824                    self.restore_displaced_markers(displaced_markers);
825                }
826
827                // Clear ephemeral decorations — their source systems will re-push
828                // correct positions after the edit notification.
829                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                // Update cursor positions
841                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                // Invalidate highlight cache for entire buffer
849                self.highlighter.invalidate_all();
850
851                // Update primary cursor line number
852                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    /// Capture positions of markers strictly inside a deleted range.
863    /// Call this BEFORE applying the delete. Returns encoded displaced markers.
864    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    /// Capture displaced markers for multiple delete ranges (BulkEdit).
895    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    /// Restore displaced markers to their exact original positions.
909    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    /// Apply multiple events in sequence
924    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    /// Called when this buffer loses focus (e.g., switching to another buffer,
931    /// opening a prompt, focusing file explorer, etc.)
932    /// Dismisses transient popups like Hover and Signature Help.
933    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
940/// Convert event overlay face to the actual overlay face
941fn 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            // Build fallback style from RGB values or named colors
966            let mut style = Style::default();
967
968            // Extract foreground color (RGB, named color, or default white)
969            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            // Extract background color (RGB, named color, or fallback)
980            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            // Apply modifiers
991            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            // Extract theme keys (exclude recognized named colors, already resolved above)
1009            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 theme keys are provided, use ThemedStyle for runtime resolution
1023            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
1036/// Convert popup data to the actual popup object
1037pub(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    // Map the explicit kind hint to PopupKind for input handling
1066    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    // Kind-implied resolver default: a popup whose kind is
1073    // `Completion` always confirms by inserting the selected
1074    // completion, regardless of who built it. Other kinds need an
1075    // explicit resolver (LSP confirm, plugin action, LSP status, code
1076    // action) because the same `List` kind is used for all four, so we
1077    // can't infer which feature owns the popup from its kind alone.
1078    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
1102/// Convert margin position data to the actual margin position
1103fn convert_margin_position(position: &MarginPositionData) -> MarginPosition {
1104    match position {
1105        MarginPositionData::Left => MarginPosition::Left,
1106        MarginPositionData::Right => MarginPosition::Right,
1107    }
1108}
1109
1110/// Convert margin content data to the actual margin content
1111fn 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    /// Prepare viewport for rendering (called before frame render)
1127    ///
1128    /// This pre-loads all data that will be needed for rendering the current viewport,
1129    /// ensuring that subsequent read-only access during rendering will succeed.
1130    ///
1131    /// Takes viewport parameters since viewport is now owned by SplitViewState.
1132    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    /// Resolve all plugin-injected virtual-line anchor byte positions
1138    /// for this buffer.  Sorted ascending.
1139    ///
1140    /// Used by `Viewport::scroll_down` / `scroll_up` /
1141    /// `find_max_visual_scroll_position` so the scroll math counts the
1142    /// rows the renderer actually draws (e.g. markdown_compose's
1143    /// `┌─┬─┐` table borders) when computing `max_scroll_row`.  Without
1144    /// this, mouse wheel and PageDown clamp to a row count that
1145    /// ignores virtual lines and stop short of the buffer's real tail.
1146    ///
1147    /// Empty when no plugin has added virtual lines.
1148    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    /// Resolve all plugin-injected soft-break `(byte_position, indent)`
1163    /// pairs for this buffer.
1164    ///
1165    /// Returns a sorted slice suitable for passing to `Viewport::scroll_up` /
1166    /// `scroll_down`, which use it to keep their visual-row counting in
1167    /// lock-step with the renderer (which applies these same breaks via
1168    /// `apply_soft_breaks`).  The `indent` field is the column count of
1169    /// hanging-indent spaces the plugin asked the renderer to inject
1170    /// after the break — the wrap counter needs it to compute the
1171    /// continuation segment's effective width correctly.
1172    ///
1173    /// Empty when no plugin is wrapping the buffer.
1174    pub fn collect_soft_break_positions(&self) -> Vec<(usize, u16)> {
1175        if self.soft_breaks.is_empty() {
1176            return Vec::new();
1177        }
1178        // query_viewport already returns pairs sorted by ascending position.
1179        self.soft_breaks
1180            .query_viewport(0, self.buffer.len() + 1, &self.marker_list)
1181    }
1182
1183    // ========== DocumentModel Helper Methods ==========
1184    // These methods provide convenient access to DocumentModel functionality
1185    // while maintaining backward compatibility with existing code.
1186
1187    /// Get text in a range, driving lazy loading transparently
1188    ///
1189    /// This is a convenience wrapper around DocumentModel::get_range that:
1190    /// - Drives lazy loading automatically (never fails due to unloaded data)
1191    /// - Uses byte offsets directly
1192    /// - Returns String (not Result) - errors are logged internally
1193    /// - Returns empty string for invalid ranges
1194    ///
1195    /// This is the preferred API for getting text ranges. The caller never needs
1196    /// to worry about lazy loading or buffer preparation.
1197    ///
1198    /// # Example
1199    /// ```ignore
1200    /// let text = state.get_text_range(0, 100);
1201    /// ```
1202    pub fn get_text_range(&mut self, start: usize, end: usize) -> String {
1203        // TextBuffer::get_text_range_mut() handles lazy loading automatically
1204        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    /// Get the content of a line by its byte offset
1217    ///
1218    /// Returns the line containing the given offset, along with its start position.
1219    /// This uses DocumentModel's viewport functionality for consistent behavior.
1220    ///
1221    /// # Returns
1222    /// `Some((line_start_offset, line_content))` if successful, `None` if offset is invalid
1223    pub fn get_line_at_offset(&mut self, offset: usize) -> Option<(usize, String)> {
1224        use crate::model::document_model::DocumentModel;
1225
1226        // Find the start of the line containing this offset
1227        // Scan backwards to find the previous newline or start of buffer
1228        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        // Get a single line viewport starting at the line start
1241        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    /// Get text from current cursor position to end of line
1255    ///
1256    /// This is a common pattern in editing operations. Uses DocumentModel
1257    /// for consistent behavior across file sizes.
1258    pub fn get_text_to_end_of_line(&mut self, cursor_pos: usize) -> Result<String> {
1259        use crate::model::document_model::DocumentModel;
1260
1261        // Get the line containing cursor
1262        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                // Use get() to safely handle potential non-char-boundary offsets
1274                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    /// Replace cached semantic tokens with a new store.
1284    pub fn set_semantic_tokens(&mut self, store: SemanticTokenStore) {
1285        self.semantic_tokens = Some(store);
1286    }
1287
1288    /// Clear cached semantic tokens (e.g., when tokens are invalidated).
1289    pub fn clear_semantic_tokens(&mut self) {
1290        self.semantic_tokens = None;
1291    }
1292
1293    /// Get the server-provided semantic token result_id if available.
1294    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
1301/// Implement DocumentModel trait for EditorState
1302///
1303/// This provides a clean abstraction layer between rendering/editing operations
1304/// and the underlying text buffer implementation.
1305impl 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, // TODO: add large file detection
1311            byte_length: self.buffer.len(),
1312            approximate_line_count: line_count.unwrap_or_else(|| {
1313                // Estimate assuming ~80 bytes per line
1314                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        // Convert to byte offset
1325        let start_offset = self.position_to_offset(start_pos)?;
1326
1327        // Use new efficient line iteration that tracks line numbers during iteration
1328        // by accumulating line_feed_cnt from pieces (single source of truth)
1329        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                // Use piece tree's position conversion
1356                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                // Line index exists but metadata unavailable - fall back to byte offset
1371                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        // Convert line number to byte offset
1403        let line_start_offset = self.buffer.line_start_offset(line_number)?;
1404
1405        // Get line content using iterator
1406        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        // Delete then insert
1455        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        // Get text in range
1475        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        // Find all matches (simple substring search for now)
1481        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/// Cached semantic tokens for a buffer.
1493#[derive(Clone, Debug)]
1494pub struct SemanticTokenStore {
1495    /// Buffer version the tokens correspond to.
1496    pub version: u64,
1497    /// Server-provided result identifier (if any).
1498    pub result_id: Option<String>,
1499    /// Raw semantic token data (u32 array, 5 integers per token).
1500    pub data: Vec<u32>,
1501    /// All semantic token spans resolved to byte ranges.
1502    pub tokens: Vec<SemanticTokenSpan>,
1503}
1504
1505/// A semantic token span resolved to buffer byte offsets.
1506#[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        // Insert then delete
1572        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        // Add a second cursor at position 5
1694        state.apply(
1695            &mut cursors,
1696            &Event::AddCursor {
1697                cursor_id: CursorId(1),
1698                position: 5,
1699                anchor: None,
1700            },
1701        );
1702
1703        // Insert at position 0 - should push second cursor forward
1704        state.apply(
1705            &mut cursors,
1706            &Event::Insert {
1707                position: 0,
1708                text: "abc".to_string(),
1709                cursor_id,
1710            },
1711        );
1712
1713        // Second cursor should be at position 5 + 3 = 8
1714        if let Some(cursor) = cursors.get(CursorId(1)) {
1715            assert_eq!(cursor.position, 8);
1716        }
1717    }
1718
1719    // DocumentModel trait tests
1720    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            // Test ByteOffset -> offset
1751            let pos1 = DocumentPosition::ByteOffset(6);
1752            let offset1 = state.position_to_offset(pos1).unwrap();
1753            assert_eq!(offset1, 6);
1754
1755            // Test LineColumn -> offset
1756            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            // Test offset -> position (should return LineColumn for small files)
1761            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            // Insert text
1850            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            // Delete text
1857            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            // Should not panic - pass top_byte=0 and height=24 (typical viewport params)
1913            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            // Test normal range
1927            let text = state.get_text_range(0, 5);
1928            assert_eq!(text, "hello");
1929
1930            // Test middle range
1931            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            // Get first line (offset 0)
1946            let (offset, content) = state.get_line_at_offset(0).unwrap();
1947            assert_eq!(offset, 0);
1948            assert_eq!(content, "line1");
1949
1950            // Get second line (offset in middle of line)
1951            let (offset2, content2) = state.get_line_at_offset(8).unwrap();
1952            assert_eq!(offset2, 6); // Line starts at byte 6
1953            assert_eq!(content2, "line2");
1954
1955            // Get last line
1956            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            // From beginning of line
1972            let text = state.get_text_to_end_of_line(0).unwrap();
1973            assert_eq!(text, "hello world");
1974
1975            // From middle of line
1976            let text2 = state.get_text_to_end_of_line(6).unwrap();
1977            assert_eq!(text2, "world");
1978
1979            // From end of line
1980            let text3 = state.get_text_to_end_of_line(11).unwrap();
1981            assert_eq!(text3, "");
1982
1983            // From second line
1984            let text4 = state.get_text_to_end_of_line(12).unwrap();
1985            assert_eq!(text4, "line2");
1986        }
1987    }
1988
1989    // Virtual text integration tests
1990    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            // Initialize marker list for buffer
2006            if !state.buffer.is_empty() {
2007                state.marker_list.adjust_for_insert(0, state.buffer.len());
2008            }
2009
2010            // Add virtual text at position 5 (after 'hello')
2011            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            // Query should return the virtual text
2021            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); // Position
2024            assert_eq!(results[0].1.text, ": string");
2025
2026            // Build lookup should work
2027            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            // Clean up
2033            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            // Initialize marker list for buffer
2048            if !state.buffer.is_empty() {
2049                state.marker_list.adjust_for_insert(0, state.buffer.len());
2050            }
2051
2052            // Add virtual text at position 6 (the 'w' in 'world')
2053            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            // Insert "beautiful " at position 6 using Event
2063            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            // Virtual text should now be at position 16 (6 + 10)
2075            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); // Position should have moved
2078            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            // Initialize marker list for buffer
2092            if !state.buffer.is_empty() {
2093                state.marker_list.adjust_for_insert(0, state.buffer.len());
2094            }
2095
2096            // Add virtual text at position 16 (the 'w' in 'world')
2097            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            // Delete "beautiful " (positions 6-16) using Event
2107            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            // Virtual text should now be at position 6
2119            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); // Position should have moved back
2122            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            // Initialize marker list for buffer
2136            if !state.buffer.is_empty() {
2137                state.marker_list.adjust_for_insert(0, state.buffer.len());
2138            }
2139
2140            // Add type hint after 'x' (position 5)
2141            state.virtual_texts.add(
2142                &mut state.marker_list,
2143                5,
2144                ": i32".to_string(),
2145                Style::default(),
2146                VirtualTextPosition::AfterChar,
2147                0, // Lower priority - renders first
2148            );
2149
2150            // Add another hint at same position with higher priority
2151            state.virtual_texts.add(
2152                &mut state.marker_list,
2153                5,
2154                " /* inferred */".to_string(),
2155                Style::default(),
2156                VirtualTextPosition::AfterChar,
2157                10, // Higher priority - renders second
2158            );
2159
2160            // Build lookup - should have both, sorted by priority (lower first)
2161            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            // Lower priority first (like layer ordering)
2166            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            // Initialize marker list for buffer
2181            if !state.buffer.is_empty() {
2182                state.marker_list.adjust_for_insert(0, state.buffer.len());
2183            }
2184
2185            // Add multiple virtual texts
2186            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            // Clear all
2206            state.virtual_texts.clear(&mut state.marker_list);
2207            assert!(state.virtual_texts.is_empty());
2208
2209            // Query should return nothing
2210            let results = state.virtual_texts.query_range(&state.marker_list, 0, 10);
2211            assert!(results.is_empty());
2212        }
2213    }
2214}