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