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