Skip to main content

strata_editor/
code_editor.rs

1//! High-performance Code Editor controller with virtualized lines, syntax highlighting, and gutter.
2
3use crate::buffer::LineBuffer;
4use crate::cursor::{MultiCursor, Position, Selection};
5use crate::diagnostics::{DiagnosticCollection, DiagnosticCounts, EditorDiagnostic};
6use crate::history::HistoryStack;
7use crate::ime::ImeComposition;
8use crate::minimap::{minimap_y_to_scroll_top, MinimapConfig};
9use crate::search::{FindReplaceState, SearchMatch};
10use crate::syntax::{FoldRange, Language, SyntaxHighlighter, TokenType};
11use crate::theme::EditorTheme;
12use strata_dom::{Event, NodeBlueprint, Tag};
13
14/// High-level code editor managing buffer state, multi-cursors, incremental syntax,
15/// search/replace, folding, diagnostics, theming, and virtualized rendering.
16#[derive(Debug, Clone)]
17pub struct CodeEditor {
18    buffer: LineBuffer,
19    cursors: MultiCursor,
20    history: HistoryStack,
21    highlighter: SyntaxHighlighter,
22    language: Language,
23    folded_lines: Vec<usize>,
24    cached_folds: Vec<FoldRange>,
25    folds_valid: bool,
26    ime: ImeComposition,
27    tab_size: usize,
28    wrap_column: Option<usize>,
29    search: FindReplaceState,
30    diagnostics: DiagnosticCollection,
31    theme: EditorTheme,
32    scroll_top: f32,
33    scroll_left: f32,
34    viewport_height: f32,
35    line_height: f32,
36    char_width: f32,
37    read_only: bool,
38    is_pointer_dragging: bool,
39}
40
41impl CodeEditor {
42    /// Constructs a new code editor with initial source code and language syntax.
43    pub fn new(content: &str, language: Language) -> Self {
44        let buffer = LineBuffer::from_str(content);
45        let mut highlighter = SyntaxHighlighter::with_language(language);
46        highlighter.parse_buffer(&buffer);
47        let mut diagnostics = DiagnosticCollection::new();
48        diagnostics.set_syntax_diagnostics(highlighter.collect_syntax_diagnostics(&buffer));
49        Self {
50            buffer,
51            cursors: MultiCursor::new(),
52            history: HistoryStack::default(),
53            highlighter,
54            language,
55            folded_lines: Vec::new(),
56            cached_folds: Vec::new(),
57            folds_valid: false,
58            ime: ImeComposition::new(),
59            tab_size: 4,
60            wrap_column: None,
61            search: FindReplaceState::new(),
62            diagnostics,
63            theme: EditorTheme::default(),
64            scroll_top: 0.0,
65            scroll_left: 0.0,
66            viewport_height: 480.0,
67            line_height: 22.0,
68            char_width: 8.4,
69            read_only: false,
70            is_pointer_dragging: false,
71        }
72    }
73
74    /// Synchronizes live syntax diagnostics, invalidates cached folds, and refreshes open search results.
75    fn on_buffer_mutated(&mut self) {
76        self.folds_valid = false;
77        self.diagnostics
78            .set_syntax_diagnostics(self.highlighter.collect_syntax_diagnostics(&self.buffer));
79        if self.search.is_open && !self.search.query.is_empty() {
80            self.search.recompute_matches(&self.buffer);
81        }
82    }
83
84    /// Accesses the active syntax highlighter.
85    pub fn highlighter(&self) -> &SyntaxHighlighter {
86        &self.highlighter
87    }
88
89    /// Accesses the active syntax highlighter mutably.
90    pub fn highlighter_mut(&mut self) -> &mut SyntaxHighlighter {
91        &mut self.highlighter
92    }
93
94    /// Returns the active syntax language.
95    pub fn language(&self) -> Language {
96        self.language
97    }
98
99    /// Changes the syntax language and re-parses the AST directly from the rope buffer.
100    pub fn set_language(&mut self, language: Language) {
101        self.language = language;
102        self.highlighter.set_language(language);
103        self.highlighter.parse_buffer(&self.buffer);
104        self.folded_lines.clear();
105        self.on_buffer_mutated();
106    }
107
108    /// Re-parses the document incrementally with the active Tree-Sitter grammar via zero-copy rope slices.
109    pub fn reparse(&mut self) {
110        let total = self.buffer.line_count();
111        self.highlighter
112            .reparse_incremental_buffer(&self.buffer, 0, total);
113        self.on_buffer_mutated();
114    }
115
116    /// Feeds one or more chronological `tree_sitter::InputEdit` records into the syntax
117    /// highlighter and performs a localized incremental reparse directly from the rope.
118    fn apply_syntax_edits_and_reparse(&mut self, edits: &[tree_sitter::InputEdit]) {
119        if edits.is_empty() {
120            return;
121        }
122        let mut dirty_start = usize::MAX;
123        let mut dirty_end = 0usize;
124        for edit in edits {
125            self.highlighter.edit(edit);
126            dirty_start = dirty_start.min(edit.start_position.row);
127            let row_delta =
128                edit.new_end_position.row as isize - edit.old_end_position.row as isize;
129            let shifted_end = (dirty_end as isize + row_delta).max(0) as usize;
130            dirty_end = shifted_end.max(edit.new_end_position.row.saturating_add(1));
131        }
132        if dirty_start == usize::MAX {
133            dirty_start = 0;
134        }
135        self.highlighter
136            .reparse_incremental_buffer(&self.buffer, dirty_start, dirty_end);
137        self.on_buffer_mutated();
138    }
139
140    /// Accesses the underlying line buffer.
141    pub fn buffer(&self) -> &LineBuffer {
142        &self.buffer
143    }
144
145    /// Accesses the undo/redo history stack.
146    pub fn history(&self) -> &HistoryStack {
147        &self.history
148    }
149
150    /// Accesses the active Find & Replace state.
151    pub fn search(&self) -> &FindReplaceState {
152        &self.search
153    }
154
155    /// Mutably accesses the active Find & Replace state.
156    pub fn search_mut(&mut self) -> &mut FindReplaceState {
157        &mut self.search
158    }
159
160    /// Accesses the diagnostics collection (live syntax + external LSP diagnostics).
161    pub fn diagnostics(&self) -> &DiagnosticCollection {
162        &self.diagnostics
163    }
164
165    /// Replaces external/LSP diagnostics while preserving live syntax diagnostics.
166    pub fn set_external_diagnostics(&mut self, diagnostics: Vec<EditorDiagnostic>) {
167        self.diagnostics.set_external(diagnostics);
168    }
169
170    /// Clears external/LSP diagnostics.
171    pub fn clear_external_diagnostics(&mut self) {
172        self.diagnostics.clear_external();
173    }
174
175    /// Returns diagnostic severity counts for status bars and badges.
176    pub fn diagnostic_counts(&self) -> DiagnosticCounts {
177        self.diagnostics.counts()
178    }
179
180    /// Accesses the active CSS-variable editor theme.
181    pub fn theme(&self) -> &EditorTheme {
182        &self.theme
183    }
184
185    /// Updates the active editor theme.
186    pub fn set_theme(&mut self, theme: EditorTheme) {
187        self.theme = theme;
188    }
189
190    pub fn read_only(&self) -> bool {
191        self.read_only
192    }
193
194    pub fn set_read_only(&mut self, read_only: bool) {
195        self.read_only = read_only;
196    }
197
198    pub fn scroll_top(&self) -> f32 {
199        self.scroll_top
200    }
201
202    pub fn set_scroll_top(&mut self, scroll_top: f32) {
203        let max_scroll = self.max_scroll_top();
204        self.scroll_top = scroll_top.clamp(0.0, max_scroll);
205    }
206
207    pub fn scroll_left(&self) -> f32 {
208        self.scroll_left
209    }
210
211    pub fn set_scroll_left(&mut self, scroll_left: f32) {
212        self.scroll_left = scroll_left.max(0.0);
213    }
214
215    pub fn viewport_height(&self) -> f32 {
216        self.viewport_height
217    }
218
219    pub fn set_viewport_height(&mut self, height: f32) {
220        self.viewport_height = height.max(40.0);
221        let max_scroll = self.max_scroll_top();
222        self.scroll_top = self.scroll_top.clamp(0.0, max_scroll);
223    }
224
225    pub fn line_height(&self) -> f32 {
226        self.line_height
227    }
228
229    pub fn set_line_height(&mut self, line_height: f32) {
230        self.line_height = line_height.max(12.0);
231    }
232
233    pub fn char_width(&self) -> f32 {
234        self.char_width
235    }
236
237    pub fn set_char_width(&mut self, char_width: f32) {
238        self.char_width = char_width.max(4.0);
239    }
240
241    pub fn max_scroll_top(&self) -> f32 {
242        let visible_rows = self.visible_logical_lines().len().max(1) as f32;
243        (visible_rows * self.line_height - self.viewport_height).max(0.0)
244    }
245
246    /// Accesses the active cursors.
247    pub fn cursors(&self) -> &MultiCursor {
248        &self.cursors
249    }
250
251    /// Accesses the active cursors mutably.
252    pub fn cursors_mut(&mut self) -> &mut MultiCursor {
253        &mut self.cursors
254    }
255
256    /// Returns the active IME composition state.
257    pub fn ime(&self) -> &ImeComposition {
258        &self.ime
259    }
260
261    /// Mutably accesses the IME composition state.
262    pub fn ime_mut(&mut self) -> &mut ImeComposition {
263        &mut self.ime
264    }
265
266    /// Returns the configured tab size (in spaces).
267    pub fn tab_size(&self) -> usize {
268        self.tab_size
269    }
270
271    /// Configures tab size.
272    pub fn set_tab_size(&mut self, size: usize) {
273        self.tab_size = size;
274    }
275
276    /// Returns the soft-wrap column limit, if enabled.
277    pub fn wrap_column(&self) -> Option<usize> {
278        self.wrap_column
279    }
280
281    /// Configures soft-wrap column limit.
282    pub fn set_wrap_column(&mut self, wrap: Option<usize>) {
283        self.wrap_column = wrap;
284    }
285
286    /// Total number of lines in the buffer.
287    pub fn line_count(&self) -> usize {
288        self.buffer.line_count()
289    }
290
291    /// Serializes entire buffer content to a String.
292    pub fn text(&self) -> String {
293        self.buffer.to_string()
294    }
295
296    /// Replaces entire buffer content and resets history.
297    pub fn set_text(&mut self, text: &str) {
298        self.buffer = LineBuffer::from_str(text);
299        self.cursors.set_single(Position::ZERO);
300        self.history = HistoryStack::default();
301        self.folded_lines.clear();
302        self.scroll_top = 0.0;
303        self.scroll_left = 0.0;
304        self.highlighter.parse_buffer(&self.buffer);
305        self.on_buffer_mutated();
306    }
307
308    /// Inserts a character at all active cursors (or handles Enter with auto-indentation).
309    pub fn insert_char(&mut self, ch: char) {
310        if ch == '\n' {
311            self.insert_newline();
312        } else {
313            self.insert_text(&ch.to_string());
314        }
315    }
316
317    /// Inserts a newline with automatic indentation calculated from the syntax engine.
318    pub fn insert_newline(&mut self) {
319        self.cursors.normalize();
320        let before_all = self.cursors.all().to_vec();
321        let descending = self.cursors.selections_descending();
322
323        let mut operations = Vec::with_capacity(descending.len() * 2);
324        let mut syntax_edits = Vec::with_capacity(descending.len() * 2);
325        let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
326
327        for sel in descending {
328            let (start, end) = sel.ordered_range();
329            if start != end {
330                let (del_edit, _) = self.buffer.compute_input_edit(start, end, "");
331                let deleted = self
332                    .buffer
333                    .delete_range(start.line, start.col, end.line, end.col);
334                syntax_edits.push(del_edit);
335                operations.push(crate::history::EditOperation::Delete {
336                    start,
337                    end,
338                    text: deleted,
339                });
340            }
341
342            let indent_spaces = self
343                .highlighter
344                .compute_auto_indent(&self.buffer, start.line);
345            let indent_str = if indent_spaces > 0 {
346                " ".repeat(indent_spaces)
347            } else {
348                String::new()
349            };
350            let inserted_text = format!("\n{indent_str}");
351            let (ins_edit, _) = self.buffer.compute_input_edit(start, start, &inserted_text);
352
353            self.buffer.split_line(start.line, start.col);
354            let new_line = start.line + 1;
355            if !indent_str.is_empty() {
356                self.buffer.insert_str(new_line, 0, &indent_str);
357            }
358            syntax_edits.push(ins_edit);
359
360            operations.push(crate::history::EditOperation::Insert {
361                pos: start,
362                text: inserted_text,
363            });
364
365            let lines_slice: Vec<&str> = vec!["", &indent_str];
366            let my_new_pos = Position::new(new_line, indent_spaces);
367
368            for caret in &mut processed_carets {
369                *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &lines_slice);
370            }
371
372            processed_carets.push(my_new_pos);
373        }
374
375        let new_cursors: Vec<Selection> =
376            processed_carets.into_iter().map(Selection::point).collect();
377
378        self.cursors = MultiCursor::from_selections(new_cursors);
379
380        self.history
381            .push_transaction(crate::history::EditorTransaction::new(
382                operations,
383                before_all,
384                self.cursors.all().to_vec(),
385            ));
386
387        self.apply_syntax_edits_and_reparse(&syntax_edits);
388    }
389
390    /// Inserts text at all cursor positions atomically in descending document order.
391    pub fn insert_text(&mut self, text: &str) {
392        if text.is_empty() {
393            return;
394        }
395
396        self.cursors.normalize();
397        let before_all = self.cursors.all().to_vec();
398        let descending = self.cursors.selections_descending();
399
400        let mut operations = Vec::with_capacity(descending.len());
401        let mut syntax_edits = Vec::with_capacity(descending.len() * 2);
402        let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
403
404        let text_lines: Vec<&str> = text.split('\n').collect();
405
406        for sel in descending {
407            let (start, end) = sel.ordered_range();
408            if start != end {
409                let (del_edit, _) = self.buffer.compute_input_edit(start, end, "");
410                let deleted = self
411                    .buffer
412                    .delete_range(start.line, start.col, end.line, end.col);
413                syntax_edits.push(del_edit);
414                operations.push(crate::history::EditOperation::Delete {
415                    start,
416                    end,
417                    text: deleted,
418                });
419            }
420
421            let (ins_edit, _) = self.buffer.compute_input_edit(start, start, text);
422            self.buffer.insert_str(start.line, start.col, text);
423            syntax_edits.push(ins_edit);
424            operations.push(crate::history::EditOperation::Insert {
425                pos: start,
426                text: text.to_string(),
427            });
428
429            let my_new_pos = if text_lines.len() == 1 {
430                Position::new(start.line, start.col + text_lines[0].chars().count())
431            } else {
432                Position::new(
433                    start.line + text_lines.len() - 1,
434                    text_lines.last().map_or(0, |l| l.chars().count()),
435                )
436            };
437
438            for caret in &mut processed_carets {
439                *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &text_lines);
440            }
441
442            processed_carets.push(my_new_pos);
443        }
444
445        let new_cursors: Vec<Selection> =
446            processed_carets.into_iter().map(Selection::point).collect();
447
448        self.cursors = MultiCursor::from_selections(new_cursors);
449
450        self.history
451            .push_transaction(crate::history::EditorTransaction::new(
452                operations,
453                before_all,
454                self.cursors.all().to_vec(),
455            ));
456
457        self.apply_syntax_edits_and_reparse(&syntax_edits);
458    }
459
460    /// Performs backspace deletion at all active cursors atomically in descending document order.
461    pub fn delete_backwards(&mut self) {
462        self.cursors.normalize();
463        let before_all = self.cursors.all().to_vec();
464        let descending = self.cursors.selections_descending();
465
466        let mut operations = Vec::with_capacity(descending.len());
467        let mut syntax_edits = Vec::with_capacity(descending.len());
468        let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
469
470        for sel in descending {
471            let (start, end) = sel.ordered_range();
472            if start != end {
473                let (del_edit, _) = self.buffer.compute_input_edit(start, end, "");
474                let deleted = self
475                    .buffer
476                    .delete_range(start.line, start.col, end.line, end.col);
477                syntax_edits.push(del_edit);
478                operations.push(crate::history::EditOperation::Delete {
479                    start,
480                    end,
481                    text: deleted,
482                });
483
484                for caret in &mut processed_carets {
485                    *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &[""]);
486                }
487
488                processed_carets.push(start);
489            } else if start.col > 0 {
490                let del_start = Position::new(start.line, start.col - 1);
491                let (del_edit, _) = self.buffer.compute_input_edit(del_start, start, "");
492                let deleted =
493                    self.buffer
494                        .delete_range(del_start.line, del_start.col, start.line, start.col);
495                syntax_edits.push(del_edit);
496                operations.push(crate::history::EditOperation::Delete {
497                    start: del_start,
498                    end: start,
499                    text: deleted,
500                });
501
502                for caret in &mut processed_carets {
503                    *caret =
504                        crate::cursor::shift_position_after_edit(*caret, del_start, start, &[""]);
505                }
506
507                processed_carets.push(del_start);
508            } else if start.line > 0 {
509                let prev_line = start.line - 1;
510                let prev_len = self.buffer.line_len(prev_line);
511                let del_start = Position::new(prev_line, prev_len);
512                let del_end = Position::new(start.line, 0);
513                let (del_edit, _) = self.buffer.compute_input_edit(del_start, del_end, "");
514
515                self.buffer.join_line_with_next(prev_line);
516                syntax_edits.push(del_edit);
517                operations.push(crate::history::EditOperation::Delete {
518                    start: del_start,
519                    end: del_end,
520                    text: "\n".to_string(),
521                });
522
523                for caret in &mut processed_carets {
524                    *caret = crate::cursor::shift_position_after_edit(
525                        *caret,
526                        del_start,
527                        del_end,
528                        &[""],
529                    );
530                }
531
532                processed_carets.push(del_start);
533            } else {
534                processed_carets.push(start);
535            }
536        }
537
538        let new_cursors: Vec<Selection> =
539            processed_carets.into_iter().map(Selection::point).collect();
540
541        self.cursors = MultiCursor::from_selections(new_cursors);
542
543        if !operations.is_empty() {
544            self.history
545                .push_transaction(crate::history::EditorTransaction::new(
546                    operations,
547                    before_all,
548                    self.cursors.all().to_vec(),
549                ));
550            self.apply_syntax_edits_and_reparse(&syntax_edits);
551        }
552    }
553
554    /// Performs forward Delete key deletion at all active cursors atomically.
555    pub fn delete_forward(&mut self) {
556        self.cursors.normalize();
557        let before_all = self.cursors.all().to_vec();
558        let descending = self.cursors.selections_descending();
559
560        let mut operations = Vec::with_capacity(descending.len());
561        let mut syntax_edits = Vec::with_capacity(descending.len());
562        let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
563
564        for sel in descending {
565            let (start, end) = sel.ordered_range();
566            if start != end {
567                let (del_edit, _) = self.buffer.compute_input_edit(start, end, "");
568                let deleted = self
569                    .buffer
570                    .delete_range(start.line, start.col, end.line, end.col);
571                syntax_edits.push(del_edit);
572                operations.push(crate::history::EditOperation::Delete {
573                    start,
574                    end,
575                    text: deleted,
576                });
577                for caret in &mut processed_carets {
578                    *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &[""]);
579                }
580                processed_carets.push(start);
581            } else {
582                let line_len = self.buffer.line_len(start.line);
583                if start.col < line_len {
584                    let del_end = Position::new(start.line, start.col + 1);
585                    let (del_edit, _) = self.buffer.compute_input_edit(start, del_end, "");
586                    let deleted =
587                        self.buffer
588                            .delete_range(start.line, start.col, del_end.line, del_end.col);
589                    syntax_edits.push(del_edit);
590                    operations.push(crate::history::EditOperation::Delete {
591                        start,
592                        end: del_end,
593                        text: deleted,
594                    });
595                    for caret in &mut processed_carets {
596                        *caret = crate::cursor::shift_position_after_edit(
597                            *caret,
598                            start,
599                            del_end,
600                            &[""],
601                        );
602                    }
603                    processed_carets.push(start);
604                } else if start.line + 1 < self.buffer.line_count() {
605                    let del_end = Position::new(start.line + 1, 0);
606                    let (del_edit, _) = self.buffer.compute_input_edit(start, del_end, "");
607                    self.buffer.join_line_with_next(start.line);
608                    syntax_edits.push(del_edit);
609                    operations.push(crate::history::EditOperation::Delete {
610                        start,
611                        end: del_end,
612                        text: "\n".to_string(),
613                    });
614                    for caret in &mut processed_carets {
615                        *caret = crate::cursor::shift_position_after_edit(
616                            *caret,
617                            start,
618                            del_end,
619                            &[""],
620                        );
621                    }
622                    processed_carets.push(start);
623                } else {
624                    processed_carets.push(start);
625                }
626            }
627        }
628
629        let new_cursors: Vec<Selection> =
630            processed_carets.into_iter().map(Selection::point).collect();
631        self.cursors = MultiCursor::from_selections(new_cursors);
632
633        if !operations.is_empty() {
634            self.history
635                .push_transaction(crate::history::EditorTransaction::new(
636                    operations,
637                    before_all,
638                    self.cursors.all().to_vec(),
639                ));
640            self.apply_syntax_edits_and_reparse(&syntax_edits);
641        }
642    }
643
644    /// Replaces an arbitrary `[start, end)` range with `replacement` as a single undoable
645    /// transaction and drives an incremental Tree-Sitter / line-state update.
646    /// Returns the resulting end `Position` of `replacement`.
647    pub fn replace_range(
648        &mut self,
649        start: Position,
650        end: Position,
651        replacement: &str,
652    ) -> Position {
653        let (s, e) = if start <= end {
654            (start, end)
655        } else {
656            (end, start)
657        };
658        let before_all = self.cursors.all().to_vec();
659        let mut operations = Vec::with_capacity(2);
660        let mut syntax_edits = Vec::with_capacity(2);
661
662        if s != e {
663            let (del_edit, _) = self.buffer.compute_input_edit(s, e, "");
664            let deleted = self.buffer.delete_range(s.line, s.col, e.line, e.col);
665            syntax_edits.push(del_edit);
666            operations.push(crate::history::EditOperation::Delete {
667                start: s,
668                end: e,
669                text: deleted,
670            });
671        }
672
673        let new_end = if !replacement.is_empty() {
674            let (ins_edit, end_pos) = self.buffer.compute_input_edit(s, s, replacement);
675            self.buffer.insert_str(s.line, s.col, replacement);
676            syntax_edits.push(ins_edit);
677            operations.push(crate::history::EditOperation::Insert {
678                pos: s,
679                text: replacement.to_string(),
680            });
681            end_pos
682        } else {
683            s
684        };
685
686        self.cursors.set_single(new_end);
687        if !operations.is_empty() {
688            self.history
689                .push_transaction(crate::history::EditorTransaction::new(
690                    operations,
691                    before_all,
692                    self.cursors.all().to_vec(),
693                ));
694            self.apply_syntax_edits_and_reparse(&syntax_edits);
695        }
696        new_end
697    }
698
699    /// Atomically replaces multiple disjoint `(start, end, replacement)` ranges in descending
700    /// document order as a single undo transaction and a single incremental AST reparse.
701    pub fn replace_ranges_atomic(&mut self, mut replacements: Vec<(Position, Position, String)>) {
702        if replacements.is_empty() {
703            return;
704        }
705        // Normalize and sort descending so earlier offsets remain valid as later ones change.
706        for item in &mut replacements {
707            if item.0 > item.1 {
708                std::mem::swap(&mut item.0, &mut item.1);
709            }
710        }
711        replacements.sort_by_key(|item| std::cmp::Reverse(item.0));
712
713        let before_all = self.cursors.all().to_vec();
714        let mut operations = Vec::with_capacity(replacements.len() * 2);
715        let mut syntax_edits = Vec::with_capacity(replacements.len() * 2);
716        let mut last_pos = Position::ZERO;
717
718        for (s, e, repl) in replacements {
719            if s != e {
720                let (del_edit, _) = self.buffer.compute_input_edit(s, e, "");
721                let deleted = self.buffer.delete_range(s.line, s.col, e.line, e.col);
722                syntax_edits.push(del_edit);
723                operations.push(crate::history::EditOperation::Delete {
724                    start: s,
725                    end: e,
726                    text: deleted,
727                });
728            }
729            if !repl.is_empty() {
730                let (ins_edit, end_pos) = self.buffer.compute_input_edit(s, s, &repl);
731                self.buffer.insert_str(s.line, s.col, &repl);
732                syntax_edits.push(ins_edit);
733                operations.push(crate::history::EditOperation::Insert { pos: s, text: repl });
734                last_pos = end_pos;
735            } else {
736                last_pos = s;
737            }
738        }
739
740        self.cursors.set_single(last_pos);
741        if !operations.is_empty() {
742            self.history
743                .push_transaction(crate::history::EditorTransaction::new(
744                    operations,
745                    before_all,
746                    self.cursors.all().to_vec(),
747                ));
748            self.apply_syntax_edits_and_reparse(&syntax_edits);
749        }
750    }
751
752    /// Undoes the last recorded transaction with incremental AST synchronization.
753    pub fn undo(&mut self) {
754        if let Some((restored, edits)) = self.history.undo_with_edits(&mut self.buffer) {
755            self.cursors = MultiCursor::from_selections(restored);
756            self.apply_syntax_edits_and_reparse(&edits);
757        }
758    }
759
760    /// Redoes the last undone transaction with incremental AST synchronization.
761    pub fn redo(&mut self) {
762        if let Some((restored, edits)) = self.history.redo_with_edits(&mut self.buffer) {
763            self.cursors = MultiCursor::from_selections(restored);
764            self.apply_syntax_edits_and_reparse(&edits);
765        }
766    }
767
768    /// Moves all active cursors left by 1 character.
769    pub fn move_left(&mut self, select: bool) {
770        let before = self.cursors.all().to_vec();
771        let mut new_cursors = Vec::with_capacity(before.len());
772
773        for sel in &before {
774            let focus = sel.focus;
775            let new_focus = if focus.col > 0 {
776                Position::new(focus.line, focus.col - 1)
777            } else if focus.line > 0 {
778                let prev_line = focus.line - 1;
779                let prev_len = self.buffer.line_len(prev_line);
780                Position::new(prev_line, prev_len)
781            } else {
782                Position::ZERO
783            };
784
785            let anchor = if select { sel.anchor } else { new_focus };
786            new_cursors.push(Selection::range(anchor, new_focus));
787        }
788
789        self.cursors = MultiCursor::from_selections(new_cursors);
790    }
791
792    /// Moves all active cursors right by 1 character.
793    pub fn move_right(&mut self, select: bool) {
794        let before = self.cursors.all().to_vec();
795        let mut new_cursors = Vec::with_capacity(before.len());
796
797        for sel in &before {
798            let focus = sel.focus;
799            let cur_line_len = self.buffer.line_len(focus.line);
800
801            let new_focus = if focus.col < cur_line_len {
802                Position::new(focus.line, focus.col + 1)
803            } else if focus.line + 1 < self.buffer.line_count() {
804                Position::new(focus.line + 1, 0)
805            } else {
806                Position::new(focus.line, cur_line_len)
807            };
808
809            let anchor = if select { sel.anchor } else { new_focus };
810            new_cursors.push(Selection::range(anchor, new_focus));
811        }
812
813        self.cursors = MultiCursor::from_selections(new_cursors);
814    }
815
816    /// Moves all active cursors up by 1 line.
817    pub fn move_up(&mut self, select: bool) {
818        let before = self.cursors.all().to_vec();
819        let mut new_cursors = Vec::with_capacity(before.len());
820
821        for sel in &before {
822            let focus = sel.focus;
823            let new_focus = if focus.line > 0 {
824                let prev_line = focus.line - 1;
825                let prev_len = self.buffer.line_len(prev_line);
826                Position::new(prev_line, focus.col.min(prev_len))
827            } else {
828                Position::new(0, 0)
829            };
830
831            let anchor = if select { sel.anchor } else { new_focus };
832            new_cursors.push(Selection::range(anchor, new_focus));
833        }
834
835        self.cursors = MultiCursor::from_selections(new_cursors);
836    }
837
838    /// Moves all active cursors down by 1 line.
839    pub fn move_down(&mut self, select: bool) {
840        let before = self.cursors.all().to_vec();
841        let mut new_cursors = Vec::with_capacity(before.len());
842
843        for sel in &before {
844            let focus = sel.focus;
845            let new_focus = if focus.line + 1 < self.buffer.line_count() {
846                let next_line = focus.line + 1;
847                let next_len = self.buffer.line_len(next_line);
848                Position::new(next_line, focus.col.min(next_len))
849            } else {
850                let last_len = self.buffer.line_len(focus.line);
851                Position::new(focus.line, last_len)
852            };
853
854            let anchor = if select { sel.anchor } else { new_focus };
855            new_cursors.push(Selection::range(anchor, new_focus));
856        }
857
858        self.cursors = MultiCursor::from_selections(new_cursors);
859    }
860
861    /// Moves all active cursors to the start of their respective line.
862    pub fn move_to_line_start(&mut self, select: bool) {
863        let before = self.cursors.all().to_vec();
864        let mut new_cursors = Vec::with_capacity(before.len());
865
866        for sel in &before {
867            let new_focus = Position::new(sel.focus.line, 0);
868            let anchor = if select { sel.anchor } else { new_focus };
869            new_cursors.push(Selection::range(anchor, new_focus));
870        }
871
872        self.cursors = MultiCursor::from_selections(new_cursors);
873    }
874
875    /// Moves all active cursors to the end of their respective line.
876    pub fn move_to_line_end(&mut self, select: bool) {
877        let before = self.cursors.all().to_vec();
878        let mut new_cursors = Vec::with_capacity(before.len());
879
880        for sel in &before {
881            let line_len = self.buffer.line_len(sel.focus.line);
882            let new_focus = Position::new(sel.focus.line, line_len);
883            let anchor = if select { sel.anchor } else { new_focus };
884            new_cursors.push(Selection::range(anchor, new_focus));
885        }
886
887        self.cursors = MultiCursor::from_selections(new_cursors);
888    }
889
890    /// Selects all text in the document.
891    pub fn select_all(&mut self) {
892        let total_lines = self.buffer.line_count();
893        let last_line = total_lines.saturating_sub(1);
894        let last_col = self.buffer.line_len(last_line);
895        self.cursors.set_single(Position::ZERO);
896        self.cursors.all_mut()[0] =
897            Selection::range(Position::ZERO, Position::new(last_line, last_col));
898    }
899
900    /// Ensures structural fold ranges are computed and cached for the current buffer state.
901    pub fn ensure_folds_cached(&mut self) -> &[FoldRange] {
902        if !self.folds_valid {
903            self.cached_folds = self.highlighter.compute_fold_ranges(&self.buffer);
904            self.folds_valid = true;
905            // Prune stale folded line indices that no longer correspond to a fold start.
906            self.folded_lines.retain(|&line| {
907                self.cached_folds.iter().any(|f| f.start_line == line)
908            });
909        }
910        &self.cached_folds
911    }
912
913    /// Returns all structural fold ranges for the current document (using cache when valid).
914    pub fn fold_ranges(&self) -> Vec<FoldRange> {
915        if self.folds_valid {
916            self.cached_folds.clone()
917        } else {
918            self.highlighter.compute_fold_ranges(&self.buffer)
919        }
920    }
921
922    /// Toggles code folding on the specified line.
923    pub fn toggle_fold(&mut self, line: usize) {
924        if let Some(pos) = self.folded_lines.iter().position(|&l| l == line) {
925            self.folded_lines.remove(pos);
926        } else {
927            self.folded_lines.push(line);
928        }
929    }
930
931    /// Toggles folding at `line` only if `line` starts a foldable range; returns `true` if toggled.
932    pub fn toggle_fold_at(&mut self, line: usize) -> bool {
933        let is_fold_start = self
934            .ensure_folds_cached()
935            .iter()
936            .any(|f| f.start_line == line && f.end_line > f.start_line);
937        if !is_fold_start {
938            return false;
939        }
940        self.toggle_fold(line);
941        true
942    }
943
944    /// Collapses every foldable block in the document.
945    pub fn fold_all(&mut self) {
946        let starts: Vec<usize> = self
947            .ensure_folds_cached()
948            .iter()
949            .filter(|f| f.end_line > f.start_line)
950            .map(|f| f.start_line)
951            .collect();
952        self.folded_lines = starts;
953        self.folded_lines.sort_unstable();
954        self.folded_lines.dedup();
955    }
956
957    /// Expands all folded regions in the document.
958    pub fn unfold_all(&mut self) {
959        self.folded_lines.clear();
960    }
961
962    /// Checks if the line is currently folded.
963    pub fn is_folded(&self, line: usize) -> bool {
964        self.folded_lines.contains(&line)
965    }
966
967    /// If `line` is currently folded, returns the number of hidden lines beneath it.
968    pub fn folded_hidden_count(&self, line: usize) -> Option<usize> {
969        if !self.is_folded(line) {
970            return None;
971        }
972        let folds = self.fold_ranges();
973        folds
974            .iter()
975            .filter(|f| f.start_line == line && f.end_line > line)
976            .map(|f| f.end_line - f.start_line)
977            .max()
978    }
979
980    /// Returns the ordered list of visible 0-indexed logical line numbers after skipping
981    /// lines concealed inside collapsed fold regions.
982    pub fn visible_logical_lines(&self) -> Vec<usize> {
983        let total = self.buffer.line_count();
984        if self.folded_lines.is_empty() {
985            return (0..total).collect();
986        }
987        let folds = self.fold_ranges();
988        let mut collapsed_spans: Vec<(usize, usize)> = folds
989            .iter()
990            .filter(|f| self.folded_lines.contains(&f.start_line) && f.end_line > f.start_line)
991            .map(|f| (f.start_line + 1, f.end_line.min(total.saturating_sub(1))))
992            .collect();
993        if collapsed_spans.is_empty() {
994            return (0..total).collect();
995        }
996        collapsed_spans.sort_unstable_by_key(|&(s, _)| s);
997
998        let mut visible = Vec::with_capacity(total);
999        let mut line = 0usize;
1000        let mut span_idx = 0usize;
1001        while line < total {
1002            while span_idx < collapsed_spans.len() && collapsed_spans[span_idx].1 < line {
1003                span_idx += 1;
1004            }
1005            if span_idx < collapsed_spans.len()
1006                && line >= collapsed_spans[span_idx].0
1007                && line <= collapsed_spans[span_idx].1
1008            {
1009                line = collapsed_spans[span_idx].1 + 1;
1010                continue;
1011            }
1012            visible.push(line);
1013            line += 1;
1014        }
1015        visible
1016    }
1017
1018    /// Maps a 0-indexed logical line number to its visible display row index (or `None` if hidden inside a fold).
1019    pub fn logical_to_display_row(&self, logical_line: usize) -> Option<usize> {
1020        if self.folded_lines.is_empty() {
1021            return (logical_line < self.buffer.line_count()).then_some(logical_line);
1022        }
1023        let visible = self.visible_logical_lines();
1024        visible.binary_search(&logical_line).ok()
1025    }
1026
1027    /// Maps a visible display row index back to its 0-indexed logical line number.
1028    pub fn display_row_to_logical(&self, display_row: usize) -> Option<usize> {
1029        if self.folded_lines.is_empty() {
1030            return (display_row < self.buffer.line_count()).then_some(display_row);
1031        }
1032        let visible = self.visible_logical_lines();
1033        visible.get(display_row).copied()
1034    }
1035
1036    // -------------------------------------------------------------------------
1037    // Find & Replace Controller Delegation
1038    // -------------------------------------------------------------------------
1039
1040    pub fn open_find(&mut self) {
1041        self.search.open_find();
1042        if !self.search.query.is_empty() {
1043            self.search.recompute_matches(&self.buffer);
1044        }
1045    }
1046
1047    pub fn open_replace(&mut self) {
1048        self.search.open_replace();
1049        if !self.search.query.is_empty() {
1050            self.search.recompute_matches(&self.buffer);
1051        }
1052    }
1053
1054    pub fn close_find(&mut self) {
1055        self.search.close();
1056    }
1057
1058    pub fn set_find_query(&mut self, query: impl Into<String>) {
1059        self.search.set_query(query, &self.buffer);
1060        if let Some(m) = self.search.active_match().cloned() {
1061            self.select_search_match(&m);
1062        }
1063    }
1064
1065    pub fn set_replace_text(&mut self, replacement: impl Into<String>) {
1066        self.search.set_replacement(replacement);
1067    }
1068
1069    pub fn find_next(&mut self) -> Option<SearchMatch> {
1070        if self.search.matches.is_empty() && !self.search.query.is_empty() {
1071            self.search.recompute_matches(&self.buffer);
1072        }
1073        let m = self.search.find_next()?;
1074        self.select_search_match(&m);
1075        Some(m)
1076    }
1077
1078    pub fn find_prev(&mut self) -> Option<SearchMatch> {
1079        if self.search.matches.is_empty() && !self.search.query.is_empty() {
1080            self.search.recompute_matches(&self.buffer);
1081        }
1082        let m = self.search.find_prev()?;
1083        self.select_search_match(&m);
1084        Some(m)
1085    }
1086
1087    pub fn replace_current(&mut self) -> bool {
1088        if self.read_only {
1089            return false;
1090        }
1091        let mut search = std::mem::take(&mut self.search);
1092        let replaced = search.replace_current(self);
1093        self.search = search;
1094        if let Some(m) = self.search.active_match().cloned() {
1095            self.select_search_match(&m);
1096        }
1097        replaced
1098    }
1099
1100    pub fn replace_all(&mut self) -> usize {
1101        if self.read_only {
1102            return 0;
1103        }
1104        let mut search = std::mem::take(&mut self.search);
1105        let count = search.replace_all(self);
1106        self.search = search;
1107        count
1108    }
1109
1110    fn select_search_match(&mut self, m: &SearchMatch) {
1111        self.cursors.set_single(m.start);
1112        self.cursors.all_mut()[0] = Selection::range(m.start, m.end);
1113        self.ensure_line_visible(m.start.line);
1114    }
1115
1116    // -------------------------------------------------------------------------
1117    // Monaco-Class Editing, Navigation, Scrolling & Input Event Handlers
1118    // -------------------------------------------------------------------------
1119
1120    /// Toggles single-line comments (`//` or `#`) across all lines touched by active selections.
1121    pub fn toggle_line_comment(&mut self) {
1122        if self.read_only {
1123            return;
1124        }
1125        let Some(prefix) = self.language.line_comment_prefix() else {
1126            return;
1127        };
1128        let mut lines: Vec<usize> = Vec::new();
1129        for sel in self.cursors.all() {
1130            let (s, e) = sel.ordered_range();
1131            for line in s.line..=e.line {
1132                if !lines.contains(&line) {
1133                    lines.push(line);
1134                }
1135            }
1136        }
1137        if lines.is_empty() {
1138            return;
1139        }
1140        lines.sort_unstable();
1141
1142        let all_commented = lines.iter().all(|&l| {
1143            self.buffer
1144                .line(l)
1145                .map(|txt| {
1146                    let t = txt.trim_start();
1147                    t.is_empty() || t.starts_with(prefix)
1148                })
1149                .unwrap_or(true)
1150        });
1151
1152        let mut edits = Vec::new();
1153        let prefix_chars = prefix.chars().count();
1154        for line in lines {
1155            let Some(txt) = self.buffer.line(line) else {
1156                continue;
1157            };
1158            let indent = txt.chars().take_while(|c| *c == ' ' || *c == '\t').count();
1159            if all_commented {
1160                let after_indent: String = txt.chars().skip(indent).collect();
1161                if after_indent.starts_with(prefix) {
1162                    let remove_len = if after_indent[prefix.len()..].starts_with(' ') {
1163                        prefix_chars + 1
1164                    } else {
1165                        prefix_chars
1166                    };
1167                    edits.push((
1168                        Position::new(line, indent),
1169                        Position::new(line, indent + remove_len),
1170                        String::new(),
1171                    ));
1172                }
1173            } else {
1174                edits.push((
1175                    Position::new(line, indent),
1176                    Position::new(line, indent),
1177                    format!("{prefix} "),
1178                ));
1179            }
1180        }
1181        self.replace_ranges_atomic(edits);
1182    }
1183
1184    /// Indents selected lines by `tab_size` spaces (or inserts spaces at collapsed carets).
1185    pub fn indent_selection(&mut self) {
1186        if self.read_only {
1187            return;
1188        }
1189        let spaces = " ".repeat(self.tab_size.max(1));
1190        let has_multiline = self
1191            .cursors
1192            .all()
1193            .iter()
1194            .any(|s| s.anchor.line != s.focus.line);
1195        if !has_multiline && self.cursors.all().iter().all(|s| s.is_collapsed()) {
1196            self.insert_text(&spaces);
1197            return;
1198        }
1199
1200        let mut lines = Vec::new();
1201        for sel in self.cursors.all() {
1202            let (s, e) = sel.ordered_range();
1203            for line in s.line..=e.line {
1204                if !lines.contains(&line) {
1205                    lines.push(line);
1206                }
1207            }
1208        }
1209        let edits: Vec<(Position, Position, String)> = lines
1210            .into_iter()
1211            .map(|l| (Position::new(l, 0), Position::new(l, 0), spaces.clone()))
1212            .collect();
1213        self.replace_ranges_atomic(edits);
1214    }
1215
1216    /// Outdents selected lines by removing up to `tab_size` leading spaces (or one leading `\t`).
1217    pub fn outdent_selection(&mut self) {
1218        if self.read_only {
1219            return;
1220        }
1221        let mut lines = Vec::new();
1222        for sel in self.cursors.all() {
1223            let (s, e) = sel.ordered_range();
1224            for line in s.line..=e.line {
1225                if !lines.contains(&line) {
1226                    lines.push(line);
1227                }
1228            }
1229        }
1230        let mut edits = Vec::new();
1231        for line in lines {
1232            let Some(txt) = self.buffer.line(line) else {
1233                continue;
1234            };
1235            if txt.starts_with('\t') {
1236                edits.push((Position::new(line, 0), Position::new(line, 1), String::new()));
1237            } else {
1238                let leading_spaces = txt.chars().take_while(|&c| c == ' ').count();
1239                let remove = leading_spaces.min(self.tab_size.max(1));
1240                if remove > 0 {
1241                    edits.push((
1242                        Position::new(line, 0),
1243                        Position::new(line, remove),
1244                        String::new(),
1245                    ));
1246                }
1247            }
1248        }
1249        self.replace_ranges_atomic(edits);
1250    }
1251
1252    /// Moves all cursors left by one word boundary.
1253    pub fn move_word_left(&mut self, select: bool) {
1254        let before = self.cursors.all().to_vec();
1255        let mut next = Vec::with_capacity(before.len());
1256        for sel in &before {
1257            let focus = sel.focus;
1258            let new_focus = if focus.col == 0 {
1259                if focus.line > 0 {
1260                    let prev = focus.line - 1;
1261                    Position::new(prev, self.buffer.line_len(prev))
1262                } else {
1263                    Position::ZERO
1264                }
1265            } else if let Some(line_str) = self.buffer.line(focus.line) {
1266                let chars: Vec<char> = line_str.chars().collect();
1267                let mut col = focus.col.min(chars.len());
1268                while col > 0 && chars[col - 1].is_whitespace() {
1269                    col -= 1;
1270                }
1271                if col > 0 {
1272                    let is_word = is_word_char(chars[col - 1]);
1273                    while col > 0 && is_word_char(chars[col - 1]) == is_word && !chars[col - 1].is_whitespace() {
1274                        col -= 1;
1275                    }
1276                }
1277                Position::new(focus.line, col)
1278            } else {
1279                Position::new(focus.line, 0)
1280            };
1281            let anchor = if select { sel.anchor } else { new_focus };
1282            next.push(Selection::range(anchor, new_focus));
1283        }
1284        self.cursors = MultiCursor::from_selections(next);
1285    }
1286
1287    /// Moves all cursors right by one word boundary.
1288    pub fn move_word_right(&mut self, select: bool) {
1289        let before = self.cursors.all().to_vec();
1290        let mut next = Vec::with_capacity(before.len());
1291        for sel in &before {
1292            let focus = sel.focus;
1293            let cur_len = self.buffer.line_len(focus.line);
1294            let new_focus = if focus.col >= cur_len {
1295                if focus.line + 1 < self.buffer.line_count() {
1296                    Position::new(focus.line + 1, 0)
1297                } else {
1298                    Position::new(focus.line, cur_len)
1299                }
1300            } else if let Some(line_str) = self.buffer.line(focus.line) {
1301                let chars: Vec<char> = line_str.chars().collect();
1302                let mut col = focus.col.min(chars.len());
1303                while col < chars.len() && chars[col].is_whitespace() {
1304                    col += 1;
1305                }
1306                if col < chars.len() {
1307                    let is_word = is_word_char(chars[col]);
1308                    while col < chars.len() && is_word_char(chars[col]) == is_word && !chars[col].is_whitespace() {
1309                        col += 1;
1310                    }
1311                }
1312                Position::new(focus.line, col)
1313            } else {
1314                Position::new(focus.line, cur_len)
1315            };
1316            let anchor = if select { sel.anchor } else { new_focus };
1317            next.push(Selection::range(anchor, new_focus));
1318        }
1319        self.cursors = MultiCursor::from_selections(next);
1320    }
1321
1322    /// Moves cursors up by one viewport page.
1323    pub fn page_up(&mut self, select: bool) {
1324        let step = ((self.viewport_height / self.line_height.max(1.0)).floor() as usize).max(1);
1325        let before = self.cursors.all().to_vec();
1326        let mut next = Vec::with_capacity(before.len());
1327        for sel in &before {
1328            let target_line = sel.focus.line.saturating_sub(step);
1329            let target_col = sel.focus.col.min(self.buffer.line_len(target_line));
1330            let new_focus = Position::new(target_line, target_col);
1331            let anchor = if select { sel.anchor } else { new_focus };
1332            next.push(Selection::range(anchor, new_focus));
1333        }
1334        self.cursors = MultiCursor::from_selections(next);
1335        self.ensure_cursor_visible();
1336    }
1337
1338    /// Moves cursors down by one viewport page.
1339    pub fn page_down(&mut self, select: bool) {
1340        let step = ((self.viewport_height / self.line_height.max(1.0)).floor() as usize).max(1);
1341        let max_line = self.buffer.line_count().saturating_sub(1);
1342        let before = self.cursors.all().to_vec();
1343        let mut next = Vec::with_capacity(before.len());
1344        for sel in &before {
1345            let target_line = (sel.focus.line + step).min(max_line);
1346            let target_col = sel.focus.col.min(self.buffer.line_len(target_line));
1347            let new_focus = Position::new(target_line, target_col);
1348            let anchor = if select { sel.anchor } else { new_focus };
1349            next.push(Selection::range(anchor, new_focus));
1350        }
1351        self.cursors = MultiCursor::from_selections(next);
1352        self.ensure_cursor_visible();
1353    }
1354
1355    /// Selects the identifier/word surrounding `pos` (used on double-click).
1356    pub fn select_word_at(&mut self, pos: Position) {
1357        let line = pos.line.min(self.buffer.line_count().saturating_sub(1));
1358        let Some(line_str) = self.buffer.line(line) else {
1359            return;
1360        };
1361        let chars: Vec<char> = line_str.chars().collect();
1362        if chars.is_empty() {
1363            self.cursors.set_single(Position::new(line, 0));
1364            return;
1365        }
1366        let idx = pos.col.min(chars.len().saturating_sub(1));
1367        let target_is_word = is_word_char(chars[idx]);
1368        let mut start = idx;
1369        while start > 0 && is_word_char(chars[start - 1]) == target_is_word && !chars[start - 1].is_whitespace() {
1370            start -= 1;
1371        }
1372        let mut end = idx + 1;
1373        while end < chars.len() && is_word_char(chars[end]) == target_is_word && !chars[end].is_whitespace() {
1374            end += 1;
1375        }
1376        self.cursors.set_single(Position::new(line, start));
1377        self.cursors.all_mut()[0] =
1378            Selection::range(Position::new(line, start), Position::new(line, end));
1379    }
1380
1381    /// Selects the entire logical line (used on triple-click).
1382    pub fn select_line(&mut self, line: usize) {
1383        let clamped = line.min(self.buffer.line_count().saturating_sub(1));
1384        let len = self.buffer.line_len(clamped);
1385        self.cursors.set_single(Position::new(clamped, 0));
1386        self.cursors.all_mut()[0] =
1387            Selection::range(Position::new(clamped, 0), Position::new(clamped, len));
1388    }
1389
1390    /// Scrolls the viewport vertically by `delta_y` pixels.
1391    pub fn scroll_by(&mut self, delta_y: f32) {
1392        self.set_scroll_top(self.scroll_top + delta_y);
1393    }
1394
1395    /// Scrolls so that `logical_line` is positioned near the top of the viewport.
1396    pub fn scroll_to_line(&mut self, logical_line: usize) {
1397        if let Some(display_row) = self.logical_to_display_row(logical_line) {
1398            self.set_scroll_top(display_row as f32 * self.line_height);
1399        }
1400    }
1401
1402    /// Adjusts `scroll_top` minimally so `logical_line` sits inside the visible viewport.
1403    pub fn ensure_line_visible(&mut self, logical_line: usize) {
1404        let Some(display_row) = self.logical_to_display_row(logical_line) else {
1405            return;
1406        };
1407        let row_top = display_row as f32 * self.line_height;
1408        let row_bottom = row_top + self.line_height;
1409        if row_top < self.scroll_top {
1410            self.set_scroll_top(row_top);
1411        } else if row_bottom > self.scroll_top + self.viewport_height {
1412            self.set_scroll_top(row_bottom - self.viewport_height);
1413        }
1414    }
1415
1416    /// Scrolls minimally to keep the primary caret visible.
1417    pub fn ensure_cursor_visible(&mut self) {
1418        let line = self.cursors.primary().focus.line;
1419        self.ensure_line_visible(line);
1420    }
1421
1422    /// Maps an editor-local pointer `(rel_x, rel_y)` to a document [`Position`].
1423    pub fn position_from_point(&self, rel_x: f32, rel_y: f32, gutter_width: f32) -> Position {
1424        let display_row = ((rel_y + self.scroll_top).max(0.0) / self.line_height.max(1.0)).floor() as usize;
1425        let visible = self.visible_logical_lines();
1426        let line = if visible.is_empty() {
1427            0
1428        } else {
1429            visible[display_row.min(visible.len() - 1)]
1430        };
1431        let code_x = (rel_x - gutter_width + self.scroll_left).max(0.0);
1432        let raw_col = (code_x / self.char_width.max(1.0)).round() as usize;
1433        let max_col = self.buffer.line_len(line);
1434        Position::new(line, raw_col.min(max_col))
1435    }
1436
1437    /// Handles pointer press inside the code viewport (click, Shift+click, Alt+click multi-cursor,
1438    /// double-click word selection, triple-click line selection).
1439    pub fn handle_pointer_down(
1440        &mut self,
1441        rel_x: f32,
1442        rel_y: f32,
1443        detail: i32,
1444        alt_key: bool,
1445        shift_key: bool,
1446        gutter_width: f32,
1447    ) {
1448        let pos = self.position_from_point(rel_x, rel_y, gutter_width);
1449        self.is_pointer_dragging = true;
1450        if detail >= 3 {
1451            self.select_line(pos.line);
1452        } else if detail == 2 {
1453            self.select_word_at(pos);
1454        } else if alt_key {
1455            self.cursors.add_cursor(pos);
1456        } else if shift_key {
1457            let anchor = self.cursors.primary().anchor;
1458            self.cursors.set_single(anchor);
1459            self.cursors.all_mut()[0] = Selection::range(anchor, pos);
1460        } else {
1461            self.cursors.set_single(pos);
1462        }
1463    }
1464
1465    /// Extends the active primary selection while dragging the pointer.
1466    pub fn handle_pointer_drag(&mut self, rel_x: f32, rel_y: f32, gutter_width: f32) {
1467        if !self.is_pointer_dragging {
1468            return;
1469        }
1470        let pos = self.position_from_point(rel_x, rel_y, gutter_width);
1471        let anchor = self.cursors.primary().anchor;
1472        self.cursors.set_single(anchor);
1473        self.cursors.all_mut()[0] = Selection::range(anchor, pos);
1474    }
1475
1476    /// Ends a pointer drag gesture.
1477    pub fn handle_pointer_up(&mut self) {
1478        self.is_pointer_dragging = false;
1479    }
1480
1481    /// Handles wheel scrolling over the editor viewport.
1482    pub fn handle_wheel(&mut self, delta_y: f32) {
1483        self.scroll_by(delta_y);
1484    }
1485
1486    /// Handles click or drag inside the Canvas2D minimap to jump/scrub `scroll_top`.
1487    pub fn handle_minimap_pointer(
1488        &mut self,
1489        pointer_y: f32,
1490        minimap_height: f32,
1491        config: &MinimapConfig,
1492    ) {
1493        let target = minimap_y_to_scroll_top(
1494            pointer_y,
1495            minimap_height,
1496            self.visible_logical_lines().len().max(1),
1497            self.viewport_height,
1498            self.line_height,
1499            config,
1500        );
1501        self.set_scroll_top(target);
1502    }
1503
1504    /// Handles a W3C-compatible Strata [`Event`] keydown with full Monaco keybindings.
1505    /// Returns `true` if the event was handled and mutated editor state.
1506    pub fn handle_key_event(&mut self, e: &Event) -> bool {
1507        let cmd = e.ctrl_key || e.meta_key;
1508        let key = e.key.as_str();
1509
1510        if cmd {
1511            match key {
1512                "f" | "F" => {
1513                    self.open_find();
1514                    return true;
1515                }
1516                "h" | "H" => {
1517                    self.open_replace();
1518                    return true;
1519                }
1520                "a" | "A" => {
1521                    self.select_all();
1522                    return true;
1523                }
1524                "z" | "Z" => {
1525                    if !self.read_only {
1526                        if e.shift_key {
1527                            self.redo();
1528                        } else {
1529                            self.undo();
1530                        }
1531                        self.ensure_cursor_visible();
1532                    }
1533                    return true;
1534                }
1535                "y" | "Y" => {
1536                    if !self.read_only {
1537                        self.redo();
1538                        self.ensure_cursor_visible();
1539                    }
1540                    return true;
1541                }
1542                "/" => {
1543                    self.toggle_line_comment();
1544                    return true;
1545                }
1546                "[" if e.shift_key => {
1547                    let line = self.cursors.primary().focus.line;
1548                    self.toggle_fold_at(line);
1549                    return true;
1550                }
1551                "]" if e.shift_key => {
1552                    let line = self.cursors.primary().focus.line;
1553                    if self.is_folded(line) {
1554                        self.toggle_fold(line);
1555                    }
1556                    return true;
1557                }
1558                "ArrowLeft" => {
1559                    self.move_word_left(e.shift_key);
1560                    self.ensure_cursor_visible();
1561                    return true;
1562                }
1563                "ArrowRight" => {
1564                    self.move_word_right(e.shift_key);
1565                    self.ensure_cursor_visible();
1566                    return true;
1567                }
1568                "Home" => {
1569                    let anchor = if e.shift_key {
1570                        self.cursors.primary().anchor
1571                    } else {
1572                        Position::ZERO
1573                    };
1574                    self.cursors.set_single(Position::ZERO);
1575                    self.cursors.all_mut()[0] = Selection::range(anchor, Position::ZERO);
1576                    self.ensure_cursor_visible();
1577                    return true;
1578                }
1579                "End" => {
1580                    let last_line = self.buffer.line_count().saturating_sub(1);
1581                    let end = Position::new(last_line, self.buffer.line_len(last_line));
1582                    let anchor = if e.shift_key {
1583                        self.cursors.primary().anchor
1584                    } else {
1585                        end
1586                    };
1587                    self.cursors.set_single(end);
1588                    self.cursors.all_mut()[0] = Selection::range(anchor, end);
1589                    self.ensure_cursor_visible();
1590                    return true;
1591                }
1592                _ => return false,
1593            }
1594        }
1595
1596        match key {
1597            "Escape" => {
1598                if self.search.is_open {
1599                    self.close_find();
1600                    return true;
1601                }
1602                if self.cursors.count() > 1 {
1603                    let p = self.cursors.primary().focus;
1604                    self.cursors.set_single(p);
1605                    return true;
1606                }
1607                false
1608            }
1609            "ArrowLeft" => {
1610                self.move_left(e.shift_key);
1611                self.ensure_cursor_visible();
1612                true
1613            }
1614            "ArrowRight" => {
1615                self.move_right(e.shift_key);
1616                self.ensure_cursor_visible();
1617                true
1618            }
1619            "ArrowUp" => {
1620                self.move_up(e.shift_key);
1621                self.ensure_cursor_visible();
1622                true
1623            }
1624            "ArrowDown" => {
1625                self.move_down(e.shift_key);
1626                self.ensure_cursor_visible();
1627                true
1628            }
1629            "Home" => {
1630                self.move_to_line_start(e.shift_key);
1631                self.ensure_cursor_visible();
1632                true
1633            }
1634            "End" => {
1635                self.move_to_line_end(e.shift_key);
1636                self.ensure_cursor_visible();
1637                true
1638            }
1639            "PageUp" => {
1640                self.page_up(e.shift_key);
1641                true
1642            }
1643            "PageDown" => {
1644                self.page_down(e.shift_key);
1645                true
1646            }
1647            "Enter" => {
1648                if !self.read_only {
1649                    self.insert_newline();
1650                    self.ensure_cursor_visible();
1651                }
1652                true
1653            }
1654            "Backspace" => {
1655                if !self.read_only {
1656                    self.delete_backwards();
1657                    self.ensure_cursor_visible();
1658                }
1659                true
1660            }
1661            "Delete" => {
1662                if !self.read_only {
1663                    self.delete_forward();
1664                    self.ensure_cursor_visible();
1665                }
1666                true
1667            }
1668            "Tab" => {
1669                if !self.read_only {
1670                    if e.shift_key {
1671                        self.outdent_selection();
1672                    } else {
1673                        self.indent_selection();
1674                    }
1675                }
1676                true
1677            }
1678            other if !e.alt_key && other.chars().count() == 1 => {
1679                if let Some(ch) = other.chars().next() {
1680                    if !ch.is_control() {
1681                        if !self.read_only {
1682                            self.insert_char(ch);
1683                            self.ensure_cursor_visible();
1684                        }
1685                        return true;
1686                    }
1687                }
1688                false
1689            }
1690            _ => false,
1691        }
1692    }
1693
1694    /// Renders a complete code editor view blueprint with default styling.
1695    pub fn render(&self) -> NodeBlueprint {
1696        self.render_blueprint("")
1697    }
1698
1699    /// Renders a complete code editor view blueprint with line numbering gutter and syntax tokens.
1700    pub fn render_blueprint(&self, class_style: &str) -> NodeBlueprint {
1701        if self.buffer.line_count() > 100 {
1702            return self.render_virtualized(0.0, 800.0, 24.0, class_style);
1703        }
1704
1705        let mut row_nodes = Vec::new();
1706
1707        let visible_lines = self.buffer.slice_lines(0, self.buffer.line_count());
1708        let active_line = self.cursors.primary().focus.line;
1709
1710        for (l_idx, line_str) in visible_lines {
1711            let is_active = l_idx == active_line;
1712
1713            let row_class = if is_active {
1714                "flex items-center font-mono text-sm leading-6 bg-slate-800/40 hover:bg-slate-800/60"
1715            } else {
1716                "flex items-center font-mono text-sm leading-6 hover:bg-slate-800/30"
1717            };
1718
1719            let visual_sublines = if let Some(cols) = self.wrap_column {
1720                crate::soft_wrap::wrap_logical_line(line_str, l_idx, cols, true)
1721            } else {
1722                vec![crate::soft_wrap::VisualLine {
1723                    logical_line: l_idx,
1724                    visual_subline: 0,
1725                    text: line_str.to_string(),
1726                    char_start: 0,
1727                    char_end: line_str.chars().count(),
1728                    is_continuation: false,
1729                }]
1730            };
1731
1732            for vline in visual_sublines {
1733                let gutter_text = if vline.is_continuation {
1734                    "↳".to_string()
1735                } else {
1736                    (l_idx + 1).to_string()
1737                };
1738
1739                let gutter_node = NodeBlueprint::element(
1740                    Tag::Span,
1741                    vec![
1742                        "w-12 text-right pr-4 select-none text-slate-500 font-mono text-xs"
1743                            .to_string(),
1744                    ],
1745                    Vec::new(),
1746                    vec![NodeBlueprint::text(gutter_text)],
1747                );
1748
1749                let tokens = self.highlighter.highlight_line_ast(l_idx, &vline.text);
1750                let line_token_nodes = Self::build_token_nodes(&vline.text, tokens);
1751
1752                let code_node = NodeBlueprint::element(
1753                    Tag::Span,
1754                    vec!["flex-1 pl-2 whitespace-pre".to_string()],
1755                    Vec::new(),
1756                    line_token_nodes,
1757                );
1758
1759                row_nodes.push(NodeBlueprint::element(
1760                    Tag::Div,
1761                    vec![row_class.to_string()],
1762                    Vec::new(),
1763                    vec![gutter_node, code_node],
1764                ));
1765            }
1766        }
1767
1768        let container_class = format!(
1769            "bg-slate-950 text-slate-200 border border-slate-800 rounded-lg p-4 font-mono overflow-x-auto {}",
1770            class_style
1771        );
1772
1773        NodeBlueprint::element(Tag::Div, vec![container_class], Vec::new(), row_nodes)
1774    }
1775
1776    /// Maps a semantic [`TokenType`] to a Tailwind utility class string.
1777    pub fn token_type_class(token_type: TokenType) -> &'static str {
1778        match token_type {
1779            TokenType::Keyword => "text-purple-400 font-semibold",
1780            TokenType::ControlFlow => "text-fuchsia-400 font-semibold",
1781            TokenType::Type => "text-amber-400 font-medium",
1782            TokenType::Function => "text-blue-400",
1783            TokenType::Macro => "text-indigo-300 font-medium",
1784            TokenType::Identifier => "text-slate-200",
1785            TokenType::Parameter => "text-orange-200",
1786            TokenType::Property => "text-sky-300",
1787            TokenType::String => "text-emerald-400",
1788            TokenType::StringEscape => "text-teal-300 font-semibold",
1789            TokenType::Number => "text-orange-400",
1790            TokenType::Boolean => "text-amber-300 font-semibold",
1791            TokenType::Comment => "text-slate-500 italic",
1792            TokenType::DocComment => "text-slate-400 italic",
1793            TokenType::Operator => "text-rose-400",
1794            TokenType::Punctuation => "text-slate-400",
1795            TokenType::Tag => "text-cyan-400",
1796            TokenType::Attribute => "text-sky-300",
1797            TokenType::Namespace => "text-amber-200",
1798            TokenType::Heading => "text-cyan-300 font-bold",
1799            TokenType::Link => "text-blue-300 underline",
1800            TokenType::Variable => "text-violet-300",
1801        }
1802    }
1803
1804    fn build_token_nodes(
1805        line_text: &str,
1806        tokens: Vec<crate::syntax::SyntaxToken>,
1807    ) -> Vec<NodeBlueprint> {
1808        let mut line_token_nodes = Vec::new();
1809        if tokens.is_empty() {
1810            line_token_nodes.push(NodeBlueprint::text(line_text));
1811            return line_token_nodes;
1812        }
1813
1814        let mut last_col = 0usize;
1815        for token in tokens {
1816            let start_col = token.start_col.min(line_text.len());
1817            let end_col = token.end_col.min(line_text.len());
1818            if start_col > last_col
1819                && line_text.is_char_boundary(last_col)
1820                && line_text.is_char_boundary(start_col)
1821            {
1822                line_token_nodes.push(NodeBlueprint::text(&line_text[last_col..start_col]));
1823            }
1824
1825            let color_class = Self::token_type_class(token.token_type);
1826            line_token_nodes.push(NodeBlueprint::element(
1827                Tag::Span,
1828                vec![color_class.to_string()],
1829                Vec::new(),
1830                vec![NodeBlueprint::text(token.text)],
1831            ));
1832            last_col = end_col.max(last_col);
1833        }
1834        if last_col < line_text.len() && line_text.is_char_boundary(last_col) {
1835            line_token_nodes.push(NodeBlueprint::text(&line_text[last_col..]));
1836        }
1837        line_token_nodes
1838    }
1839
1840    /// Renders a virtualized viewport slice of the code editor.
1841    ///
1842    /// Only the lines currently visible in the scroll viewport (plus an overscan margin)
1843    /// are laid out and styled into DOM blueprint nodes. Spacer containers at the top
1844    /// and bottom maintain the exact natural scroll height of the entire document.
1845    pub fn render_virtualized(
1846        &self,
1847        scroll_top: f32,
1848        viewport_height: f32,
1849        line_height: f32,
1850        class_style: &str,
1851    ) -> NodeBlueprint {
1852        let total_lines = self.buffer.line_count();
1853        let effective_lh = line_height.max(1.0);
1854
1855        let first_visible = (scroll_top / effective_lh).floor() as usize;
1856        let visible_count = (viewport_height / effective_lh).ceil() as usize;
1857
1858        // Apply a 2-line overscan buffer for smooth scrolling
1859        let start_line = first_visible.saturating_sub(2).min(total_lines);
1860        let end_line = (first_visible + visible_count + 2).min(total_lines);
1861
1862        let top_spacer_height = start_line as f32 * effective_lh;
1863        let bottom_spacer_height = (total_lines.saturating_sub(end_line)) as f32 * effective_lh;
1864
1865        let mut row_nodes = Vec::new();
1866
1867        // Top spacer for virtual scroll height preservation
1868        if top_spacer_height > 0.0 {
1869            row_nodes.push(NodeBlueprint::element(
1870                Tag::Div,
1871                vec![format!(
1872                    "h-[{:.1}px] w-full pointer-events-none",
1873                    top_spacer_height
1874                )],
1875                Vec::new(),
1876                Vec::new(),
1877            ));
1878        }
1879
1880        let visible_lines = self
1881            .buffer
1882            .slice_lines(start_line, end_line.saturating_sub(start_line));
1883        let active_line = self.cursors.primary().focus.line;
1884
1885        for (l_idx, line_str) in visible_lines {
1886            let is_active = l_idx == active_line;
1887
1888            let row_class = if is_active {
1889                "flex items-center font-mono text-sm leading-6 bg-slate-800/40 hover:bg-slate-800/60"
1890            } else {
1891                "flex items-center font-mono text-sm leading-6 hover:bg-slate-800/30"
1892            };
1893
1894            let visual_sublines = if let Some(cols) = self.wrap_column {
1895                crate::soft_wrap::wrap_logical_line(line_str, l_idx, cols, true)
1896            } else {
1897                vec![crate::soft_wrap::VisualLine {
1898                    logical_line: l_idx,
1899                    visual_subline: 0,
1900                    text: line_str.to_string(),
1901                    char_start: 0,
1902                    char_end: line_str.chars().count(),
1903                    is_continuation: false,
1904                }]
1905            };
1906
1907            for vline in visual_sublines {
1908                let gutter_text = if vline.is_continuation {
1909                    "↳".to_string()
1910                } else {
1911                    (l_idx + 1).to_string()
1912                };
1913
1914                let gutter_class = if vline.is_continuation {
1915                    "w-12 text-right pr-4 select-none text-slate-600 font-mono text-xs"
1916                } else {
1917                    "w-12 text-right pr-4 select-none text-slate-500 font-mono text-xs"
1918                };
1919
1920                let gutter_node = NodeBlueprint::element(
1921                    Tag::Span,
1922                    vec![gutter_class.to_string()],
1923                    Vec::new(),
1924                    vec![NodeBlueprint::text(gutter_text)],
1925                );
1926
1927                // Tokens
1928                let tokens = self.highlighter.highlight_line_ast(l_idx, &vline.text);
1929                let line_token_nodes = Self::build_token_nodes(&vline.text, tokens);
1930
1931                let code_node = NodeBlueprint::element(
1932                    Tag::Span,
1933                    vec!["flex-1 pl-2 whitespace-pre".to_string()],
1934                    Vec::new(),
1935                    line_token_nodes,
1936                );
1937
1938                row_nodes.push(NodeBlueprint::element(
1939                    Tag::Div,
1940                    vec![row_class.to_string()],
1941                    Vec::new(),
1942                    vec![gutter_node, code_node],
1943                ));
1944            }
1945        }
1946
1947        // Bottom spacer for virtual scroll height preservation
1948        if bottom_spacer_height > 0.0 {
1949            row_nodes.push(NodeBlueprint::element(
1950                Tag::Div,
1951                vec![format!(
1952                    "h-[{:.1}px] w-full pointer-events-none",
1953                    bottom_spacer_height
1954                )],
1955                Vec::new(),
1956                Vec::new(),
1957            ));
1958        }
1959
1960        let container_class = format!(
1961            "bg-slate-950 text-slate-200 border border-slate-800 rounded-lg p-4 font-mono overflow-y-auto {}",
1962            class_style
1963        );
1964
1965        NodeBlueprint::element(Tag::Div, vec![container_class], Vec::new(), row_nodes)
1966    }
1967}
1968
1969#[inline]
1970fn is_word_char(c: char) -> bool {
1971    c.is_alphanumeric() || c == '_'
1972}