Skip to main content

strata_editor/
syntax.rs

1//! Real-time incremental syntax tokenization, Tree-Sitter `InputEdit` AST updates,
2//! multi-line incremental grammar state machines for 10 languages, bracket pair matching,
3//! structural code folding, and syntax diagnostic extraction.
4
5use std::ops::Range;
6
7use serde::{Deserialize, Serialize};
8use tree_sitter::{InputEdit, Node, Parser, Point, Tree};
9
10use crate::buffer::LineBuffer;
11use crate::cursor::Position;
12
13/// Supported language syntaxes for the Monaco-class code editor.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
15pub enum Language {
16    #[default]
17    Rust,
18    Python,
19    Json,
20    Yaml,
21    Toml,
22    XmlSdf,
23    Cpp,
24    JavaScript,
25    TypeScript,
26    Markdown,
27    Shell,
28    Html,
29    PlainText,
30}
31
32impl Language {
33    /// Returns all 10 primary code/config languages supported by `strata-editor`.
34    pub const ALL_LANGUAGES: &'static [Language] = &[
35        Language::Rust,
36        Language::Python,
37        Language::Json,
38        Language::Yaml,
39        Language::Toml,
40        Language::XmlSdf,
41        Language::Cpp,
42        Language::JavaScript,
43        Language::TypeScript,
44        Language::Markdown,
45        Language::Shell,
46    ];
47
48    /// Infers the [`Language`] from a file extension or Markdown fence info string
49    /// (case-insensitive, with or without leading dot).
50    pub fn from_extension(ext: &str) -> Self {
51        let cleaned = ext.trim().trim_start_matches('.').to_ascii_lowercase();
52        match cleaned.as_str() {
53            "rs" | "rust" => Self::Rust,
54            "py" | "pyi" | "pyw" | "python" | "python3" => Self::Python,
55            "json" | "jsonc" | "geojson" => Self::Json,
56            "yml" | "yaml" => Self::Yaml,
57            "toml" => Self::Toml,
58            "xml" | "sdf" | "urdf" | "xacro" | "world" | "launch" | "svg" => Self::XmlSdf,
59            "c" | "h" | "cc" | "cpp" | "c++" | "cxx" | "hh" | "hpp" | "hxx" | "ino" => Self::Cpp,
60            "js" | "mjs" | "cjs" | "jsx" | "javascript" => Self::JavaScript,
61            "ts" | "mts" | "cts" | "tsx" | "typescript" => Self::TypeScript,
62            "md" | "markdown" | "mdx" => Self::Markdown,
63            "sh" | "bash" | "zsh" | "ksh" | "env" | "shell" | "console" => Self::Shell,
64            "html" | "htm" => Self::Html,
65            _ => Self::PlainText,
66        }
67    }
68
69    /// Infers the [`Language`] from a filename or path.
70    pub fn from_filename(path: &str) -> Self {
71        let base = path.rsplit(['/', '\\']).next().unwrap_or(path);
72        match base {
73            "Cargo.lock" | "Cargo.toml" => return Self::Toml,
74            "Makefile" | "Dockerfile" | ".bashrc" | ".zshrc" | ".profile" => return Self::Shell,
75            _ => {}
76        }
77        if let Some((_, ext)) = base.rsplit_once('.') {
78            Self::from_extension(ext)
79        } else {
80            Self::PlainText
81        }
82    }
83
84    /// Human-readable display label for status bars and language pickers.
85    pub const fn display_name(self) -> &'static str {
86        match self {
87            Self::Rust => "Rust",
88            Self::Python => "Python",
89            Self::Json => "JSON",
90            Self::Yaml => "YAML",
91            Self::Toml => "TOML",
92            Self::XmlSdf => "XML / SDF",
93            Self::Cpp => "C / C++",
94            Self::JavaScript => "JavaScript",
95            Self::TypeScript => "TypeScript",
96            Self::Markdown => "Markdown",
97            Self::Shell => "Shell",
98            Self::Html => "HTML",
99            Self::PlainText => "Plain Text",
100        }
101    }
102
103    /// Default single-line comment prefix for `Ctrl+/` toggle-comment actions.
104    pub const fn line_comment_prefix(self) -> Option<&'static str> {
105        match self {
106            Self::Rust | Self::Cpp | Self::JavaScript | Self::TypeScript => Some("//"),
107            Self::Python | Self::Yaml | Self::Toml | Self::Shell => Some("#"),
108            Self::XmlSdf | Self::Html | Self::Markdown | Self::Json | Self::PlainText => None,
109        }
110    }
111
112    /// Whether this language uses a native Tree-Sitter grammar by default.
113    pub const fn has_builtin_tree_sitter(self) -> bool {
114        matches!(self, Self::Rust | Self::JavaScript)
115    }
116}
117
118/// Token classification for semantic syntax highlighting.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
120pub enum TokenType {
121    Keyword,
122    ControlFlow,
123    Type,
124    Function,
125    Macro,
126    Identifier,
127    Parameter,
128    Property,
129    String,
130    StringEscape,
131    Number,
132    Boolean,
133    Comment,
134    DocComment,
135    Operator,
136    Punctuation,
137    Tag,
138    Attribute,
139    Namespace,
140    Heading,
141    Link,
142    Variable,
143}
144
145/// A highlighted syntax token with UTF-8 byte column span offsets within its line.
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct SyntaxToken {
148    pub token_type: TokenType,
149    pub start_col: usize,
150    pub end_col: usize,
151    pub text: String,
152}
153
154/// A collapsible block of code in the editor gutter.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct FoldRange {
157    pub start_line: usize,
158    pub end_line: usize,
159    pub collapsed: bool,
160}
161
162/// Lightweight structural syntax diagnostic emitted directly by the incremental syntax engine.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct SyntaxDiagnostic {
165    pub start: Position,
166    pub end: Position,
167    pub message: String,
168    pub is_warning: bool,
169}
170
171/// Persistent cross-line lexer state stored per line for O(delta) incremental re-tokenization.
172#[derive(Debug, Clone, PartialEq, Eq, Default)]
173pub enum LineLexState {
174    #[default]
175    Normal,
176    /// Inside `/* ... */` block comment (Rust, C/C++, JS/TS) with nesting depth for Rust.
177    BlockComment { depth: u16, doc: bool },
178    /// Inside `<!-- ... -->` XML/SDF/HTML/Markdown comment.
179    XmlComment,
180    /// Inside `<![CDATA[ ... ]]>` XML/SDF section.
181    XmlCdata,
182    /// Inside Python/TOML triple-quoted string (`"""` or `'''`).
183    TripleString { quote: u8 },
184    /// Inside Rust raw string `r###"..."###`.
185    RustRawString { hashes: u8 },
186    /// Inside Markdown fenced code block with optional embedded language.
187    MarkdownFence {
188        fence_char: u8,
189        fence_len: u8,
190        embedded: Language,
191    },
192    /// Inside Shell heredoc `<<EOF ... EOF`.
193    ShellHeredoc { delimiter: String },
194    /// Inside YAML block scalar (`|` or `>`) indented deeper than `base_indent`.
195    YamlBlockScalar { base_indent: usize },
196}
197
198fn create_parser_for_lang(lang: Language) -> Option<Parser> {
199    let mut parser = Parser::new();
200    match lang {
201        Language::Rust => {
202            parser
203                .set_language(&tree_sitter_rust::LANGUAGE.into())
204                .ok()?;
205            Some(parser)
206        }
207        Language::JavaScript => {
208            parser
209                .set_language(&tree_sitter_javascript::LANGUAGE.into())
210                .ok()?;
211            Some(parser)
212        }
213        _ => None,
214    }
215}
216
217fn classify_tree_sitter_kind(kind: &str, parent_kind: &str, text: &str) -> TokenType {
218    match kind {
219        "line_comment" | "block_comment" | "comment" => {
220            if text.starts_with("///") || text.starts_with("//!") || text.starts_with("/**") {
221                TokenType::DocComment
222            } else {
223                TokenType::Comment
224            }
225        }
226
227        "string_literal"
228        | "raw_string_literal"
229        | "char_literal"
230        | "string"
231        | "template_string"
232        | "string_content"
233        | "string_fragment" => TokenType::String,
234
235        "escape_sequence" => TokenType::StringEscape,
236
237        "integer_literal" | "float_literal" | "number" => TokenType::Number,
238
239        "true" | "false" | "boolean_literal" => TokenType::Boolean,
240
241        "primitive_type" | "type_identifier" | "predefined_type" => TokenType::Type,
242
243        "lifetime" | "label" => TokenType::Namespace,
244
245        "attribute_item" | "inner_attribute_item" | "meta_item" => TokenType::Attribute,
246
247        "identifier"
248            if parent_kind == "macro_invocation" || parent_kind == "macro_definition" =>
249        {
250            TokenType::Macro
251        }
252
253        "identifier"
254            if parent_kind == "call_expression"
255                || parent_kind == "function_item"
256                || parent_kind == "function_declaration"
257                || parent_kind == "function_declarator"
258                || parent_kind == "method_definition" =>
259        {
260            TokenType::Function
261        }
262
263        "identifier" if parent_kind == "parameter" || parent_kind == "formal_parameters" => {
264            TokenType::Parameter
265        }
266
267        "if" | "else" | "match" | "return" | "for" | "in" | "while" | "loop" | "break"
268        | "continue" | "try" | "catch" | "finally" | "switch" | "case" | "throw" | "yield"
269        | "await" => TokenType::ControlFlow,
270
271        "fn" | "let" | "mut" | "pub" | "struct" | "enum" | "impl" | "trait" | "async" | "use"
272        | "mod" | "crate" | "const" | "static" | "type" | "where" | "as" | "ref" | "move"
273        | "unsafe" | "dyn" | "super" | "self" | "Self" | "function" | "var" | "import"
274        | "export" | "default" | "from" | "class" | "interface" | "extends" | "new" | "this"
275        | "typeof" | "instanceof" | "debugger" | "null" | "undefined" => TokenType::Keyword,
276
277        "+" | "-" | "*" | "/" | "%" | "=" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||"
278        | "!" | "&" | "|" | "^" | "<<" | ">>" | "+=" | "-=" | "*=" | "/=" | "%=" | "&=" | "|="
279        | "^=" | "=>" | "->" | "?" | ".." | "..=" => TokenType::Operator,
280
281        "(" | ")" | "[" | "]" | "{" | "}" | ";" | ":" | "::" | "," | "." => TokenType::Punctuation,
282
283        "tag_name" | "jsx_opening_element" | "jsx_closing_element" => TokenType::Tag,
284        "property_identifier" | "field_identifier" | "shorthand_property_identifier" => {
285            TokenType::Property
286        }
287
288        _ => TokenType::Identifier,
289    }
290}
291
292fn snap_char_boundary(s: &str, mut byte_idx: usize) -> usize {
293    byte_idx = byte_idx.min(s.len());
294    while byte_idx > 0 && !s.is_char_boundary(byte_idx) {
295        byte_idx -= 1;
296    }
297    byte_idx
298}
299
300fn collect_leaf_tokens(node: Node, line_idx: usize, out: &mut Vec<SyntaxToken>, line_text: &str) {
301    if node.start_position().row > line_idx || node.end_position().row < line_idx {
302        return;
303    }
304
305    // Keep string / comment literals cohesive rather than splitting quotes from content if no escapes.
306    let kind = node.kind();
307    let is_atomic = matches!(
308        kind,
309        "line_comment" | "block_comment" | "comment" | "raw_string_literal" | "char_literal"
310    );
311
312    if node.child_count() == 0 || is_atomic {
313        let start_pt = node.start_position();
314        let end_pt = node.end_position();
315
316        let raw_start = if start_pt.row == line_idx {
317            start_pt.column
318        } else {
319            0
320        };
321        let raw_end = if end_pt.row == line_idx {
322            end_pt.column
323        } else {
324            line_text.len()
325        };
326
327        let start_col = snap_char_boundary(line_text, raw_start);
328        let end_col = snap_char_boundary(line_text, raw_end);
329
330        if start_col < end_col && start_col < line_text.len() {
331            let text = &line_text[start_col..end_col];
332            if !text.trim().is_empty() {
333                let parent_kind = node.parent().map(|p| p.kind()).unwrap_or("");
334                let token_type = classify_tree_sitter_kind(kind, parent_kind, text);
335                out.push(SyntaxToken {
336                    token_type,
337                    start_col,
338                    end_col,
339                    text: text.to_string(),
340                });
341            }
342        }
343        return;
344    }
345
346    for i in 0..node.child_count() {
347        if let Some(child) = node.child(i) {
348            collect_leaf_tokens(child, line_idx, out, line_text);
349        }
350    }
351}
352
353fn collect_ast_fold_ranges(node: Node, out: &mut Vec<FoldRange>) {
354    let start_row = node.start_position().row;
355    let end_row = node.end_position().row;
356
357    if end_row > start_row {
358        let is_foldable = matches!(
359            node.kind(),
360            "block"
361                | "declaration_list"
362                | "match_block"
363                | "statement_block"
364                | "field_declaration_list"
365                | "enum_variant_list"
366                | "object"
367                | "array"
368                | "function_item"
369                | "impl_item"
370                | "struct_item"
371                | "enum_item"
372                | "trait_item"
373                | "mod_item"
374                | "function_declaration"
375                | "class_declaration"
376                | "class_body"
377                | "switch_body"
378                | "block_comment"
379        );
380
381        if is_foldable {
382            out.push(FoldRange {
383                start_line: start_row,
384                end_line: end_row,
385                collapsed: false,
386            });
387        }
388    }
389
390    for i in 0..node.child_count() {
391        if let Some(child) = node.child(i) {
392            collect_ast_fold_ranges(child, out);
393        }
394    }
395}
396
397fn collect_tree_sitter_errors(node: Node, out: &mut Vec<SyntaxDiagnostic>) {
398    if node.is_error() || node.is_missing() {
399        let s = node.start_position();
400        let e = node.end_position();
401        let msg = if node.is_missing() {
402            format!("Missing expected syntax token `{}`", node.kind())
403        } else {
404            "Syntax error".to_string()
405        };
406        out.push(SyntaxDiagnostic {
407            start: Position::new(s.row, s.column),
408            end: Position::new(e.row, e.column.max(s.column + 1)),
409            message: msg,
410            is_warning: false,
411        });
412        return;
413    }
414    if !node.has_error() {
415        return;
416    }
417    for i in 0..node.child_count() {
418        if let Some(child) = node.child(i) {
419            collect_tree_sitter_errors(child, out);
420        }
421    }
422}
423
424/// Syntax analysis engine providing real-time Tree-Sitter `InputEdit` incremental parsing,
425/// 10-language incremental line-state tokenization, structural code folding, and diagnostics.
426pub struct SyntaxHighlighter {
427    parser: Option<Parser>,
428    custom_ts_language: Option<tree_sitter::Language>,
429    tree: Option<Tree>,
430    language: Language,
431    /// Multi-line lexer state entering line `i` (length == `line_count`).
432    line_entry_states: Vec<LineLexState>,
433    /// Cached syntax tokens per line for O(1) 120 FPS viewport rendering.
434    line_token_cache: Vec<Option<Vec<SyntaxToken>>>,
435    /// Count of incremental `tree.edit(&InputEdit)` + reparse cycles executed.
436    incremental_edit_count: u64,
437    /// Last changed line ranges reported by Tree-Sitter or incremental state propagation.
438    last_changed_lines: Vec<Range<usize>>,
439}
440
441impl std::fmt::Debug for SyntaxHighlighter {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        f.debug_struct("SyntaxHighlighter")
444            .field("has_parser", &self.parser.is_some())
445            .field("has_tree", &self.tree.is_some())
446            .field("language", &self.language)
447            .field("cached_lines", &self.line_token_cache.len())
448            .field("incremental_edit_count", &self.incremental_edit_count)
449            .finish()
450    }
451}
452
453impl Clone for SyntaxHighlighter {
454    fn clone(&self) -> Self {
455        let mut cloned = Self::with_language(self.language);
456        if let Some(ref custom) = self.custom_ts_language {
457            cloned.register_tree_sitter_language(custom.clone());
458        }
459        cloned.tree = self.tree.clone();
460        cloned.line_entry_states = self.line_entry_states.clone();
461        cloned.line_token_cache = self.line_token_cache.clone();
462        cloned.incremental_edit_count = self.incremental_edit_count;
463        cloned.last_changed_lines = self.last_changed_lines.clone();
464        cloned
465    }
466}
467
468impl Default for SyntaxHighlighter {
469    fn default() -> Self {
470        Self::new()
471    }
472}
473
474impl SyntaxHighlighter {
475    pub fn new() -> Self {
476        Self::with_language(Language::Rust)
477    }
478
479    pub fn with_language(lang: Language) -> Self {
480        let parser = create_parser_for_lang(lang);
481        Self {
482            parser,
483            custom_ts_language: None,
484            tree: None,
485            language: lang,
486            line_entry_states: Vec::new(),
487            line_token_cache: Vec::new(),
488            incremental_edit_count: 0,
489            last_changed_lines: Vec::new(),
490        }
491    }
492
493    /// Registers an external [`tree_sitter::Language`] grammar on this highlighter instance
494    /// (e.g. if an application brings its own `tree-sitter-python` or `tree-sitter-cpp` crate).
495    pub fn register_tree_sitter_language(&mut self, ts_lang: tree_sitter::Language) -> bool {
496        let mut parser = Parser::new();
497        if parser.set_language(&ts_lang).is_ok() {
498            self.parser = Some(parser);
499            self.custom_ts_language = Some(ts_lang);
500            self.tree = None;
501            self.line_token_cache.clear();
502            true
503        } else {
504            false
505        }
506    }
507
508    pub fn set_language(&mut self, lang: Language) {
509        if self.language != lang {
510            self.language = lang;
511            self.custom_ts_language = None;
512            self.parser = create_parser_for_lang(lang);
513            self.tree = None;
514            self.line_entry_states.clear();
515            self.line_token_cache.clear();
516            self.last_changed_lines.clear();
517        }
518    }
519
520    pub fn language(&self) -> Language {
521        self.language
522    }
523
524    /// Number of incremental edits processed via [`Self::edit`] / [`Self::apply_input_edit_and_reparse`].
525    pub fn incremental_edit_count(&self) -> u64 {
526        self.incremental_edit_count
527    }
528
529    /// Returns the line ranges invalidated during the most recent incremental reparse.
530    pub fn last_changed_lines(&self) -> &[Range<usize>] {
531        &self.last_changed_lines
532    }
533
534    /// Accesses the active Tree-Sitter AST tree, if parsed.
535    pub fn tree(&self) -> Option<&Tree> {
536        self.tree.as_ref()
537    }
538
539    /// Parses a complete source text into a Tree-Sitter AST and initializes line lexer states.
540    pub fn parse(&mut self, source: &str) {
541        if let Some(ref mut parser) = self.parser {
542            self.tree = parser.parse(source, None);
543        } else {
544            self.tree = None;
545        }
546        let buf = LineBuffer::from_str(source);
547        self.rebuild_line_states(&buf);
548    }
549
550    /// Parses a [`LineBuffer`] directly via zero-copy rope slices (no full-document `String` copy).
551    pub fn parse_buffer(&mut self, buffer: &LineBuffer) {
552        self.tree = self.parse_rope_tree(buffer, None);
553        self.rebuild_line_states(buffer);
554    }
555
556    /// Internal zero-copy Tree-Sitter rope callback parser using `Parser::parse_with_options`.
557    fn parse_rope_tree(&mut self, buffer: &LineBuffer, old_tree: Option<&Tree>) -> Option<Tree> {
558        let parser = self.parser.as_mut()?;
559        let line_count = buffer.line_count();
560        let mut read_cb = |_byte_offset: usize, position: Point| -> &[u8] {
561            let row = position.row;
562            let col = position.column;
563            if row >= line_count {
564                return b"";
565            }
566            if let Some(line) = buffer.line(row) {
567                if col < line.len() {
568                    return &line.as_bytes()[col..];
569                } else if col == line.len() && row + 1 < line_count {
570                    return b"\n";
571                }
572            }
573            b""
574        };
575        parser.parse_with_options(&mut read_cb, old_tree, None)
576    }
577
578    /// Recomputes `line_entry_states` across the entire buffer and resets the per-line token cache.
579    fn rebuild_line_states(&mut self, buffer: &LineBuffer) {
580        let n = buffer.line_count();
581        self.line_entry_states.clear();
582        self.line_entry_states.reserve(n);
583        self.line_token_cache.clear();
584        self.line_token_cache.resize(n, None);
585
586        let mut cur_state = LineLexState::Normal;
587        for row in 0..n {
588            self.line_entry_states.push(cur_state.clone());
589            if let Some(line) = buffer.line(row) {
590                let (_, next_state) = Self::scan_line_with_state(line, self.language, &cur_state);
591                cur_state = next_state;
592            }
593        }
594        self.last_changed_lines.clear();
595        self.last_changed_lines.push(0..n);
596    }
597
598    /// Informs the Tree-Sitter AST and incremental line-state cache of an edit before re-parsing.
599    pub fn edit(&mut self, edit: &InputEdit) {
600        if let Some(ref mut tree) = self.tree {
601            tree.edit(edit);
602        }
603        self.apply_line_cache_splice(edit);
604        self.incremental_edit_count = self.incremental_edit_count.saturating_add(1);
605    }
606
607    fn apply_line_cache_splice(&mut self, edit: &InputEdit) {
608        if self.line_entry_states.is_empty() {
609            return;
610        }
611        let start_row = edit.start_position.row;
612        let old_end_row = edit.old_end_position.row;
613        let new_end_row = edit.new_end_position.row;
614
615        if old_end_row > new_end_row {
616            let remove_count = old_end_row - new_end_row;
617            let del_start = (new_end_row + 1).min(self.line_entry_states.len());
618            let del_end = (del_start + remove_count).min(self.line_entry_states.len());
619            if del_start < del_end {
620                self.line_entry_states.drain(del_start..del_end);
621                self.line_token_cache.drain(del_start..del_end);
622            }
623        } else if new_end_row > old_end_row {
624            let insert_count = new_end_row - old_end_row;
625            let ins_at = (old_end_row + 1).min(self.line_entry_states.len());
626            let fill_state = self
627                .line_entry_states
628                .get(start_row)
629                .cloned()
630                .unwrap_or_default();
631            self.line_entry_states
632                .splice(ins_at..ins_at, std::iter::repeat_n(fill_state, insert_count));
633            self.line_token_cache
634                .splice(ins_at..ins_at, std::iter::repeat_n(None, insert_count));
635        }
636
637        // Invalidate token cache across the directly edited line span.
638        let inv_start = start_row.min(self.line_token_cache.len());
639        let inv_end = (new_end_row + 1).min(self.line_token_cache.len());
640        for slot in &mut self.line_token_cache[inv_start..inv_end] {
641            *slot = None;
642        }
643    }
644
645    /// Re-parses the document incrementally from a full `&str` using the edited previous AST.
646    pub fn parse_incremental(&mut self, source: &str) {
647        let old_tree = self.tree.take();
648        if let Some(ref mut parser) = self.parser {
649            let new_tree = parser.parse(source, old_tree.as_ref());
650            if let (Some(ref old_t), Some(ref new_t)) = (&old_tree, &new_tree) {
651                self.last_changed_lines = old_t
652                    .changed_ranges(new_t)
653                    .map(|r| r.start_point.row..r.end_point.row.saturating_add(1))
654                    .collect();
655            }
656            self.tree = new_tree;
657        }
658        let buf = LineBuffer::from_str(source);
659        self.propagate_states_from(0, buf.line_count(), &buf);
660    }
661
662    /// Re-parses the [`LineBuffer`] incrementally via zero-copy rope slices after one or more
663    /// [`Self::edit`] calls, invalidating ONLY the lines whose AST or multi-line lexer state changed.
664    pub fn reparse_incremental_buffer(
665        &mut self,
666        buffer: &LineBuffer,
667        dirty_start_row: usize,
668        dirty_end_row: usize,
669    ) -> &[Range<usize>] {
670        let old_tree = self.tree.take();
671        let new_tree = self.parse_rope_tree(buffer, old_tree.as_ref());
672        let mut changed_ranges: Vec<Range<usize>> = Vec::new();
673        let total_lines = buffer.line_count();
674
675        if let (Some(ref old_t), Some(ref new_t)) = (&old_tree, &new_tree) {
676            for r in old_t.changed_ranges(new_t) {
677                let s = r.start_point.row.min(total_lines);
678                let e = (r.end_point.row + 1).min(total_lines);
679                if s < e {
680                    changed_ranges.push(s..e);
681                }
682            }
683        }
684        self.tree = new_tree;
685
686        if self.line_entry_states.len() != total_lines {
687            self.line_entry_states.resize(total_lines, LineLexState::Normal);
688            self.line_token_cache.resize(total_lines, None);
689        }
690
691        let prop_end = self.propagate_states_from(dirty_start_row, dirty_end_row, buffer);
692        let base_s = dirty_start_row.min(total_lines);
693        let base_e = prop_end.min(total_lines);
694        if base_s < base_e {
695            changed_ranges.push(base_s..base_e);
696        }
697
698        // Invalidate token cache for every changed range.
699        for r in &changed_ranges {
700            let s = r.start.min(self.line_token_cache.len());
701            let e = r.end.min(self.line_token_cache.len());
702            for slot in &mut self.line_token_cache[s..e] {
703                *slot = None;
704            }
705        }
706
707        self.last_changed_lines = changed_ranges;
708        &self.last_changed_lines
709    }
710
711    /// Convenience single-edit incremental update: calls `tree.edit(edit)` and reparses via
712    /// zero-copy rope slices in a single call.
713    pub fn apply_input_edit_and_reparse(
714        &mut self,
715        edit: &InputEdit,
716        buffer: &LineBuffer,
717    ) -> &[Range<usize>] {
718        self.edit(edit);
719        self.reparse_incremental_buffer(
720            buffer,
721            edit.start_position.row,
722            edit.new_end_position.row.saturating_add(1),
723        )
724    }
725
726    /// Propagates multi-line lexer state forward from `start_row`, stopping early as soon as
727    /// `row >= min_end_row` and the entry state of `row` matches the previously cached state.
728    fn propagate_states_from(
729        &mut self,
730        start_row: usize,
731        min_end_row: usize,
732        buffer: &LineBuffer,
733    ) -> usize {
734        let total = buffer.line_count();
735        if total == 0 {
736            self.line_entry_states.clear();
737            self.line_token_cache.clear();
738            return 0;
739        }
740        if self.line_entry_states.len() != total {
741            self.rebuild_line_states(buffer);
742            return total;
743        }
744
745        let mut row = start_row.min(total - 1);
746        let mut cur_state = self.line_entry_states[row].clone();
747        let stop_floor = min_end_row.min(total);
748
749        while row < total {
750            self.line_entry_states[row] = cur_state.clone();
751            self.line_token_cache[row] = None;
752            let next_state = if let Some(line) = buffer.line(row) {
753                Self::scan_line_with_state(line, self.language, &cur_state).1
754            } else {
755                LineLexState::Normal
756            };
757            row += 1;
758            if row < total {
759                if row >= stop_floor && self.line_entry_states[row] == next_state {
760                    break;
761                }
762                cur_state = next_state;
763            }
764        }
765        row
766    }
767
768    /// Returns cached syntax tokens for `line_idx`, computing and memoizing them lazily on cache miss.
769    pub fn tokens_for_line_cached(&mut self, line_idx: usize, buffer: &LineBuffer) -> &[SyntaxToken] {
770        let total = buffer.line_count();
771        if line_idx >= total {
772            return &[];
773        }
774        if self.line_token_cache.len() != total {
775            self.rebuild_line_states(buffer);
776        }
777        if self.line_token_cache[line_idx].is_none() {
778            let line = buffer.line(line_idx).unwrap_or("");
779            let tokens = self.highlight_line_ast(line_idx, line);
780            self.line_token_cache[line_idx] = Some(tokens);
781        }
782        self.line_token_cache[line_idx].as_deref().unwrap_or(&[])
783    }
784
785    /// Tokenizes a single line statelessly (backwards-compatible helper).
786    pub fn highlight_line(&self, line: &str, lang: Language) -> Vec<SyntaxToken> {
787        if line.is_empty() {
788            return Vec::new();
789        }
790        Self::tokenize_line_lexical(line, lang)
791    }
792
793    /// Extracts syntax tokens for a line using the active Tree-Sitter AST when present,
794    /// falling back to the incremental multi-line state tokenizer for non-Tree-Sitter languages.
795    pub fn highlight_line_ast(&self, line_idx: usize, line: &str) -> Vec<SyntaxToken> {
796        if line.is_empty() {
797            return Vec::new();
798        }
799
800        if let Some(ref tree) = self.tree {
801            let mut tokens = Vec::new();
802            collect_leaf_tokens(tree.root_node(), line_idx, &mut tokens, line);
803            if !tokens.is_empty() {
804                tokens.sort_by_key(|t| t.start_col);
805                return tokens;
806            }
807        }
808
809        let entry_state = self
810            .line_entry_states
811            .get(line_idx)
812            .cloned()
813            .unwrap_or(LineLexState::Normal);
814        Self::scan_line_with_state(line, self.language, &entry_state).0
815    }
816
817    /// Stateless single-line tokenizer returning tokens with UTF-8 byte offsets.
818    pub fn tokenize_line_lexical(line: &str, lang: Language) -> Vec<SyntaxToken> {
819        if line.is_empty() {
820            return Vec::new();
821        }
822        Self::scan_line_with_state(line, lang, &LineLexState::Normal).0
823    }
824
825    /// Core 10-language incremental line scanner returning `(tokens_with_byte_offsets, exit_state)`.
826    pub fn scan_line_with_state(
827        line: &str,
828        lang: Language,
829        entry_state: &LineLexState,
830    ) -> (Vec<SyntaxToken>, LineLexState) {
831        match lang {
832            Language::Json => (Self::scan_json_line(line), LineLexState::Normal),
833            Language::Yaml => Self::scan_yaml_line(line, entry_state),
834            Language::Toml => Self::scan_toml_line(line, entry_state),
835            Language::XmlSdf | Language::Html => Self::scan_xml_line(line, entry_state),
836            Language::Markdown => Self::scan_markdown_line(line, entry_state),
837            Language::Shell => Self::scan_shell_line(line, entry_state),
838            Language::Python => Self::scan_python_line(line, entry_state),
839            Language::Cpp => Self::scan_c_like_line(line, lang, entry_state),
840            Language::Rust | Language::JavaScript | Language::TypeScript => {
841                Self::scan_c_like_line(line, lang, entry_state)
842            }
843            Language::PlainText => (Vec::new(), LineLexState::Normal),
844        }
845    }
846
847    fn scan_json_line(line: &str) -> Vec<SyntaxToken> {
848        let mut tokens = Vec::new();
849        let bytes = line.as_bytes();
850        let len = bytes.len();
851        let mut i = 0;
852
853        while i < len {
854            let b = bytes[i];
855            if b.is_ascii_whitespace() {
856                i += 1;
857                continue;
858            }
859            // JSONC comments
860            if b == b'/' && i + 1 < len && bytes[i + 1] == b'/' {
861                tokens.push(SyntaxToken {
862                    token_type: TokenType::Comment,
863                    start_col: i,
864                    end_col: len,
865                    text: line[i..len].to_string(),
866                });
867                break;
868            }
869            // Strings (distinguish object property keys followed by `:`)
870            if b == b'"' {
871                let start = i;
872                i += 1;
873                while i < len {
874                    if bytes[i] == b'\\' && i + 1 < len {
875                        i += 2;
876                    } else if bytes[i] == b'"' {
877                        i += 1;
878                        break;
879                    } else {
880                        i += 1;
881                    }
882                }
883                let mut look = i;
884                while look < len && bytes[look].is_ascii_whitespace() {
885                    look += 1;
886                }
887                let tt = if look < len && bytes[look] == b':' {
888                    TokenType::Property
889                } else {
890                    TokenType::String
891                };
892                tokens.push(SyntaxToken {
893                    token_type: tt,
894                    start_col: start,
895                    end_col: i,
896                    text: line[start..i].to_string(),
897                });
898                continue;
899            }
900            // Numbers (including negative and scientific notation)
901            if b.is_ascii_digit() || (b == b'-' && i + 1 < len && bytes[i + 1].is_ascii_digit()) {
902                let start = i;
903                i += 1;
904                while i < len
905                    && (bytes[i].is_ascii_digit()
906                        || matches!(bytes[i], b'.' | b'e' | b'E' | b'+' | b'-'))
907                {
908                    i += 1;
909                }
910                tokens.push(SyntaxToken {
911                    token_type: TokenType::Number,
912                    start_col: start,
913                    end_col: i,
914                    text: line[start..i].to_string(),
915                });
916                continue;
917            }
918            // Booleans & null
919            if b.is_ascii_alphabetic() {
920                let start = i;
921                while i < len && bytes[i].is_ascii_alphanumeric() {
922                    i += 1;
923                }
924                let word = &line[start..i];
925                let tt = match word {
926                    "true" | "false" => TokenType::Boolean,
927                    "null" => TokenType::Keyword,
928                    _ => TokenType::Identifier,
929                };
930                tokens.push(SyntaxToken {
931                    token_type: tt,
932                    start_col: start,
933                    end_col: i,
934                    text: word.to_string(),
935                });
936                continue;
937            }
938            let ch_len = line[i..].chars().next().map_or(1, char::len_utf8);
939            tokens.push(SyntaxToken {
940                token_type: TokenType::Punctuation,
941                start_col: i,
942                end_col: i + ch_len,
943                text: line[i..i + ch_len].to_string(),
944            });
945            i += ch_len;
946        }
947        tokens
948    }
949
950    fn scan_yaml_line(line: &str, entry_state: &LineLexState) -> (Vec<SyntaxToken>, LineLexState) {
951        let indent = line.bytes().take_while(|&b| b == b' ').count();
952        let trimmed = line.trim();
953
954        if let LineLexState::YamlBlockScalar { base_indent } = *entry_state {
955            if trimmed.is_empty() || indent > base_indent {
956                let mut toks = Vec::new();
957                if !trimmed.is_empty() {
958                    toks.push(SyntaxToken {
959                        token_type: TokenType::String,
960                        start_col: indent,
961                        end_col: line.len(),
962                        text: line[indent..].to_string(),
963                    });
964                }
965                return (toks, LineLexState::YamlBlockScalar { base_indent });
966            }
967        }
968
969        let mut tokens = Vec::new();
970        if trimmed.is_empty() {
971            return (tokens, LineLexState::Normal);
972        }
973        if trimmed == "---" || trimmed == "..." {
974            tokens.push(SyntaxToken {
975                token_type: TokenType::Keyword,
976                start_col: indent,
977                end_col: indent + trimmed.len(),
978                text: trimmed.to_string(),
979            });
980            return (tokens, LineLexState::Normal);
981        }
982        if trimmed.starts_with('#') {
983            tokens.push(SyntaxToken {
984                token_type: TokenType::Comment,
985                start_col: indent,
986                end_col: line.len(),
987                text: line[indent..].to_string(),
988            });
989            return (tokens, LineLexState::Normal);
990        }
991
992        let mut pos = indent;
993        let bytes = line.as_bytes();
994        // Leading list dash `- `
995        if bytes.get(pos) == Some(&b'-')
996            && bytes.get(pos + 1).is_none_or(|b| b.is_ascii_whitespace())
997        {
998            tokens.push(SyntaxToken {
999                token_type: TokenType::Punctuation,
1000                start_col: pos,
1001                end_col: pos + 1,
1002                text: "-".to_string(),
1003            });
1004            pos += 1;
1005            while pos < line.len() && bytes[pos].is_ascii_whitespace() {
1006                pos += 1;
1007            }
1008        }
1009
1010        // Check for `key:` pair
1011        let mut exit_state = LineLexState::Normal;
1012        if let Some(colon_rel) = find_yaml_mapping_colon(&line[pos..]) {
1013            let colon_abs = pos + colon_rel;
1014            let key_str = line[pos..colon_abs].trim_end();
1015            if !key_str.is_empty() {
1016                tokens.push(SyntaxToken {
1017                    token_type: TokenType::Property,
1018                    start_col: pos,
1019                    end_col: pos + key_str.len(),
1020                    text: key_str.to_string(),
1021                });
1022            }
1023            tokens.push(SyntaxToken {
1024                token_type: TokenType::Punctuation,
1025                start_col: colon_abs,
1026                end_col: colon_abs + 1,
1027                text: ":".to_string(),
1028            });
1029            pos = colon_abs + 1;
1030        }
1031
1032        // Scan YAML value portion
1033        let mut i = pos;
1034        while i < line.len() {
1035            let b = bytes[i];
1036            if b.is_ascii_whitespace() {
1037                i += 1;
1038                continue;
1039            }
1040            if b == b'#' {
1041                tokens.push(SyntaxToken {
1042                    token_type: TokenType::Comment,
1043                    start_col: i,
1044                    end_col: line.len(),
1045                    text: line[i..].to_string(),
1046                });
1047                break;
1048            }
1049            if b == b'|' || b == b'>' {
1050                let start = i;
1051                i += 1;
1052                while i < line.len() && matches!(bytes[i], b'-' | b'+' | b'0'..=b'9') {
1053                    i += 1;
1054                }
1055                tokens.push(SyntaxToken {
1056                    token_type: TokenType::Operator,
1057                    start_col: start,
1058                    end_col: i,
1059                    text: line[start..i].to_string(),
1060                });
1061                exit_state = LineLexState::YamlBlockScalar {
1062                    base_indent: indent,
1063                };
1064                continue;
1065            }
1066            if b == b'&' || b == b'*' {
1067                let start = i;
1068                i += 1;
1069                while i < line.len() && !bytes[i].is_ascii_whitespace() {
1070                    i += 1;
1071                }
1072                tokens.push(SyntaxToken {
1073                    token_type: TokenType::Namespace,
1074                    start_col: start,
1075                    end_col: i,
1076                    text: line[start..i].to_string(),
1077                });
1078                continue;
1079            }
1080            if b == b'!' {
1081                let start = i;
1082                while i < line.len() && !bytes[i].is_ascii_whitespace() {
1083                    i += 1;
1084                }
1085                tokens.push(SyntaxToken {
1086                    token_type: TokenType::Type,
1087                    start_col: start,
1088                    end_col: i,
1089                    text: line[start..i].to_string(),
1090                });
1091                continue;
1092            }
1093            if b == b'"' || b == b'\'' {
1094                let quote = b;
1095                let start = i;
1096                i += 1;
1097                while i < line.len() {
1098                    if quote == b'"' && bytes[i] == b'\\' && i + 1 < line.len() {
1099                        i += 2;
1100                    } else if bytes[i] == quote {
1101                        i += 1;
1102                        break;
1103                    } else {
1104                        i += 1;
1105                    }
1106                }
1107                tokens.push(SyntaxToken {
1108                    token_type: TokenType::String,
1109                    start_col: start,
1110                    end_col: i,
1111                    text: line[start..i].to_string(),
1112                });
1113                continue;
1114            }
1115            if matches!(b, b'[' | b']' | b'{' | b'}' | b',') {
1116                tokens.push(SyntaxToken {
1117                    token_type: TokenType::Punctuation,
1118                    start_col: i,
1119                    end_col: i + 1,
1120                    text: line[i..i + 1].to_string(),
1121                });
1122                i += 1;
1123                continue;
1124            }
1125            // Scalar word / number / bool
1126            let start = i;
1127            while i < line.len()
1128                && !matches!(bytes[i], b',' | b']' | b'}' | b'#')
1129                && !bytes[i].is_ascii_whitespace()
1130            {
1131                i += 1;
1132            }
1133            let word = &line[start..i];
1134            let tt = match word {
1135                "true" | "false" | "yes" | "no" | "on" | "off" => TokenType::Boolean,
1136                "null" | "~" => TokenType::Keyword,
1137                _ if is_numeric_literal(word) => TokenType::Number,
1138                _ => TokenType::String,
1139            };
1140            tokens.push(SyntaxToken {
1141                token_type: tt,
1142                start_col: start,
1143                end_col: i,
1144                text: word.to_string(),
1145            });
1146        }
1147
1148        (tokens, exit_state)
1149    }
1150
1151    fn scan_toml_line(line: &str, entry_state: &LineLexState) -> (Vec<SyntaxToken>, LineLexState) {
1152        let mut tokens = Vec::new();
1153        let bytes = line.as_bytes();
1154        let len = bytes.len();
1155        let mut i = 0;
1156
1157        if let LineLexState::TripleString { quote } = *entry_state {
1158            let delim = [quote, quote, quote];
1159            if let Some(pos) = find_bytes(&bytes[i..], &delim) {
1160                let end = i + pos + 3;
1161                tokens.push(SyntaxToken {
1162                    token_type: TokenType::String,
1163                    start_col: 0,
1164                    end_col: end,
1165                    text: line[0..end].to_string(),
1166                });
1167                i = end;
1168            } else {
1169                if !line.is_empty() {
1170                    tokens.push(SyntaxToken {
1171                        token_type: TokenType::String,
1172                        start_col: 0,
1173                        end_col: len,
1174                        text: line.to_string(),
1175                    });
1176                }
1177                return (tokens, LineLexState::TripleString { quote });
1178            }
1179        }
1180
1181        let trimmed_start = line.bytes().take_while(|b| b.is_ascii_whitespace()).count();
1182        if i == 0 && bytes.get(trimmed_start) == Some(&b'[') {
1183            // Section header `[table]` or `[[array]]`
1184            let mut end = len;
1185            if let Some(comment_pos) = line[trimmed_start..].find('#') {
1186                end = trimmed_start + comment_pos;
1187            }
1188            let header = line[trimmed_start..end].trim_end();
1189            tokens.push(SyntaxToken {
1190                token_type: TokenType::Heading,
1191                start_col: trimmed_start,
1192                end_col: trimmed_start + header.len(),
1193                text: header.to_string(),
1194            });
1195            if end < len {
1196                tokens.push(SyntaxToken {
1197                    token_type: TokenType::Comment,
1198                    start_col: end,
1199                    end_col: len,
1200                    text: line[end..].to_string(),
1201                });
1202            }
1203            return (tokens, LineLexState::Normal);
1204        }
1205
1206        let mut seen_eq = false;
1207        while i < len {
1208            let b = bytes[i];
1209            if b.is_ascii_whitespace() {
1210                i += 1;
1211                continue;
1212            }
1213            if b == b'#' {
1214                tokens.push(SyntaxToken {
1215                    token_type: TokenType::Comment,
1216                    start_col: i,
1217                    end_col: len,
1218                    text: line[i..].to_string(),
1219                });
1220                break;
1221            }
1222            // Triple-quoted strings
1223            if (b == b'"' || b == b'\'')
1224                && i + 2 < len
1225                && bytes[i + 1] == b
1226                && bytes[i + 2] == b
1227            {
1228                let start = i;
1229                let delim = [b, b, b];
1230                i += 3;
1231                if let Some(rel) = find_bytes(&bytes[i..], &delim) {
1232                    i += rel + 3;
1233                    tokens.push(SyntaxToken {
1234                        token_type: TokenType::String,
1235                        start_col: start,
1236                        end_col: i,
1237                        text: line[start..i].to_string(),
1238                    });
1239                    continue;
1240                } else {
1241                    tokens.push(SyntaxToken {
1242                        token_type: TokenType::String,
1243                        start_col: start,
1244                        end_col: len,
1245                        text: line[start..len].to_string(),
1246                    });
1247                    return (tokens, LineLexState::TripleString { quote: b });
1248                }
1249            }
1250            if b == b'"' || b == b'\'' {
1251                let start = i;
1252                let q = b;
1253                i += 1;
1254                while i < len {
1255                    if q == b'"' && bytes[i] == b'\\' && i + 1 < len {
1256                        i += 2;
1257                    } else if bytes[i] == q {
1258                        i += 1;
1259                        break;
1260                    } else {
1261                        i += 1;
1262                    }
1263                }
1264                tokens.push(SyntaxToken {
1265                    token_type: if !seen_eq {
1266                        TokenType::Property
1267                    } else {
1268                        TokenType::String
1269                    },
1270                    start_col: start,
1271                    end_col: i,
1272                    text: line[start..i].to_string(),
1273                });
1274                continue;
1275            }
1276            if b == b'=' {
1277                seen_eq = true;
1278                tokens.push(SyntaxToken {
1279                    token_type: TokenType::Operator,
1280                    start_col: i,
1281                    end_col: i + 1,
1282                    text: "=".to_string(),
1283                });
1284                i += 1;
1285                continue;
1286            }
1287            if b.is_ascii_digit() || (b == b'-' && seen_eq && i + 1 < len && bytes[i + 1].is_ascii_digit()) {
1288                let start = i;
1289                i += 1;
1290                while i < len
1291                    && (bytes[i].is_ascii_alphanumeric()
1292                        || matches!(bytes[i], b'.' | b'_' | b'-' | b':' | b'+' | b'T' | b'Z'))
1293                {
1294                    i += 1;
1295                }
1296                tokens.push(SyntaxToken {
1297                    token_type: TokenType::Number,
1298                    start_col: start,
1299                    end_col: i,
1300                    text: line[start..i].to_string(),
1301                });
1302                continue;
1303            }
1304            if b.is_ascii_alphabetic() || b == b'_' {
1305                let start = i;
1306                while i < len && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'_' | b'-')) {
1307                    i += 1;
1308                }
1309                let word = &line[start..i];
1310                let tt = if !seen_eq {
1311                    TokenType::Property
1312                } else if word == "true" || word == "false" {
1313                    TokenType::Boolean
1314                } else {
1315                    TokenType::Identifier
1316                };
1317                tokens.push(SyntaxToken {
1318                    token_type: tt,
1319                    start_col: start,
1320                    end_col: i,
1321                    text: word.to_string(),
1322                });
1323                continue;
1324            }
1325            let ch_len = line[i..].chars().next().map_or(1, char::len_utf8);
1326            tokens.push(SyntaxToken {
1327                token_type: TokenType::Punctuation,
1328                start_col: i,
1329                end_col: i + ch_len,
1330                text: line[i..i + ch_len].to_string(),
1331            });
1332            i += ch_len;
1333        }
1334        (tokens, LineLexState::Normal)
1335    }
1336
1337    fn scan_xml_line(line: &str, entry_state: &LineLexState) -> (Vec<SyntaxToken>, LineLexState) {
1338        let mut tokens = Vec::new();
1339        let bytes = line.as_bytes();
1340        let len = bytes.len();
1341        let mut i = 0;
1342
1343        match entry_state {
1344            LineLexState::XmlComment => {
1345                if let Some(rel) = find_bytes(&bytes[i..], b"-->") {
1346                    let end = i + rel + 3;
1347                    tokens.push(SyntaxToken {
1348                        token_type: TokenType::Comment,
1349                        start_col: 0,
1350                        end_col: end,
1351                        text: line[0..end].to_string(),
1352                    });
1353                    i = end;
1354                } else {
1355                    if !line.is_empty() {
1356                        tokens.push(SyntaxToken {
1357                            token_type: TokenType::Comment,
1358                            start_col: 0,
1359                            end_col: len,
1360                            text: line.to_string(),
1361                        });
1362                    }
1363                    return (tokens, LineLexState::XmlComment);
1364                }
1365            }
1366            LineLexState::XmlCdata => {
1367                if let Some(rel) = find_bytes(&bytes[i..], b"]]>") {
1368                    let end = i + rel + 3;
1369                    tokens.push(SyntaxToken {
1370                        token_type: TokenType::String,
1371                        start_col: 0,
1372                        end_col: end,
1373                        text: line[0..end].to_string(),
1374                    });
1375                    i = end;
1376                } else {
1377                    if !line.is_empty() {
1378                        tokens.push(SyntaxToken {
1379                            token_type: TokenType::String,
1380                            start_col: 0,
1381                            end_col: len,
1382                            text: line.to_string(),
1383                        });
1384                    }
1385                    return (tokens, LineLexState::XmlCdata);
1386                }
1387            }
1388            _ => {}
1389        }
1390
1391        while i < len {
1392            let b = bytes[i];
1393            if b.is_ascii_whitespace() {
1394                i += 1;
1395                continue;
1396            }
1397            if bytes[i..].starts_with(b"<!--") {
1398                let start = i;
1399                if let Some(rel) = find_bytes(&bytes[i + 4..], b"-->") {
1400                    i = i + 4 + rel + 3;
1401                    tokens.push(SyntaxToken {
1402                        token_type: TokenType::Comment,
1403                        start_col: start,
1404                        end_col: i,
1405                        text: line[start..i].to_string(),
1406                    });
1407                    continue;
1408                } else {
1409                    tokens.push(SyntaxToken {
1410                        token_type: TokenType::Comment,
1411                        start_col: start,
1412                        end_col: len,
1413                        text: line[start..len].to_string(),
1414                    });
1415                    return (tokens, LineLexState::XmlComment);
1416                }
1417            }
1418            if bytes[i..].starts_with(b"<![CDATA[") {
1419                let start = i;
1420                if let Some(rel) = find_bytes(&bytes[i + 9..], b"]]>") {
1421                    i = i + 9 + rel + 3;
1422                    tokens.push(SyntaxToken {
1423                        token_type: TokenType::String,
1424                        start_col: start,
1425                        end_col: i,
1426                        text: line[start..i].to_string(),
1427                    });
1428                    continue;
1429                } else {
1430                    tokens.push(SyntaxToken {
1431                        token_type: TokenType::String,
1432                        start_col: start,
1433                        end_col: len,
1434                        text: line[start..len].to_string(),
1435                    });
1436                    return (tokens, LineLexState::XmlCdata);
1437                }
1438            }
1439            if b == b'<' {
1440                let p_start = i;
1441                i += 1;
1442                if i < len && (bytes[i] == b'/' || bytes[i] == b'?' || bytes[i] == b'!') {
1443                    i += 1;
1444                }
1445                tokens.push(SyntaxToken {
1446                    token_type: TokenType::Punctuation,
1447                    start_col: p_start,
1448                    end_col: i,
1449                    text: line[p_start..i].to_string(),
1450                });
1451                // Tag name
1452                let tag_start = i;
1453                while i < len
1454                    && (bytes[i].is_ascii_alphanumeric()
1455                        || matches!(bytes[i], b'_' | b'-' | b':' | b'.'))
1456                {
1457                    i += 1;
1458                }
1459                if i > tag_start {
1460                    tokens.push(SyntaxToken {
1461                        token_type: TokenType::Tag,
1462                        start_col: tag_start,
1463                        end_col: i,
1464                        text: line[tag_start..i].to_string(),
1465                    });
1466                }
1467                // Attributes until `>`
1468                while i < len {
1469                    if bytes[i].is_ascii_whitespace() {
1470                        i += 1;
1471                        continue;
1472                    }
1473                    if bytes[i] == b'>' {
1474                        tokens.push(SyntaxToken {
1475                            token_type: TokenType::Punctuation,
1476                            start_col: i,
1477                            end_col: i + 1,
1478                            text: ">".to_string(),
1479                        });
1480                        i += 1;
1481                        break;
1482                    }
1483                    if (bytes[i] == b'/' || bytes[i] == b'?') && i + 1 < len && bytes[i + 1] == b'>' {
1484                        tokens.push(SyntaxToken {
1485                            token_type: TokenType::Punctuation,
1486                            start_col: i,
1487                            end_col: i + 2,
1488                            text: line[i..i + 2].to_string(),
1489                        });
1490                        i += 2;
1491                        break;
1492                    }
1493                    if bytes[i] == b'=' {
1494                        tokens.push(SyntaxToken {
1495                            token_type: TokenType::Operator,
1496                            start_col: i,
1497                            end_col: i + 1,
1498                            text: "=".to_string(),
1499                        });
1500                        i += 1;
1501                        continue;
1502                    }
1503                    if bytes[i] == b'"' || bytes[i] == b'\'' {
1504                        let q = bytes[i];
1505                        let s_start = i;
1506                        i += 1;
1507                        while i < len && bytes[i] != q {
1508                            i += 1;
1509                        }
1510                        if i < len {
1511                            i += 1;
1512                        }
1513                        tokens.push(SyntaxToken {
1514                            token_type: TokenType::String,
1515                            start_col: s_start,
1516                            end_col: i,
1517                            text: line[s_start..i].to_string(),
1518                        });
1519                        continue;
1520                    }
1521                    let a_start = i;
1522                    while i < len
1523                        && !bytes[i].is_ascii_whitespace()
1524                        && !matches!(bytes[i], b'=' | b'>' | b'/' | b'?')
1525                    {
1526                        i += 1;
1527                    }
1528                    if i > a_start {
1529                        tokens.push(SyntaxToken {
1530                            token_type: TokenType::Attribute,
1531                            start_col: a_start,
1532                            end_col: i,
1533                            text: line[a_start..i].to_string(),
1534                        });
1535                    } else {
1536                        i += 1;
1537                    }
1538                }
1539                continue;
1540            }
1541            // Text / numeric payload between XML/SDF tags (e.g. `<pose>0 0 1.2 0 0 0</pose>`)
1542            let start = i;
1543            while i < len && bytes[i] != b'<' && !bytes[i].is_ascii_whitespace() {
1544                i += 1;
1545            }
1546            let word = &line[start..i];
1547            let tt = if is_numeric_literal(word) {
1548                TokenType::Number
1549            } else if word == "true" || word == "false" {
1550                TokenType::Boolean
1551            } else {
1552                TokenType::Identifier
1553            };
1554            tokens.push(SyntaxToken {
1555                token_type: tt,
1556                start_col: start,
1557                end_col: i,
1558                text: word.to_string(),
1559            });
1560        }
1561        (tokens, LineLexState::Normal)
1562    }
1563
1564    fn scan_markdown_line(
1565        line: &str,
1566        entry_state: &LineLexState,
1567    ) -> (Vec<SyntaxToken>, LineLexState) {
1568        let indent = line.bytes().take_while(|&b| b == b' ').count();
1569        let trimmed = &line[indent..];
1570
1571        if let LineLexState::MarkdownFence {
1572            fence_char,
1573            fence_len,
1574            embedded,
1575        } = *entry_state
1576        {
1577            let run = trimmed.bytes().take_while(|&b| b == fence_char).count();
1578            if run >= fence_len as usize && trimmed[run..].trim().is_empty() {
1579                return (
1580                    vec![SyntaxToken {
1581                        token_type: TokenType::Punctuation,
1582                        start_col: indent,
1583                        end_col: line.len(),
1584                        text: trimmed.to_string(),
1585                    }],
1586                    LineLexState::Normal,
1587                );
1588            }
1589            let (toks, _) = Self::scan_line_with_state(line, embedded, &LineLexState::Normal);
1590            return (
1591                toks,
1592                LineLexState::MarkdownFence {
1593                    fence_char,
1594                    fence_len,
1595                    embedded,
1596                },
1597            );
1598        }
1599
1600        // Opening fenced code block ```lang or ~~~lang
1601        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
1602            let fc = trimmed.as_bytes()[0];
1603            let fl = trimmed.bytes().take_while(|&b| b == fc).count().min(255) as u8;
1604            let info = trimmed[fl as usize..].trim();
1605            let embedded = if info.is_empty() {
1606                Language::PlainText
1607            } else {
1608                Language::from_extension(info.split_whitespace().next().unwrap_or(""))
1609            };
1610            let mut toks = vec![SyntaxToken {
1611                token_type: TokenType::Punctuation,
1612                start_col: indent,
1613                end_col: indent + fl as usize,
1614                text: line[indent..indent + fl as usize].to_string(),
1615            }];
1616            if !info.is_empty() {
1617                let info_start = indent + fl as usize;
1618                toks.push(SyntaxToken {
1619                    token_type: TokenType::Type,
1620                    start_col: info_start,
1621                    end_col: line.len(),
1622                    text: line[info_start..].to_string(),
1623                });
1624            }
1625            return (
1626                toks,
1627                LineLexState::MarkdownFence {
1628                    fence_char: fc,
1629                    fence_len: fl,
1630                    embedded,
1631                },
1632            );
1633        }
1634
1635        // ATX Headings `# ...`
1636        if trimmed.starts_with('#') {
1637            let hashes = trimmed.bytes().take_while(|&b| b == b'#').count();
1638            if (1..=6).contains(&hashes)
1639                && trimmed.as_bytes().get(hashes).is_none_or(|b| *b == b' ')
1640            {
1641                return (
1642                    vec![SyntaxToken {
1643                        token_type: TokenType::Heading,
1644                        start_col: indent,
1645                        end_col: line.len(),
1646                        text: trimmed.to_string(),
1647                    }],
1648                    LineLexState::Normal,
1649                );
1650            }
1651        }
1652
1653        // Blockquote `> ...`
1654        if trimmed.starts_with('>') {
1655            return (
1656                vec![SyntaxToken {
1657                    token_type: TokenType::Comment,
1658                    start_col: indent,
1659                    end_col: line.len(),
1660                    text: trimmed.to_string(),
1661                }],
1662                LineLexState::Normal,
1663            );
1664        }
1665
1666        let mut tokens = Vec::new();
1667        let bytes = line.as_bytes();
1668        let len = bytes.len();
1669        let mut i = indent;
1670        while i < len {
1671            if bytes[i] == b'`' {
1672                let start = i;
1673                i += 1;
1674                while i < len && bytes[i] != b'`' {
1675                    i += 1;
1676                }
1677                if i < len {
1678                    i += 1;
1679                }
1680                tokens.push(SyntaxToken {
1681                    token_type: TokenType::String,
1682                    start_col: start,
1683                    end_col: i,
1684                    text: line[start..i].to_string(),
1685                });
1686                continue;
1687            }
1688            if bytes[i] == b'[' {
1689                if let Some(close_br) = line[i..].find("](") {
1690                    let link_start = i;
1691                    let after_mid = i + close_br + 2;
1692                    if let Some(close_par) = line[after_mid..].find(')') {
1693                        let end = after_mid + close_par + 1;
1694                        tokens.push(SyntaxToken {
1695                            token_type: TokenType::Link,
1696                            start_col: link_start,
1697                            end_col: end,
1698                            text: line[link_start..end].to_string(),
1699                        });
1700                        i = end;
1701                        continue;
1702                    }
1703                }
1704            }
1705            if bytes[i..].starts_with(b"**") {
1706                if let Some(close) = line[i + 2..].find("**") {
1707                    let end = i + 2 + close + 2;
1708                    tokens.push(SyntaxToken {
1709                        token_type: TokenType::Keyword,
1710                        start_col: i,
1711                        end_col: end,
1712                        text: line[i..end].to_string(),
1713                    });
1714                    i = end;
1715                    continue;
1716                }
1717            }
1718            i += line[i..].chars().next().map_or(1, char::len_utf8);
1719        }
1720        (tokens, LineLexState::Normal)
1721    }
1722
1723    fn scan_shell_line(line: &str, entry_state: &LineLexState) -> (Vec<SyntaxToken>, LineLexState) {
1724        if let LineLexState::ShellHeredoc { ref delimiter } = *entry_state {
1725            if line.trim() == delimiter.as_str() {
1726                return (
1727                    vec![SyntaxToken {
1728                        token_type: TokenType::Keyword,
1729                        start_col: 0,
1730                        end_col: line.len(),
1731                        text: line.to_string(),
1732                    }],
1733                    LineLexState::Normal,
1734                );
1735            }
1736            let toks = if line.is_empty() {
1737                Vec::new()
1738            } else {
1739                vec![SyntaxToken {
1740                    token_type: TokenType::String,
1741                    start_col: 0,
1742                    end_col: line.len(),
1743                    text: line.to_string(),
1744                }]
1745            };
1746            return (toks, entry_state.clone());
1747        }
1748
1749        let mut tokens = Vec::new();
1750        let bytes = line.as_bytes();
1751        let len = bytes.len();
1752        let mut i = 0;
1753        let mut exit_state = LineLexState::Normal;
1754
1755        // Shebang
1756        if line.starts_with("#!") {
1757            return (
1758                vec![SyntaxToken {
1759                    token_type: TokenType::DocComment,
1760                    start_col: 0,
1761                    end_col: len,
1762                    text: line.to_string(),
1763                }],
1764                LineLexState::Normal,
1765            );
1766        }
1767
1768        while i < len {
1769            let b = bytes[i];
1770            if b.is_ascii_whitespace() {
1771                i += 1;
1772                continue;
1773            }
1774            if b == b'#' {
1775                tokens.push(SyntaxToken {
1776                    token_type: TokenType::Comment,
1777                    start_col: i,
1778                    end_col: len,
1779                    text: line[i..].to_string(),
1780                });
1781                break;
1782            }
1783            // Heredoc `<<EOF` / `<<-'EOF'`
1784            if b == b'<' && i + 1 < len && bytes[i + 1] == b'<' && bytes.get(i + 2) != Some(&b'<')
1785            {
1786                let start = i;
1787                i += 2;
1788                if i < len && bytes[i] == b'-' {
1789                    i += 1;
1790                }
1791                while i < len && bytes[i].is_ascii_whitespace() {
1792                    i += 1;
1793                }
1794                let delim_start = i;
1795                while i < len && !bytes[i].is_ascii_whitespace() && bytes[i] != b';' {
1796                    i += 1;
1797                }
1798                let raw_delim = line[delim_start..i].trim_matches(|c| c == '\'' || c == '"');
1799                tokens.push(SyntaxToken {
1800                    token_type: TokenType::Operator,
1801                    start_col: start,
1802                    end_col: i,
1803                    text: line[start..i].to_string(),
1804                });
1805                if !raw_delim.is_empty() {
1806                    exit_state = LineLexState::ShellHeredoc {
1807                        delimiter: raw_delim.to_string(),
1808                    };
1809                }
1810                continue;
1811            }
1812            if b == b'$' {
1813                let start = i;
1814                i += 1;
1815                if i < len && bytes[i] == b'{' {
1816                    i += 1;
1817                    while i < len && bytes[i] != b'}' {
1818                        i += 1;
1819                    }
1820                    if i < len {
1821                        i += 1;
1822                    }
1823                } else {
1824                    while i < len
1825                        && (bytes[i].is_ascii_alphanumeric()
1826                            || matches!(bytes[i], b'_' | b'?' | b'#' | b'@' | b'*' | b'$'))
1827                    {
1828                        i += 1;
1829                    }
1830                }
1831                tokens.push(SyntaxToken {
1832                    token_type: TokenType::Variable,
1833                    start_col: start,
1834                    end_col: i,
1835                    text: line[start..i].to_string(),
1836                });
1837                continue;
1838            }
1839            if b == b'"' || b == b'\'' {
1840                let q = b;
1841                let start = i;
1842                i += 1;
1843                while i < len {
1844                    if q == b'"' && bytes[i] == b'\\' && i + 1 < len {
1845                        i += 2;
1846                    } else if bytes[i] == q {
1847                        i += 1;
1848                        break;
1849                    } else {
1850                        i += 1;
1851                    }
1852                }
1853                tokens.push(SyntaxToken {
1854                    token_type: TokenType::String,
1855                    start_col: start,
1856                    end_col: i,
1857                    text: line[start..i].to_string(),
1858                });
1859                continue;
1860            }
1861            if b == b'-' && i + 1 < len && (bytes[i + 1].is_ascii_alphabetic() || bytes[i + 1] == b'-')
1862            {
1863                let start = i;
1864                while i < len
1865                    && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'-' | b'_'))
1866                {
1867                    i += 1;
1868                }
1869                tokens.push(SyntaxToken {
1870                    token_type: TokenType::Attribute,
1871                    start_col: start,
1872                    end_col: i,
1873                    text: line[start..i].to_string(),
1874                });
1875                continue;
1876            }
1877            if b.is_ascii_digit() {
1878                let start = i;
1879                while i < len && (bytes[i].is_ascii_digit() || bytes[i] == b'.') {
1880                    i += 1;
1881                }
1882                tokens.push(SyntaxToken {
1883                    token_type: TokenType::Number,
1884                    start_col: start,
1885                    end_col: i,
1886                    text: line[start..i].to_string(),
1887                });
1888                continue;
1889            }
1890            if b.is_ascii_alphabetic() || b == b'_' {
1891                let start = i;
1892                while i < len
1893                    && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'_' | b'-'))
1894                {
1895                    i += 1;
1896                }
1897                let word = &line[start..i];
1898                let tt = if matches!(
1899                    word,
1900                    "if" | "then"
1901                        | "else"
1902                        | "elif"
1903                        | "fi"
1904                        | "for"
1905                        | "while"
1906                        | "until"
1907                        | "do"
1908                        | "done"
1909                        | "case"
1910                        | "esac"
1911                        | "in"
1912                        | "return"
1913                        | "break"
1914                        | "continue"
1915                        | "exit"
1916                ) {
1917                    TokenType::ControlFlow
1918                } else if matches!(
1919                    word,
1920                    "function"
1921                        | "local"
1922                        | "export"
1923                        | "readonly"
1924                        | "declare"
1925                        | "unset"
1926                        | "set"
1927                        | "source"
1928                        | "eval"
1929                        | "exec"
1930                ) {
1931                    TokenType::Keyword
1932                } else if matches!(
1933                    word,
1934                    "echo" | "printf" | "cd" | "pwd" | "test" | "grep" | "sed" | "awk" | "cargo"
1935                        | "git"
1936                ) {
1937                    TokenType::Function
1938                } else if bytes.get(i) == Some(&b'=') {
1939                    TokenType::Variable
1940                } else {
1941                    TokenType::Identifier
1942                };
1943                tokens.push(SyntaxToken {
1944                    token_type: tt,
1945                    start_col: start,
1946                    end_col: i,
1947                    text: word.to_string(),
1948                });
1949                continue;
1950            }
1951            let ch_len = line[i..].chars().next().map_or(1, char::len_utf8);
1952            let tt = if matches!(b, b'|' | b'&' | b'>' | b'<' | b'=' | b'!') {
1953                TokenType::Operator
1954            } else {
1955                TokenType::Punctuation
1956            };
1957            tokens.push(SyntaxToken {
1958                token_type: tt,
1959                start_col: i,
1960                end_col: i + ch_len,
1961                text: line[i..i + ch_len].to_string(),
1962            });
1963            i += ch_len;
1964        }
1965        (tokens, exit_state)
1966    }
1967
1968    fn scan_python_line(
1969        line: &str,
1970        entry_state: &LineLexState,
1971    ) -> (Vec<SyntaxToken>, LineLexState) {
1972        let mut tokens = Vec::new();
1973        let bytes = line.as_bytes();
1974        let len = bytes.len();
1975        let mut i = 0;
1976
1977        if let LineLexState::TripleString { quote } = *entry_state {
1978            let delim = [quote, quote, quote];
1979            if let Some(rel) = find_bytes(&bytes[i..], &delim) {
1980                let end = i + rel + 3;
1981                tokens.push(SyntaxToken {
1982                    token_type: TokenType::String,
1983                    start_col: 0,
1984                    end_col: end,
1985                    text: line[0..end].to_string(),
1986                });
1987                i = end;
1988            } else {
1989                if !line.is_empty() {
1990                    tokens.push(SyntaxToken {
1991                        token_type: TokenType::String,
1992                        start_col: 0,
1993                        end_col: len,
1994                        text: line.to_string(),
1995                    });
1996                }
1997                return (tokens, LineLexState::TripleString { quote });
1998            }
1999        }
2000
2001        while i < len {
2002            let b = bytes[i];
2003            if b.is_ascii_whitespace() {
2004                i += 1;
2005                continue;
2006            }
2007            if b == b'#' {
2008                tokens.push(SyntaxToken {
2009                    token_type: TokenType::Comment,
2010                    start_col: i,
2011                    end_col: len,
2012                    text: line[i..].to_string(),
2013                });
2014                break;
2015            }
2016            // Decorators `@dataclass`
2017            if b == b'@' {
2018                let start = i;
2019                i += 1;
2020                while i < len
2021                    && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'_' | b'.'))
2022                {
2023                    i += 1;
2024                }
2025                tokens.push(SyntaxToken {
2026                    token_type: TokenType::Attribute,
2027                    start_col: start,
2028                    end_col: i,
2029                    text: line[start..i].to_string(),
2030                });
2031                continue;
2032            }
2033            // Prefixed strings (`f"..."`, `r"..."`, `b"..."`, `"""..."""`)
2034            let str_prefix_len = if matches!(b, b'f' | b'r' | b'b' | b'u' | b'F' | b'R' | b'B' | b'U')
2035                && bytes.get(i + 1).is_some_and(|&nb| nb == b'"' || nb == b'\'')
2036            {
2037                1
2038            } else if i + 2 < len
2039                && matches!(b, b'f' | b'r' | b'b' | b'F' | b'R' | b'B')
2040                && matches!(bytes[i + 1], b'f' | b'r' | b'b' | b'F' | b'R' | b'B')
2041                && matches!(bytes[i + 2], b'"' | b'\'')
2042            {
2043                2
2044            } else {
2045                0
2046            };
2047            if str_prefix_len > 0 || b == b'"' || b == b'\'' {
2048                let start = i;
2049                let q_pos = i + str_prefix_len;
2050                let q = bytes[q_pos];
2051                if q_pos + 2 < len && bytes[q_pos + 1] == q && bytes[q_pos + 2] == q {
2052                    let delim = [q, q, q];
2053                    let body_start = q_pos + 3;
2054                    if let Some(rel) = find_bytes(&bytes[body_start..], &delim) {
2055                        i = body_start + rel + 3;
2056                        tokens.push(SyntaxToken {
2057                            token_type: TokenType::String,
2058                            start_col: start,
2059                            end_col: i,
2060                            text: line[start..i].to_string(),
2061                        });
2062                        continue;
2063                    } else {
2064                        tokens.push(SyntaxToken {
2065                            token_type: TokenType::String,
2066                            start_col: start,
2067                            end_col: len,
2068                            text: line[start..len].to_string(),
2069                        });
2070                        return (tokens, LineLexState::TripleString { quote: q });
2071                    }
2072                }
2073                i = q_pos + 1;
2074                while i < len {
2075                    if bytes[i] == b'\\' && i + 1 < len {
2076                        i += 2;
2077                    } else if bytes[i] == q {
2078                        i += 1;
2079                        break;
2080                    } else {
2081                        i += 1;
2082                    }
2083                }
2084                tokens.push(SyntaxToken {
2085                    token_type: TokenType::String,
2086                    start_col: start,
2087                    end_col: i,
2088                    text: line[start..i].to_string(),
2089                });
2090                continue;
2091            }
2092            if b.is_ascii_digit() {
2093                let start = i;
2094                while i < len
2095                    && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'.' | b'_'))
2096                {
2097                    i += 1;
2098                }
2099                tokens.push(SyntaxToken {
2100                    token_type: TokenType::Number,
2101                    start_col: start,
2102                    end_col: i,
2103                    text: line[start..i].to_string(),
2104                });
2105                continue;
2106            }
2107            let ch = line[i..].chars().next().unwrap();
2108            if ch.is_alphabetic() || ch == '_' {
2109                let start = i;
2110                while i < len {
2111                    let c = line[i..].chars().next().unwrap();
2112                    if c.is_alphanumeric() || c == '_' {
2113                        i += c.len_utf8();
2114                    } else {
2115                        break;
2116                    }
2117                }
2118                let word = &line[start..i];
2119                let tt = if matches!(
2120                    word,
2121                    "True" | "False"
2122                ) {
2123                    TokenType::Boolean
2124                } else if Self::is_keyword(word, Language::Python) {
2125                    TokenType::Keyword
2126                } else if Self::is_type(word, Language::Python) {
2127                    TokenType::Type
2128                } else if bytes.get(i) == Some(&b'(') {
2129                    TokenType::Function
2130                } else {
2131                    TokenType::Identifier
2132                };
2133                tokens.push(SyntaxToken {
2134                    token_type: tt,
2135                    start_col: start,
2136                    end_col: i,
2137                    text: word.to_string(),
2138                });
2139                continue;
2140            }
2141            let ch_len = ch.len_utf8();
2142            let tt = if matches!(
2143                b,
2144                b'+' | b'-' | b'*' | b'/' | b'%' | b'=' | b'<' | b'>' | b'!' | b'&' | b'|' | b'^'
2145            ) {
2146                TokenType::Operator
2147            } else {
2148                TokenType::Punctuation
2149            };
2150            tokens.push(SyntaxToken {
2151                token_type: tt,
2152                start_col: i,
2153                end_col: i + ch_len,
2154                text: line[i..i + ch_len].to_string(),
2155            });
2156            i += ch_len;
2157        }
2158        (tokens, LineLexState::Normal)
2159    }
2160
2161    fn scan_c_like_line(
2162        line: &str,
2163        lang: Language,
2164        entry_state: &LineLexState,
2165    ) -> (Vec<SyntaxToken>, LineLexState) {
2166        let mut tokens = Vec::new();
2167        let bytes = line.as_bytes();
2168        let len = bytes.len();
2169        let mut i = 0;
2170
2171        match *entry_state {
2172            LineLexState::BlockComment { mut depth, doc } => {
2173                let start = 0;
2174                while i + 1 < len {
2175                    if lang == Language::Rust && bytes[i] == b'/' && bytes[i + 1] == b'*' {
2176                        depth += 1;
2177                        i += 2;
2178                    } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
2179                        depth = depth.saturating_sub(1);
2180                        i += 2;
2181                        if depth == 0 {
2182                            tokens.push(SyntaxToken {
2183                                token_type: if doc {
2184                                    TokenType::DocComment
2185                                } else {
2186                                    TokenType::Comment
2187                                },
2188                                start_col: start,
2189                                end_col: i,
2190                                text: line[start..i].to_string(),
2191                            });
2192                            break;
2193                        }
2194                    } else {
2195                        i += 1;
2196                    }
2197                }
2198                if depth > 0 {
2199                    if !line.is_empty() {
2200                        tokens.push(SyntaxToken {
2201                            token_type: if doc {
2202                                TokenType::DocComment
2203                            } else {
2204                                TokenType::Comment
2205                            },
2206                            start_col: 0,
2207                            end_col: len,
2208                            text: line.to_string(),
2209                        });
2210                    }
2211                    return (tokens, LineLexState::BlockComment { depth, doc });
2212                }
2213            }
2214            LineLexState::RustRawString { hashes } => {
2215                if let Some(end) = find_rust_raw_string_end(bytes, 0, hashes) {
2216                    tokens.push(SyntaxToken {
2217                        token_type: TokenType::String,
2218                        start_col: 0,
2219                        end_col: end,
2220                        text: line[0..end].to_string(),
2221                    });
2222                    i = end;
2223                } else {
2224                    if !line.is_empty() {
2225                        tokens.push(SyntaxToken {
2226                            token_type: TokenType::String,
2227                            start_col: 0,
2228                            end_col: len,
2229                            text: line.to_string(),
2230                        });
2231                    }
2232                    return (tokens, LineLexState::RustRawString { hashes });
2233                }
2234            }
2235            _ => {}
2236        }
2237
2238        // C/C++ preprocessor directive lines (`#include`, `#define`, `#ifdef`, `#endif`)
2239        if lang == Language::Cpp && i == 0 {
2240            let ws = line.bytes().take_while(|b| b.is_ascii_whitespace()).count();
2241            if bytes.get(ws) == Some(&b'#') {
2242                let mut d_end = ws + 1;
2243                while d_end < len && bytes[d_end].is_ascii_whitespace() {
2244                    d_end += 1;
2245                }
2246                while d_end < len && (bytes[d_end].is_ascii_alphanumeric() || bytes[d_end] == b'_')
2247                {
2248                    d_end += 1;
2249                }
2250                tokens.push(SyntaxToken {
2251                    token_type: TokenType::Macro,
2252                    start_col: ws,
2253                    end_col: d_end,
2254                    text: line[ws..d_end].to_string(),
2255                });
2256                i = d_end;
2257                // Highlight `<header.h>` right after `#include`
2258                if line[ws..d_end].contains("include") {
2259                    while i < len && bytes[i].is_ascii_whitespace() {
2260                        i += 1;
2261                    }
2262                    if bytes.get(i) == Some(&b'<') {
2263                        let s = i;
2264                        if let Some(rel) = line[i..].find('>') {
2265                            i += rel + 1;
2266                            tokens.push(SyntaxToken {
2267                                token_type: TokenType::String,
2268                                start_col: s,
2269                                end_col: i,
2270                                text: line[s..i].to_string(),
2271                            });
2272                        }
2273                    }
2274                }
2275            }
2276        }
2277
2278        while i < len {
2279            let b = bytes[i];
2280            if b.is_ascii_whitespace() {
2281                i += 1;
2282                continue;
2283            }
2284            // Line comments
2285            if b == b'/' && i + 1 < len && bytes[i + 1] == b'/' {
2286                let is_doc = bytes.get(i + 2).is_some_and(|&c| c == b'/' || c == b'!');
2287                tokens.push(SyntaxToken {
2288                    token_type: if is_doc {
2289                        TokenType::DocComment
2290                    } else {
2291                        TokenType::Comment
2292                    },
2293                    start_col: i,
2294                    end_col: len,
2295                    text: line[i..len].to_string(),
2296                });
2297                break;
2298            }
2299            // Block comments `/* ... */`
2300            if b == b'/' && i + 1 < len && bytes[i + 1] == b'*' {
2301                let start = i;
2302                let doc = bytes.get(i + 2) == Some(&b'*') && bytes.get(i + 3) != Some(&b'/');
2303                let mut depth = 1u16;
2304                i += 2;
2305                while i + 1 < len {
2306                    if lang == Language::Rust && bytes[i] == b'/' && bytes[i + 1] == b'*' {
2307                        depth += 1;
2308                        i += 2;
2309                    } else if bytes[i] == b'*' && bytes[i + 1] == b'/' {
2310                        depth -= 1;
2311                        i += 2;
2312                        if depth == 0 {
2313                            break;
2314                        }
2315                    } else {
2316                        i += 1;
2317                    }
2318                }
2319                if depth > 0 {
2320                    tokens.push(SyntaxToken {
2321                        token_type: if doc {
2322                            TokenType::DocComment
2323                        } else {
2324                            TokenType::Comment
2325                        },
2326                        start_col: start,
2327                        end_col: len,
2328                        text: line[start..len].to_string(),
2329                    });
2330                    return (tokens, LineLexState::BlockComment { depth, doc });
2331                }
2332                tokens.push(SyntaxToken {
2333                    token_type: if doc {
2334                        TokenType::DocComment
2335                    } else {
2336                        TokenType::Comment
2337                    },
2338                    start_col: start,
2339                    end_col: i,
2340                    text: line[start..i].to_string(),
2341                });
2342                continue;
2343            }
2344            // Rust raw strings `r#"..."#`
2345            if lang == Language::Rust && b == b'r' {
2346                let mut probe = i + 1;
2347                let mut hashes = 0u8;
2348                while probe < len && bytes[probe] == b'#' && hashes < 250 {
2349                    hashes += 1;
2350                    probe += 1;
2351                }
2352                if probe < len && bytes[probe] == b'"' {
2353                    let start = i;
2354                    if let Some(end) = find_rust_raw_string_end(bytes, probe + 1, hashes) {
2355                        tokens.push(SyntaxToken {
2356                            token_type: TokenType::String,
2357                            start_col: start,
2358                            end_col: end,
2359                            text: line[start..end].to_string(),
2360                        });
2361                        i = end;
2362                        continue;
2363                    } else {
2364                        tokens.push(SyntaxToken {
2365                            token_type: TokenType::String,
2366                            start_col: start,
2367                            end_col: len,
2368                            text: line[start..len].to_string(),
2369                        });
2370                        return (tokens, LineLexState::RustRawString { hashes });
2371                    }
2372                }
2373            }
2374            // Rust attributes `#[...]` / `#![...]`
2375            if lang == Language::Rust
2376                && b == b'#'
2377                && (bytes.get(i + 1) == Some(&b'[')
2378                    || (bytes.get(i + 1) == Some(&b'!') && bytes.get(i + 2) == Some(&b'[')))
2379            {
2380                let start = i;
2381                while i < len && bytes[i] != b']' {
2382                    i += 1;
2383                }
2384                if i < len {
2385                    i += 1;
2386                }
2387                tokens.push(SyntaxToken {
2388                    token_type: TokenType::Attribute,
2389                    start_col: start,
2390                    end_col: i,
2391                    text: line[start..i].to_string(),
2392                });
2393                continue;
2394            }
2395            // Strings (`"..."`, `'...'`, `` `...` ``)
2396            if b == b'"' || b == b'`' || (b == b'\'' && lang != Language::Rust) {
2397                let quote = b;
2398                let start = i;
2399                i += 1;
2400                while i < len {
2401                    if bytes[i] == b'\\' && i + 1 < len {
2402                        i += 2;
2403                    } else if bytes[i] == quote {
2404                        i += 1;
2405                        break;
2406                    } else {
2407                        i += 1;
2408                    }
2409                }
2410                tokens.push(SyntaxToken {
2411                    token_type: TokenType::String,
2412                    start_col: start,
2413                    end_col: i,
2414                    text: line[start..i].to_string(),
2415                });
2416                continue;
2417            }
2418            // Rust char literal vs lifetime `'a`
2419            if b == b'\'' && lang == Language::Rust {
2420                let start = i;
2421                if i + 2 < len && bytes[i + 1] == b'\\' {
2422                    i += 3;
2423                    while i < len && bytes[i] != b'\'' {
2424                        i += 1;
2425                    }
2426                    if i < len {
2427                        i += 1;
2428                    }
2429                    tokens.push(SyntaxToken {
2430                        token_type: TokenType::String,
2431                        start_col: start,
2432                        end_col: i,
2433                        text: line[start..i].to_string(),
2434                    });
2435                    continue;
2436                }
2437                if let Some(ch) = line[i + 1..].chars().next() {
2438                    let after = i + 1 + ch.len_utf8();
2439                    if bytes.get(after) == Some(&b'\'') {
2440                        i = after + 1;
2441                        tokens.push(SyntaxToken {
2442                            token_type: TokenType::String,
2443                            start_col: start,
2444                            end_col: i,
2445                            text: line[start..i].to_string(),
2446                        });
2447                        continue;
2448                    }
2449                }
2450                // Lifetime `'a`, `'static`
2451                i += 1;
2452                while i < len && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
2453                    i += 1;
2454                }
2455                tokens.push(SyntaxToken {
2456                    token_type: TokenType::Namespace,
2457                    start_col: start,
2458                    end_col: i,
2459                    text: line[start..i].to_string(),
2460                });
2461                continue;
2462            }
2463            // Numeric literals (hex, binary, float, suffixes)
2464            if b.is_ascii_digit() {
2465                let start = i;
2466                while i < len
2467                    && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'.' | b'_'))
2468                {
2469                    i += 1;
2470                }
2471                tokens.push(SyntaxToken {
2472                    token_type: TokenType::Number,
2473                    start_col: start,
2474                    end_col: i,
2475                    text: line[start..i].to_string(),
2476                });
2477                continue;
2478            }
2479            // Identifiers, keywords, macros, types, functions
2480            let ch = line[i..].chars().next().unwrap();
2481            if ch.is_alphabetic() || ch == '_' {
2482                let start = i;
2483                while i < len {
2484                    let c = line[i..].chars().next().unwrap();
2485                    if c.is_alphanumeric() || c == '_' {
2486                        i += c.len_utf8();
2487                    } else {
2488                        break;
2489                    }
2490                }
2491                let word = &line[start..i];
2492                let tt = if lang == Language::Rust && bytes.get(i) == Some(&b'!') {
2493                    i += 1;
2494                    TokenType::Macro
2495                } else if word == "true" || word == "false" {
2496                    TokenType::Boolean
2497                } else if Self::is_keyword(word, lang) {
2498                    TokenType::Keyword
2499                } else if Self::is_type(word, lang) {
2500                    TokenType::Type
2501                } else if bytes.get(i) == Some(&b'(') {
2502                    TokenType::Function
2503                } else if bytes.get(i) == Some(&b':') && bytes.get(i + 1) == Some(&b':') {
2504                    TokenType::Namespace
2505                } else {
2506                    TokenType::Identifier
2507                };
2508                tokens.push(SyntaxToken {
2509                    token_type: tt,
2510                    start_col: start,
2511                    end_col: i,
2512                    text: line[start..i].to_string(),
2513                });
2514                continue;
2515            }
2516            // Operators and punctuation
2517            let ch_len = ch.len_utf8();
2518            let tt = if matches!(
2519                b,
2520                b'+' | b'-' | b'*' | b'/' | b'%' | b'=' | b'<' | b'>' | b'!' | b'&' | b'|' | b'^'
2521            ) {
2522                TokenType::Operator
2523            } else {
2524                TokenType::Punctuation
2525            };
2526            tokens.push(SyntaxToken {
2527                token_type: tt,
2528                start_col: i,
2529                end_col: i + ch_len,
2530                text: line[i..i + ch_len].to_string(),
2531            });
2532            i += ch_len;
2533        }
2534
2535        (tokens, LineLexState::Normal)
2536    }
2537
2538    fn is_keyword(word: &str, lang: Language) -> bool {
2539        match lang {
2540            Language::Rust => matches!(
2541                word,
2542                "fn" | "let"
2543                    | "mut"
2544                    | "pub"
2545                    | "struct"
2546                    | "enum"
2547                    | "impl"
2548                    | "trait"
2549                    | "match"
2550                    | "if"
2551                    | "else"
2552                    | "return"
2553                    | "for"
2554                    | "in"
2555                    | "while"
2556                    | "loop"
2557                    | "async"
2558                    | "await"
2559                    | "use"
2560                    | "mod"
2561                    | "crate"
2562                    | "const"
2563                    | "static"
2564                    | "type"
2565                    | "where"
2566                    | "as"
2567                    | "ref"
2568                    | "move"
2569                    | "unsafe"
2570                    | "dyn"
2571                    | "break"
2572                    | "continue"
2573                    | "super"
2574                    | "self"
2575                    | "Self"
2576            ),
2577            Language::TypeScript | Language::JavaScript => matches!(
2578                word,
2579                "function"
2580                    | "const"
2581                    | "let"
2582                    | "var"
2583                    | "return"
2584                    | "if"
2585                    | "else"
2586                    | "import"
2587                    | "export"
2588                    | "default"
2589                    | "from"
2590                    | "class"
2591                    | "interface"
2592                    | "type"
2593                    | "new"
2594                    | "this"
2595                    | "async"
2596                    | "await"
2597                    | "try"
2598                    | "catch"
2599                    | "finally"
2600                    | "switch"
2601                    | "case"
2602                    | "break"
2603                    | "continue"
2604                    | "throw"
2605                    | "extends"
2606                    | "implements"
2607                    | "null"
2608                    | "undefined"
2609                    | "readonly"
2610                    | "enum"
2611            ),
2612            Language::Python => matches!(
2613                word,
2614                "def"
2615                    | "class"
2616                    | "return"
2617                    | "if"
2618                    | "elif"
2619                    | "else"
2620                    | "for"
2621                    | "in"
2622                    | "while"
2623                    | "import"
2624                    | "from"
2625                    | "as"
2626                    | "try"
2627                    | "except"
2628                    | "finally"
2629                    | "with"
2630                    | "lambda"
2631                    | "pass"
2632                    | "break"
2633                    | "continue"
2634                    | "yield"
2635                    | "async"
2636                    | "await"
2637                    | "raise"
2638                    | "assert"
2639                    | "global"
2640                    | "nonlocal"
2641                    | "del"
2642                    | "not"
2643                    | "and"
2644                    | "or"
2645                    | "is"
2646                    | "match"
2647                    | "case"
2648                    | "None"
2649                    | "True"
2650                    | "False"
2651            ),
2652            Language::Cpp => matches!(
2653                word,
2654                "auto"
2655                    | "break"
2656                    | "case"
2657                    | "catch"
2658                    | "class"
2659                    | "concept"
2660                    | "const"
2661                    | "consteval"
2662                    | "constexpr"
2663                    | "constinit"
2664                    | "continue"
2665                    | "co_await"
2666                    | "co_return"
2667                    | "co_yield"
2668                    | "default"
2669                    | "delete"
2670                    | "do"
2671                    | "else"
2672                    | "enum"
2673                    | "explicit"
2674                    | "extern"
2675                    | "final"
2676                    | "for"
2677                    | "friend"
2678                    | "goto"
2679                    | "if"
2680                    | "inline"
2681                    | "mutable"
2682                    | "namespace"
2683                    | "new"
2684                    | "noexcept"
2685                    | "nullptr"
2686                    | "operator"
2687                    | "override"
2688                    | "private"
2689                    | "protected"
2690                    | "public"
2691                    | "requires"
2692                    | "return"
2693                    | "sizeof"
2694                    | "static"
2695                    | "static_assert"
2696                    | "struct"
2697                    | "switch"
2698                    | "template"
2699                    | "this"
2700                    | "throw"
2701                    | "try"
2702                    | "typedef"
2703                    | "typename"
2704                    | "union"
2705                    | "using"
2706                    | "virtual"
2707                    | "volatile"
2708                    | "while"
2709            ),
2710            Language::Json => matches!(word, "true" | "false" | "null"),
2711            _ => false,
2712        }
2713    }
2714
2715    fn is_type(word: &str, lang: Language) -> bool {
2716        match lang {
2717            Language::Rust => {
2718                word.chars().next().is_some_and(|c| c.is_uppercase())
2719                    || matches!(
2720                        word,
2721                        "u8" | "u16"
2722                            | "u32"
2723                            | "u64"
2724                            | "u128"
2725                            | "usize"
2726                            | "i8"
2727                            | "i16"
2728                            | "i32"
2729                            | "i64"
2730                            | "i128"
2731                            | "isize"
2732                            | "f32"
2733                            | "f64"
2734                            | "bool"
2735                            | "char"
2736                            | "str"
2737                            | "String"
2738                            | "Vec"
2739                            | "Option"
2740                            | "Result"
2741                    )
2742            }
2743            Language::TypeScript => {
2744                matches!(
2745                    word,
2746                    "string"
2747                        | "number"
2748                        | "boolean"
2749                        | "any"
2750                        | "void"
2751                        | "never"
2752                        | "unknown"
2753                        | "Record"
2754                        | "Array"
2755                        | "Promise"
2756                ) || word.chars().next().is_some_and(|c| c.is_uppercase())
2757            }
2758            Language::Cpp => {
2759                matches!(
2760                    word,
2761                    "void"
2762                        | "bool"
2763                        | "char"
2764                        | "short"
2765                        | "int"
2766                        | "long"
2767                        | "float"
2768                        | "double"
2769                        | "signed"
2770                        | "unsigned"
2771                        | "size_t"
2772                        | "int8_t"
2773                        | "int16_t"
2774                        | "int32_t"
2775                        | "int64_t"
2776                        | "uint8_t"
2777                        | "uint16_t"
2778                        | "uint32_t"
2779                        | "uint64_t"
2780                        | "string"
2781                        | "vector"
2782                        | "unique_ptr"
2783                        | "shared_ptr"
2784                        | "optional"
2785                        | "span"
2786                )
2787            }
2788            Language::Python => {
2789                matches!(
2790                    word,
2791                    "int" | "float" | "str" | "bool" | "bytes" | "list" | "dict" | "set" | "tuple"
2792                        | "Any" | "Optional" | "Union" | "Callable" | "Sequence"
2793                ) || word.chars().next().is_some_and(|c| c.is_uppercase())
2794            }
2795            _ => false,
2796        }
2797    }
2798
2799    /// Returns the root node of the active Tree-Sitter syntax tree, if available.
2800    pub fn root_node(&self) -> Option<Node<'_>> {
2801        self.tree.as_ref().map(|t| t.root_node())
2802    }
2803
2804    /// Finds the finest AST node at the given 0-indexed row and byte column.
2805    pub fn node_at_position(&self, line: usize, col: usize) -> Option<Node<'_>> {
2806        let tree = self.tree.as_ref()?;
2807        let pt = Point {
2808            row: line,
2809            column: col,
2810        };
2811        tree.root_node().descendant_for_point_range(pt, pt)
2812    }
2813
2814    /// Finds the enclosing scope or block range (start_line, end_line) containing the given position.
2815    pub fn enclosing_scope_range(&self, line: usize, col: usize) -> Option<(usize, usize)> {
2816        let mut node = self.node_at_position(line, col)?;
2817        loop {
2818            let kind = node.kind();
2819            if matches!(
2820                kind,
2821                "function_item"
2822                    | "impl_item"
2823                    | "struct_item"
2824                    | "enum_item"
2825                    | "trait_item"
2826                    | "block"
2827                    | "statement_block"
2828                    | "class_declaration"
2829                    | "function_declaration"
2830            ) {
2831                return Some((node.start_position().row, node.end_position().row));
2832            }
2833            node = node.parent()?;
2834        }
2835    }
2836
2837    /// Finds matching open or close bracket for delimiter at position `pos`.
2838    pub fn find_matching_bracket(&self, buffer: &LineBuffer, pos: Position) -> Option<Position> {
2839        let line = buffer.line(pos.line)?;
2840        let ch = line.chars().nth(pos.col)?;
2841
2842        let (target, is_forward) = match ch {
2843            '(' => (')', true),
2844            '[' => (']', true),
2845            '{' => ('}', true),
2846            '<' if matches!(self.language, Language::XmlSdf | Language::Html) => ('>', true),
2847            ')' => ('(', false),
2848            ']' => ('[', false),
2849            '}' => ('{', false),
2850            '>' if matches!(self.language, Language::XmlSdf | Language::Html) => ('<', false),
2851            _ => return None,
2852        };
2853
2854        let mut depth = 0;
2855
2856        if is_forward {
2857            for l in pos.line..buffer.line_count() {
2858                if let Some(text) = buffer.line(l) {
2859                    let start_c = if l == pos.line { pos.col } else { 0 };
2860                    for (c, cur) in text.chars().enumerate().skip(start_c) {
2861                        if cur == ch {
2862                            depth += 1;
2863                        } else if cur == target {
2864                            depth -= 1;
2865                            if depth == 0 {
2866                                return Some(Position::new(l, c));
2867                            }
2868                        }
2869                    }
2870                }
2871            }
2872        } else {
2873            for l in (0..=pos.line).rev() {
2874                if let Some(text) = buffer.line(l) {
2875                    let chars: Vec<char> = text.chars().collect();
2876                    let start_c = if l == pos.line {
2877                        pos.col
2878                    } else {
2879                        chars.len().saturating_sub(1)
2880                    };
2881                    for c in (0..=start_c).rev() {
2882                        let cur = chars[c];
2883                        if cur == ch {
2884                            depth += 1;
2885                        } else if cur == target {
2886                            depth -= 1;
2887                            if depth == 0 {
2888                                return Some(Position::new(l, c));
2889                            }
2890                        }
2891                    }
2892                }
2893            }
2894        }
2895
2896        None
2897    }
2898
2899    /// Extracts structural multi-line code folding regions for all 10 supported languages.
2900    pub fn compute_fold_ranges(&self, buffer: &LineBuffer) -> Vec<FoldRange> {
2901        if let Some(ref tree) = self.tree {
2902            let mut ranges = Vec::new();
2903            collect_ast_fold_ranges(tree.root_node(), &mut ranges);
2904            if !ranges.is_empty() {
2905                ranges.sort_by_key(|r| (r.start_line, r.end_line));
2906                ranges.dedup_by_key(|r| (r.start_line, r.end_line));
2907                return ranges;
2908            }
2909        }
2910
2911        let mut ranges = match self.language {
2912            Language::Python | Language::Yaml => compute_indent_fold_ranges(buffer),
2913            Language::Toml => compute_toml_fold_ranges(buffer),
2914            Language::XmlSdf | Language::Html => compute_xml_fold_ranges(buffer),
2915            Language::Markdown => compute_markdown_fold_ranges(buffer),
2916            Language::Shell => compute_shell_fold_ranges(buffer),
2917            Language::Cpp => {
2918                let mut r = compute_brace_fold_ranges(buffer, true);
2919                r.extend(compute_cpp_preproc_fold_ranges(buffer));
2920                r
2921            }
2922            Language::Json => compute_brace_fold_ranges(buffer, true),
2923            _ => compute_brace_fold_ranges(buffer, false),
2924        };
2925
2926        ranges.sort_by_key(|r| (r.start_line, r.end_line));
2927        ranges.dedup_by_key(|r| (r.start_line, r.end_line));
2928        ranges
2929    }
2930
2931    /// Collects real-time syntax diagnostics from the Tree-Sitter AST or structural validators
2932    /// (JSON, XML/SDF, TOML, unclosed brackets).
2933    pub fn collect_syntax_diagnostics(&self, buffer: &LineBuffer) -> Vec<SyntaxDiagnostic> {
2934        let mut out = Vec::new();
2935        if let Some(ref tree) = self.tree {
2936            collect_tree_sitter_errors(tree.root_node(), &mut out);
2937            return out;
2938        }
2939        match self.language {
2940            Language::Json => {
2941                let text = buffer.to_text();
2942                if !text.trim().is_empty() {
2943                    if let Err(err) = serde_json::from_str::<serde_json::Value>(&text) {
2944                        let line = err.line().saturating_sub(1);
2945                        let col = err.column().saturating_sub(1);
2946                        out.push(SyntaxDiagnostic {
2947                            start: Position::new(line, col),
2948                            end: Position::new(line, col + 1),
2949                            message: err.to_string(),
2950                            is_warning: false,
2951                        });
2952                    }
2953                }
2954            }
2955            Language::XmlSdf | Language::Html => {
2956                validate_xml_tags(buffer, &mut out);
2957            }
2958            _ => {}
2959        }
2960        out
2961    }
2962
2963    /// Computes indentation column spaces for a newly created newline following line `line_idx`.
2964    pub fn compute_auto_indent(&self, buffer: &LineBuffer, line_idx: usize) -> usize {
2965        let prev_line = match buffer.line(line_idx) {
2966            Some(l) => l,
2967            None => return 0,
2968        };
2969
2970        let current_indent = prev_line.chars().take_while(|c| *c == ' ').count();
2971        let trimmed = prev_line.trim_end();
2972        let indent_step = match self.language {
2973            Language::Yaml | Language::Json | Language::XmlSdf | Language::Html => 2,
2974            _ => 4,
2975        };
2976
2977        if let Some(ref tree) = self.tree {
2978            let pt = Point {
2979                row: line_idx,
2980                column: prev_line.len().saturating_sub(1),
2981            };
2982            if let Some(node) = tree.root_node().descendant_for_point_range(pt, pt) {
2983                let kind = node.kind();
2984                if kind == "{" || kind == ":" || kind == "(" || kind == "[" {
2985                    return current_indent + indent_step;
2986                }
2987            }
2988        }
2989
2990        if trimmed.ends_with('{')
2991            || trimmed.ends_with(':')
2992            || trimmed.ends_with('(')
2993            || trimmed.ends_with('[')
2994            || (matches!(self.language, Language::XmlSdf | Language::Html)
2995                && trimmed.ends_with('>')
2996                && !trimmed.ends_with("/>")
2997                && !trimmed.starts_with("</")
2998                && !trimmed.starts_with("<?")
2999                && !trimmed.starts_with("<!--"))
3000            || (self.language == Language::Shell
3001                && (trimmed.ends_with("then")
3002                    || trimmed.ends_with("do")
3003                    || trimmed.ends_with("else")))
3004        {
3005            current_indent + indent_step
3006        } else {
3007            current_indent
3008        }
3009    }
3010}
3011
3012// ---------------------------------------------------------------------------
3013// Helpers & Language-Specific Fold / Validator Implementations
3014// ---------------------------------------------------------------------------
3015
3016fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
3017    if needle.is_empty() || needle.len() > haystack.len() {
3018        return None;
3019    }
3020    haystack.windows(needle.len()).position(|w| w == needle)
3021}
3022
3023fn find_rust_raw_string_end(bytes: &[u8], mut i: usize, hashes: u8) -> Option<usize> {
3024    while i < bytes.len() {
3025        if bytes[i] == b'"' {
3026            let mut h = 0u8;
3027            while h < hashes && i + 1 + (h as usize) < bytes.len() && bytes[i + 1 + h as usize] == b'#' {
3028                h += 1;
3029            }
3030            if h == hashes {
3031                return Some(i + 1 + hashes as usize);
3032            }
3033        }
3034        i += 1;
3035    }
3036    None
3037}
3038
3039fn find_yaml_mapping_colon(slice: &str) -> Option<usize> {
3040    let bytes = slice.as_bytes();
3041    let mut in_single = false;
3042    let mut in_double = false;
3043    for (i, &b) in bytes.iter().enumerate() {
3044        if b == b'\'' && !in_double {
3045            in_single = !in_single;
3046        } else if b == b'"' && !in_single {
3047            in_double = !in_double;
3048        } else if !in_single && !in_double {
3049            if b == b'#' {
3050                return None;
3051            }
3052            if b == b':' && bytes.get(i + 1).is_none_or(|nb| nb.is_ascii_whitespace()) {
3053                return Some(i);
3054            }
3055        }
3056    }
3057    None
3058}
3059
3060fn is_numeric_literal(word: &str) -> bool {
3061    if word.is_empty() {
3062        return false;
3063    }
3064    let s = word.strip_prefix('-').or_else(|| word.strip_prefix('+')).unwrap_or(word);
3065    if s.is_empty() {
3066        return false;
3067    }
3068    let mut has_digit = false;
3069    for b in s.bytes() {
3070        if b.is_ascii_digit() {
3071            has_digit = true;
3072        } else if !matches!(b, b'.' | b'_' | b'e' | b'E' | b'+' | b'-' | b'x' | b'X' | b'a'..=b'f' | b'A'..=b'F') {
3073            return false;
3074        }
3075    }
3076    has_digit
3077}
3078
3079fn compute_brace_fold_ranges(buffer: &LineBuffer, include_brackets: bool) -> Vec<FoldRange> {
3080    let mut ranges = Vec::new();
3081    let mut brace_stack = Vec::new();
3082    let mut bracket_stack = Vec::new();
3083
3084    for l in 0..buffer.line_count() {
3085        if let Some(text) = buffer.line(l) {
3086            let mut in_str: Option<char> = None;
3087            let mut prev_esc = false;
3088            for ch in text.chars() {
3089                if let Some(q) = in_str {
3090                    if prev_esc {
3091                        prev_esc = false;
3092                    } else if ch == '\\' {
3093                        prev_esc = true;
3094                    } else if ch == q {
3095                        in_str = None;
3096                    }
3097                    continue;
3098                }
3099                match ch {
3100                    '"' | '\'' => in_str = Some(ch),
3101                    '{' => brace_stack.push(l),
3102                    '}' => {
3103                        if let Some(start_l) = brace_stack.pop() {
3104                            if l > start_l {
3105                                ranges.push(FoldRange {
3106                                    start_line: start_l,
3107                                    end_line: l,
3108                                    collapsed: false,
3109                                });
3110                            }
3111                        }
3112                    }
3113                    '[' if include_brackets => bracket_stack.push(l),
3114                    ']' if include_brackets => {
3115                        if let Some(start_l) = bracket_stack.pop() {
3116                            if l > start_l {
3117                                ranges.push(FoldRange {
3118                                    start_line: start_l,
3119                                    end_line: l,
3120                                    collapsed: false,
3121                                });
3122                            }
3123                        }
3124                    }
3125                    _ => {}
3126                }
3127            }
3128        }
3129    }
3130    ranges
3131}
3132
3133fn compute_cpp_preproc_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3134    let mut ranges = Vec::new();
3135    let mut stack = Vec::new();
3136    for l in 0..buffer.line_count() {
3137        if let Some(text) = buffer.line(l) {
3138            let trimmed = text.trim_start();
3139            if trimmed.starts_with("#if") {
3140                stack.push(l);
3141            } else if trimmed.starts_with("#endif") {
3142                if let Some(start_l) = stack.pop() {
3143                    if l > start_l {
3144                        ranges.push(FoldRange {
3145                            start_line: start_l,
3146                            end_line: l,
3147                            collapsed: false,
3148                        });
3149                    }
3150                }
3151            }
3152        }
3153    }
3154    ranges
3155}
3156
3157fn compute_indent_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3158    let n = buffer.line_count();
3159    let mut ranges = Vec::new();
3160    let mut non_empty: Vec<(usize, usize)> = Vec::new();
3161
3162    for l in 0..n {
3163        if let Some(text) = buffer.line(l) {
3164            let trimmed = text.trim();
3165            if trimmed.is_empty() || trimmed.starts_with('#') {
3166                continue;
3167            }
3168            let indent = text.bytes().take_while(|&b| b == b' ' || b == b'\t').count();
3169            non_empty.push((l, indent));
3170        }
3171    }
3172
3173    for idx in 0..non_empty.len() {
3174        let (start_line, base_indent) = non_empty[idx];
3175        let mut last_child = start_line;
3176        for &(cand_line, cand_indent) in &non_empty[idx + 1..] {
3177            if cand_indent > base_indent {
3178                last_child = cand_line;
3179            } else {
3180                break;
3181            }
3182        }
3183        if last_child > start_line {
3184            ranges.push(FoldRange {
3185                start_line,
3186                end_line: last_child,
3187                collapsed: false,
3188            });
3189        }
3190    }
3191    ranges
3192}
3193
3194fn compute_toml_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3195    let mut ranges = Vec::new();
3196    let mut headers = Vec::new();
3197    let n = buffer.line_count();
3198    for l in 0..n {
3199        if let Some(text) = buffer.line(l) {
3200            let trimmed = text.trim();
3201            if trimmed.starts_with('[') && trimmed.contains(']') {
3202                headers.push(l);
3203            }
3204        }
3205    }
3206    for (idx, &start_l) in headers.iter().enumerate() {
3207        let next_start = headers.get(idx + 1).copied().unwrap_or(n);
3208        let mut end_l = next_start.saturating_sub(1);
3209        while end_l > start_l && buffer.line(end_l).is_some_and(|s| s.trim().is_empty()) {
3210            end_l -= 1;
3211        }
3212        if end_l > start_l {
3213            ranges.push(FoldRange {
3214                start_line: start_l,
3215                end_line: end_l,
3216                collapsed: false,
3217            });
3218        }
3219    }
3220    ranges
3221}
3222
3223fn compute_xml_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3224    let mut ranges = Vec::new();
3225    let mut stack: Vec<(String, usize)> = Vec::new();
3226    for l in 0..buffer.line_count() {
3227        if let Some(text) = buffer.line(l) {
3228            let mut i = 0;
3229            let bytes = text.as_bytes();
3230            while i < bytes.len() {
3231                if bytes[i] == b'<' {
3232                    if bytes[i..].starts_with(b"<!--") {
3233                        if let Some(rel) = find_bytes(&bytes[i + 4..], b"-->") {
3234                            i += 4 + rel + 3;
3235                            continue;
3236                        } else {
3237                            break;
3238                        }
3239                    }
3240                    if bytes.get(i + 1) == Some(&b'/') {
3241                        let name_start = i + 2;
3242                        let mut name_end = name_start;
3243                        while name_end < bytes.len()
3244                            && !bytes[name_end].is_ascii_whitespace()
3245                            && bytes[name_end] != b'>'
3246                        {
3247                            name_end += 1;
3248                        }
3249                        let close_name = &text[name_start..name_end];
3250                        if let Some(pos) = stack.iter().rposition(|(n, _)| n == close_name) {
3251                            let (_, start_l) = stack.remove(pos);
3252                            if l > start_l {
3253                                ranges.push(FoldRange {
3254                                    start_line: start_l,
3255                                    end_line: l,
3256                                    collapsed: false,
3257                                });
3258                            }
3259                        }
3260                        i = name_end;
3261                        continue;
3262                    } else if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
3263                    {
3264                        let name_start = i + 1;
3265                        let mut name_end = name_start;
3266                        while name_end < bytes.len()
3267                            && (bytes[name_end].is_ascii_alphanumeric()
3268                                || matches!(bytes[name_end], b'_' | b'-' | b':' | b'.'))
3269                        {
3270                            name_end += 1;
3271                        }
3272                        let tag_name = text[name_start..name_end].to_string();
3273                        if let Some(gt_rel) = text[name_end..].find('>') {
3274                            let gt_abs = name_end + gt_rel;
3275                            let self_closing = gt_abs > 0 && bytes[gt_abs - 1] == b'/';
3276                            if !self_closing {
3277                                stack.push((tag_name, l));
3278                            }
3279                            i = gt_abs + 1;
3280                            continue;
3281                        } else {
3282                            stack.push((tag_name, l));
3283                        }
3284                    }
3285                }
3286                i += 1;
3287            }
3288        }
3289    }
3290    ranges
3291}
3292
3293fn validate_xml_tags(buffer: &LineBuffer, out: &mut Vec<SyntaxDiagnostic>) {
3294    let mut stack: Vec<(String, usize, usize)> = Vec::new();
3295    let mut in_comment = false;
3296    for l in 0..buffer.line_count() {
3297        let Some(text) = buffer.line(l) else {
3298            continue;
3299        };
3300        let bytes = text.as_bytes();
3301        let mut i = 0;
3302        while i < bytes.len() {
3303            if in_comment {
3304                if let Some(rel) = find_bytes(&bytes[i..], b"-->") {
3305                    i += rel + 3;
3306                    in_comment = false;
3307                } else {
3308                    break;
3309                }
3310                continue;
3311            }
3312            if bytes[i..].starts_with(b"<!--") {
3313                if let Some(rel) = find_bytes(&bytes[i + 4..], b"-->") {
3314                    i += 4 + rel + 3;
3315                } else {
3316                    in_comment = true;
3317                    break;
3318                }
3319                continue;
3320            }
3321            if bytes[i] == b'<' {
3322                if bytes.get(i + 1) == Some(&b'/') {
3323                    let ns = i + 2;
3324                    let mut ne = ns;
3325                    while ne < bytes.len() && !bytes[ne].is_ascii_whitespace() && bytes[ne] != b'>' {
3326                        ne += 1;
3327                    }
3328                    let close_name = &text[ns..ne];
3329                    if let Some((open_name, _, _)) = stack.last() {
3330                        if open_name == close_name {
3331                            stack.pop();
3332                        } else {
3333                            out.push(SyntaxDiagnostic {
3334                                start: Position::new(l, i),
3335                                end: Position::new(l, (ne + 1).min(bytes.len())),
3336                                message: format!(
3337                                    "Mismatched closing tag `</{close_name}>`, expected `</{open_name}>`"
3338                                ),
3339                                is_warning: false,
3340                            });
3341                            if let Some(pos) = stack.iter().rposition(|(n, _, _)| n == close_name) {
3342                                stack.truncate(pos);
3343                            }
3344                        }
3345                    } else {
3346                        out.push(SyntaxDiagnostic {
3347                            start: Position::new(l, i),
3348                            end: Position::new(l, (ne + 1).min(bytes.len())),
3349                            message: format!("Unexpected closing tag `</{close_name}>`"),
3350                            is_warning: false,
3351                        });
3352                    }
3353                    i = ne;
3354                    continue;
3355                } else if bytes.get(i + 1).is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_') {
3356                    let ns = i + 1;
3357                    let mut ne = ns;
3358                    while ne < bytes.len()
3359                        && (bytes[ne].is_ascii_alphanumeric()
3360                            || matches!(bytes[ne], b'_' | b'-' | b':' | b'.'))
3361                    {
3362                        ne += 1;
3363                    }
3364                    let tag_name = text[ns..ne].to_string();
3365                    if let Some(gt_rel) = text[ne..].find('>') {
3366                        let gt_abs = ne + gt_rel;
3367                        if gt_abs == 0 || bytes[gt_abs - 1] != b'/' {
3368                            stack.push((tag_name, l, i));
3369                        }
3370                        i = gt_abs + 1;
3371                        continue;
3372                    }
3373                }
3374            }
3375            i += 1;
3376        }
3377    }
3378    for (name, line, col) in stack {
3379        out.push(SyntaxDiagnostic {
3380            start: Position::new(line, col),
3381            end: Position::new(line, col + name.len() + 1),
3382            message: format!("Unclosed XML/SDF tag `<{name}>`"),
3383            is_warning: false,
3384        });
3385    }
3386}
3387
3388fn compute_markdown_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3389    let n = buffer.line_count();
3390    let mut ranges = Vec::new();
3391    let mut heading_stack: Vec<(usize, usize)> = Vec::new(); // (level, line)
3392    let mut fence_open: Option<(u8, usize, usize)> = None; // (char, len, start_line)
3393
3394    for l in 0..n {
3395        let Some(text) = buffer.line(l) else {
3396            continue;
3397        };
3398        let trimmed = text.trim_start();
3399        if let Some((fc, fl, start_l)) = fence_open {
3400            let run = trimmed.bytes().take_while(|&b| b == fc).count();
3401            if run >= fl && trimmed[run..].trim().is_empty() {
3402                if l > start_l {
3403                    ranges.push(FoldRange {
3404                        start_line: start_l,
3405                        end_line: l,
3406                        collapsed: false,
3407                    });
3408                }
3409                fence_open = None;
3410            }
3411            continue;
3412        }
3413        if trimmed.starts_with("```") || trimmed.starts_with("~~~") {
3414            let fc = trimmed.as_bytes()[0];
3415            let fl = trimmed.bytes().take_while(|&b| b == fc).count();
3416            fence_open = Some((fc, fl, l));
3417            continue;
3418        }
3419        if trimmed.starts_with('#') {
3420            let lvl = trimmed.bytes().take_while(|&b| b == b'#').count();
3421            if (1..=6).contains(&lvl) && trimmed.as_bytes().get(lvl).is_none_or(|&b| b == b' ') {
3422                while let Some(&(prev_lvl, start_l)) = heading_stack.last() {
3423                    if prev_lvl >= lvl {
3424                        heading_stack.pop();
3425                        let end_l = l.saturating_sub(1);
3426                        if end_l > start_l {
3427                            ranges.push(FoldRange {
3428                                start_line: start_l,
3429                                end_line: end_l,
3430                                collapsed: false,
3431                            });
3432                        }
3433                    } else {
3434                        break;
3435                    }
3436                }
3437                heading_stack.push((lvl, l));
3438            }
3439        }
3440    }
3441    for (_, start_l) in heading_stack {
3442        let end_l = n.saturating_sub(1);
3443        if end_l > start_l {
3444            ranges.push(FoldRange {
3445                start_line: start_l,
3446                end_line: end_l,
3447                collapsed: false,
3448            });
3449        }
3450    }
3451    ranges
3452}
3453
3454fn compute_shell_fold_ranges(buffer: &LineBuffer) -> Vec<FoldRange> {
3455    let mut ranges = compute_brace_fold_ranges(buffer, false);
3456    let mut if_stack = Vec::new();
3457    let mut loop_stack = Vec::new();
3458    let mut case_stack = Vec::new();
3459
3460    for l in 0..buffer.line_count() {
3461        let Some(text) = buffer.line(l) else {
3462            continue;
3463        };
3464        let trimmed = text.trim();
3465        let first = trimmed.split_whitespace().next().unwrap_or("");
3466        match first {
3467            "if" => if_stack.push(l),
3468            "fi" => {
3469                if let Some(s) = if_stack.pop() {
3470                    if l > s {
3471                        ranges.push(FoldRange {
3472                            start_line: s,
3473                            end_line: l,
3474                            collapsed: false,
3475                        });
3476                    }
3477                }
3478            }
3479            "for" | "while" | "until" => loop_stack.push(l),
3480            "done" => {
3481                if let Some(s) = loop_stack.pop() {
3482                    if l > s {
3483                        ranges.push(FoldRange {
3484                            start_line: s,
3485                            end_line: l,
3486                            collapsed: false,
3487                        });
3488                    }
3489                }
3490            }
3491            "case" => case_stack.push(l),
3492            "esac" => {
3493                if let Some(s) = case_stack.pop() {
3494                    if l > s {
3495                        ranges.push(FoldRange {
3496                            start_line: s,
3497                            end_line: l,
3498                            collapsed: false,
3499                        });
3500                    }
3501                }
3502            }
3503            _ => {}
3504        }
3505    }
3506    ranges
3507}