Skip to main content

fc_ui/capabilities/editor/
editor.rs

1//! Editor state, editing commands, syntax integration, and rendering glue.
2//!
3//! `EditorState` intentionally remains the compatibility-facing façade for now,
4//! but its state falls into several distinct responsibility groups:
5//!
6//! - document text, cursor/selection, and undo/redo history;
7//! - file loading and saving;
8//! - syntax parsing, highlighting, and fold ranges;
9//! - search and replace;
10//! - layout, scrolling, blinking, and pointer interaction; and
11//! - GPUI input handling and rendering coordination.
12//!
13//! The main invariants to preserve during future extraction are:
14//!
15//! 1. `rope` always contains a trailing newline (including an empty document).
16//! 2. Cursor and selection byte offsets are always clamped to UTF-8 boundaries.
17//! 3. A content or language change invalidates older asynchronous parse results.
18//! 4. A content change invalidates older asynchronous search results.
19//! 5. Replacing a selection or all search matches is one undoable operation.
20//! 6. Fold ranges and index-keyed layout caches are migrated or invalidated when
21//!    edits change line structure.
22//!
23//! Future refactoring should extract low-coupling state first (`BlinkState`,
24//! `SearchState`, and `InteractionState`), while keeping `EditorState` as the
25//! public façade. The document/editing core and the render snapshot should only
26//! be split after the behavior tests below cover their current contracts.
27
28use crate::capabilities::foundation::icon_config::resolve_icon_path;
29use crate::capabilities::foundation::theme::use_theme;
30use crate::capabilities::scroll::scrollable::scrollable_vertical;
31use gpui::{prelude::FluentBuilder as _, *};
32use regex::Regex;
33use ropey::Rope;
34use smol::Timer;
35use std::cmp::min;
36use std::collections::HashMap;
37use std::ops::Range;
38use std::path::PathBuf;
39use std::rc::Rc;
40use std::time::Duration;
41use tree_sitter::{
42    InputEdit, Parser, Point as TSPoint, Query, QueryCursor, StreamingIterator, Tree,
43};
44
45actions!(
46    editor,
47    [
48        MoveUp,
49        MoveDown,
50        MoveLeft,
51        MoveRight,
52        MoveToLineStart,
53        MoveToLineEnd,
54        MoveToDocStart,
55        MoveToDocEnd,
56        MoveWordLeft,
57        MoveWordRight,
58        PageUp,
59        PageDown,
60        SelectUp,
61        SelectDown,
62        SelectLeft,
63        SelectRight,
64        SelectToLineStart,
65        SelectToLineEnd,
66        SelectAll,
67        Backspace,
68        Delete,
69        DeleteWord,
70        Enter,
71        Tab,
72        Copy,
73        Cut,
74        Paste,
75        Undo,
76        Redo,
77    ]
78);
79
80pub fn init(cx: &mut App) {
81    if !crate::capabilities::foundation::initialization::begin(cx, "editor") {
82        return;
83    }
84    cx.bind_keys([
85        KeyBinding::new("up", MoveUp, Some("Editor")),
86        KeyBinding::new("down", MoveDown, Some("Editor")),
87        KeyBinding::new("left", MoveLeft, Some("Editor")),
88        KeyBinding::new("right", MoveRight, Some("Editor")),
89        KeyBinding::new("home", MoveToLineStart, Some("Editor")),
90        KeyBinding::new("end", MoveToLineEnd, Some("Editor")),
91        #[cfg(target_os = "macos")]
92        KeyBinding::new("alt-left", MoveWordLeft, Some("Editor")),
93        #[cfg(not(target_os = "macos"))]
94        KeyBinding::new("ctrl-left", MoveWordLeft, Some("Editor")),
95        #[cfg(target_os = "macos")]
96        KeyBinding::new("alt-right", MoveWordRight, Some("Editor")),
97        #[cfg(not(target_os = "macos"))]
98        KeyBinding::new("ctrl-right", MoveWordRight, Some("Editor")),
99        #[cfg(target_os = "macos")]
100        KeyBinding::new("cmd-up", MoveToDocStart, Some("Editor")),
101        #[cfg(not(target_os = "macos"))]
102        KeyBinding::new("ctrl-home", MoveToDocStart, Some("Editor")),
103        #[cfg(target_os = "macos")]
104        KeyBinding::new("cmd-down", MoveToDocEnd, Some("Editor")),
105        #[cfg(not(target_os = "macos"))]
106        KeyBinding::new("ctrl-end", MoveToDocEnd, Some("Editor")),
107        KeyBinding::new("pageup", PageUp, Some("Editor")),
108        KeyBinding::new("pagedown", PageDown, Some("Editor")),
109        KeyBinding::new("shift-up", SelectUp, Some("Editor")),
110        KeyBinding::new("shift-down", SelectDown, Some("Editor")),
111        KeyBinding::new("shift-left", SelectLeft, Some("Editor")),
112        KeyBinding::new("shift-right", SelectRight, Some("Editor")),
113        KeyBinding::new("shift-home", SelectToLineStart, Some("Editor")),
114        KeyBinding::new("shift-end", SelectToLineEnd, Some("Editor")),
115        #[cfg(target_os = "macos")]
116        KeyBinding::new("cmd-a", SelectAll, Some("Editor")),
117        #[cfg(not(target_os = "macos"))]
118        KeyBinding::new("ctrl-a", SelectAll, Some("Editor")),
119        KeyBinding::new("backspace", Backspace, Some("Editor")),
120        KeyBinding::new("delete", Delete, Some("Editor")),
121        #[cfg(target_os = "macos")]
122        KeyBinding::new("alt-backspace", DeleteWord, Some("Editor")),
123        #[cfg(not(target_os = "macos"))]
124        KeyBinding::new("ctrl-backspace", DeleteWord, Some("Editor")),
125        KeyBinding::new("enter", Enter, Some("Editor")),
126        KeyBinding::new("tab", Tab, Some("Editor")),
127        #[cfg(target_os = "macos")]
128        KeyBinding::new("cmd-c", Copy, Some("Editor")),
129        #[cfg(not(target_os = "macos"))]
130        KeyBinding::new("ctrl-c", Copy, Some("Editor")),
131        #[cfg(target_os = "macos")]
132        KeyBinding::new("cmd-x", Cut, Some("Editor")),
133        #[cfg(not(target_os = "macos"))]
134        KeyBinding::new("ctrl-x", Cut, Some("Editor")),
135        #[cfg(target_os = "macos")]
136        KeyBinding::new("cmd-v", Paste, Some("Editor")),
137        #[cfg(not(target_os = "macos"))]
138        KeyBinding::new("ctrl-v", Paste, Some("Editor")),
139        #[cfg(target_os = "macos")]
140        KeyBinding::new("cmd-z", Undo, Some("Editor")),
141        #[cfg(not(target_os = "macos"))]
142        KeyBinding::new("ctrl-z", Undo, Some("Editor")),
143        #[cfg(target_os = "macos")]
144        KeyBinding::new("cmd-shift-z", Redo, Some("Editor")),
145        #[cfg(not(target_os = "macos"))]
146        KeyBinding::new("ctrl-shift-z", Redo, Some("Editor")),
147    ]);
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
151pub struct Position {
152    pub line: usize,
153    pub col: usize,
154}
155
156impl Position {
157    pub fn new(line: usize, col: usize) -> Self {
158        Self { line, col }
159    }
160
161    pub fn zero() -> Self {
162        Self { line: 0, col: 0 }
163    }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167pub struct Selection {
168    pub anchor: Position,
169    pub cursor: Position,
170}
171
172impl Selection {
173    pub fn new(anchor: Position, cursor: Position) -> Self {
174        Self { anchor, cursor }
175    }
176
177    pub fn is_empty(&self) -> bool {
178        self.anchor == self.cursor
179    }
180
181    pub fn range(&self) -> (Position, Position) {
182        if self.anchor <= self.cursor {
183            (self.anchor, self.cursor)
184        } else {
185            (self.cursor, self.anchor)
186        }
187    }
188}
189
190#[derive(Debug, Clone)]
191enum EditOp {
192    Insert {
193        byte_offset: usize,
194        text: String,
195    },
196    Delete {
197        byte_offset: usize,
198        text: String,
199    },
200    /// A single user action made up of several primitive edits, such as
201    /// replacing a selection or replacing all search matches. Keeping the
202    /// primitives together makes one undo restore the complete prior value.
203    Batch(Vec<EditOp>),
204}
205
206#[derive(Debug, Clone, Copy)]
207struct TextEditRange {
208    start: usize,
209    old_end: usize,
210    new_end: usize,
211}
212
213impl TextEditRange {
214    fn shift_offset_after_edit(self, offset: usize) -> usize {
215        self.new_end
216            .saturating_add(offset.saturating_sub(self.old_end))
217    }
218
219    fn map_cursor_offset(self, offset: usize) -> usize {
220        if offset <= self.start {
221            offset
222        } else if offset >= self.old_end {
223            self.shift_offset_after_edit(offset)
224        } else {
225            self.new_end
226        }
227    }
228
229    fn map_selection_offsets(self, anchor: usize, cursor: usize) -> (usize, usize) {
230        if anchor == cursor {
231            let mapped = self.map_cursor_offset(anchor);
232            return (mapped, mapped);
233        }
234
235        let reversed = anchor > cursor;
236        let (start, end) = if reversed {
237            (cursor, anchor)
238        } else {
239            (anchor, cursor)
240        };
241
242        let mapped_start = if start < self.start {
243            start
244        } else if start >= self.old_end {
245            self.shift_offset_after_edit(start)
246        } else {
247            self.start
248        };
249        let mapped_end = if end <= self.start {
250            end
251        } else if end >= self.old_end {
252            self.shift_offset_after_edit(end)
253        } else {
254            self.new_end
255        };
256
257        if reversed {
258            (mapped_end, mapped_start)
259        } else {
260            (mapped_start, mapped_end)
261        }
262    }
263}
264
265#[derive(Debug, Clone, Copy)]
266struct LineEditRange {
267    start_line: usize,
268    old_end_line: usize,
269    new_end_line: usize,
270}
271
272impl LineEditRange {
273    fn shift_line(self, line: usize) -> usize {
274        if self.new_end_line >= self.old_end_line {
275            line.saturating_add(self.new_end_line - self.old_end_line)
276        } else {
277            line.saturating_sub(self.old_end_line - self.new_end_line)
278        }
279    }
280
281    fn map_fold_range(self, range: FoldRange) -> Option<FoldRange> {
282        if self.start_line == self.old_end_line {
283            if range.end_line < self.start_line {
284                Some(range)
285            } else if range.start_line > self.start_line {
286                Some(FoldRange {
287                    start_line: self.shift_line(range.start_line),
288                    end_line: self.shift_line(range.end_line),
289                })
290            } else {
291                None
292            }
293        } else if range.end_line < self.start_line {
294            Some(range)
295        } else if range.start_line >= self.old_end_line {
296            Some(FoldRange {
297                start_line: self.shift_line(range.start_line),
298                end_line: self.shift_line(range.end_line),
299            })
300        } else {
301            None
302        }
303    }
304}
305
306#[derive(Debug, Clone, Copy)]
307struct PositionSnapshot {
308    cursor_offset: usize,
309    selection_offsets: Option<(usize, usize)>,
310}
311
312#[derive(Debug, Clone, Copy)]
313struct TextEditPlan {
314    range: TextEditRange,
315    old_end_position: TSPoint,
316    start_line: usize,
317    old_end_line: usize,
318}
319
320impl TextEditPlan {
321    fn new(editor: &EditorState, start: usize, old_end: usize, new_end: usize) -> Self {
322        Self {
323            range: TextEditRange {
324                start,
325                old_end,
326                new_end,
327            },
328            old_end_position: editor.byte_to_ts_point(old_end),
329            start_line: editor.line_at_byte(start),
330            old_end_line: editor.line_at_byte(old_end),
331        }
332    }
333
334    fn line_edit_range(self, editor: &EditorState) -> LineEditRange {
335        LineEditRange {
336            start_line: self.start_line,
337            old_end_line: self.old_end_line,
338            new_end_line: editor.line_at_byte(self.range.new_end),
339        }
340    }
341}
342
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub struct FoldRange {
345    pub start_line: usize,
346    pub end_line: usize,
347}
348
349const AUTO_CLOSE_PAIRS: &[(char, char)] = &[
350    ('(', ')'),
351    ('[', ']'),
352    ('{', '}'),
353    ('"', '"'),
354    ('\'', '\''),
355    ('`', '`'),
356];
357
358fn floor_char_boundary(text: &str, index: usize) -> usize {
359    if index >= text.len() {
360        return text.len();
361    }
362    let mut index = index;
363    while !text.is_char_boundary(index) {
364        index -= 1;
365    }
366    index
367}
368
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
370pub enum Language {
371    Rust,
372    JavaScript,
373    TypeScript,
374    Python,
375    Json,
376    Toml,
377    Markdown,
378    Go,
379    C,
380    Cpp,
381    Java,
382    Ruby,
383    Bash,
384    Css,
385    Html,
386    Yaml,
387    Lua,
388    Zig,
389    Scala,
390    Php,
391    OCaml,
392    Sql,
393    Plain,
394}
395
396impl Language {
397    pub fn from_extension(ext: &str) -> Self {
398        match ext.to_lowercase().as_str() {
399            "rs" => Language::Rust,
400            "js" | "jsx" | "mjs" | "cjs" => Language::JavaScript,
401            "ts" | "tsx" => Language::TypeScript,
402            "py" | "pyi" => Language::Python,
403            "json" | "jsonc" => Language::Json,
404            "toml" => Language::Toml,
405            "md" | "markdown" => Language::Markdown,
406            "go" => Language::Go,
407            "c" | "h" => Language::C,
408            "cpp" | "cxx" | "cc" | "hpp" | "hxx" | "hh" => Language::Cpp,
409            "java" => Language::Java,
410            "rb" | "rake" | "gemspec" => Language::Ruby,
411            "sh" | "bash" | "zsh" => Language::Bash,
412            "css" => Language::Css,
413            "html" | "htm" => Language::Html,
414            "yml" | "yaml" => Language::Yaml,
415            "lua" => Language::Lua,
416            "zig" => Language::Zig,
417            "scala" | "sc" => Language::Scala,
418            "php" => Language::Php,
419            "ml" | "mli" => Language::OCaml,
420            "sql" => Language::Sql,
421            _ => Language::Plain,
422        }
423    }
424
425    pub fn from_path(path: &std::path::Path) -> Self {
426        path.extension()
427            .and_then(|ext| ext.to_str())
428            .map(Self::from_extension)
429            .unwrap_or(Language::Plain)
430    }
431
432    pub fn display_name(&self) -> &'static str {
433        match self {
434            Language::Rust => "Rust",
435            Language::JavaScript => "JavaScript",
436            Language::TypeScript => "TypeScript",
437            Language::Python => "Python",
438            Language::Json => "JSON",
439            Language::Toml => "TOML",
440            Language::Markdown => "Markdown",
441            Language::Go => "Go",
442            Language::C => "C",
443            Language::Cpp => "C++",
444            Language::Java => "Java",
445            Language::Ruby => "Ruby",
446            Language::Bash => "Shell",
447            Language::Css => "CSS",
448            Language::Html => "HTML",
449            Language::Yaml => "YAML",
450            Language::Lua => "Lua",
451            Language::Zig => "Zig",
452            Language::Scala => "Scala",
453            Language::Php => "PHP",
454            Language::OCaml => "OCaml",
455            Language::Sql => "SQL",
456            Language::Plain => "Plain Text",
457        }
458    }
459
460    pub fn tree_sitter_language(&self) -> Option<tree_sitter::Language> {
461        match self {
462            #[cfg(feature = "tree-sitter-rust")]
463            Language::Rust => Some(tree_sitter_rust::LANGUAGE.into()),
464            #[cfg(feature = "tree-sitter-javascript")]
465            Language::JavaScript => Some(tree_sitter_javascript::LANGUAGE.into()),
466            #[cfg(feature = "tree-sitter-typescript")]
467            Language::TypeScript => Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
468            #[cfg(all(
469                feature = "tree-sitter-javascript",
470                not(feature = "tree-sitter-typescript")
471            ))]
472            Language::TypeScript => Some(tree_sitter_javascript::LANGUAGE.into()),
473            #[cfg(feature = "tree-sitter-python")]
474            Language::Python => Some(tree_sitter_python::LANGUAGE.into()),
475            #[cfg(feature = "tree-sitter-json")]
476            Language::Json => Some(tree_sitter_json::LANGUAGE.into()),
477            #[cfg(feature = "tree-sitter-toml-ng")]
478            Language::Toml => Some(tree_sitter_toml_ng::language()),
479            #[cfg(feature = "tree-sitter-md")]
480            Language::Markdown => Some(tree_sitter_md::LANGUAGE.into()),
481            #[cfg(feature = "tree-sitter-go")]
482            Language::Go => Some(tree_sitter_go::LANGUAGE.into()),
483            #[cfg(feature = "tree-sitter-c")]
484            Language::C => Some(tree_sitter_c::LANGUAGE.into()),
485            #[cfg(feature = "tree-sitter-cpp")]
486            Language::Cpp => Some(tree_sitter_cpp::LANGUAGE.into()),
487            #[cfg(feature = "tree-sitter-java")]
488            Language::Java => Some(tree_sitter_java::LANGUAGE.into()),
489            #[cfg(feature = "tree-sitter-ruby")]
490            Language::Ruby => Some(tree_sitter_ruby::LANGUAGE.into()),
491            #[cfg(feature = "tree-sitter-bash")]
492            Language::Bash => Some(tree_sitter_bash::LANGUAGE.into()),
493            #[cfg(feature = "tree-sitter-css")]
494            Language::Css => Some(tree_sitter_css::LANGUAGE.into()),
495            #[cfg(feature = "tree-sitter-html")]
496            Language::Html => Some(tree_sitter_html::LANGUAGE.into()),
497            #[cfg(feature = "tree-sitter-yaml")]
498            Language::Yaml => Some(tree_sitter_yaml::LANGUAGE.into()),
499            #[cfg(feature = "tree-sitter-lua")]
500            Language::Lua => Some(tree_sitter_lua::LANGUAGE.into()),
501            #[cfg(feature = "tree-sitter-zig")]
502            Language::Zig => Some(tree_sitter_zig::LANGUAGE.into()),
503            #[cfg(feature = "tree-sitter-scala")]
504            Language::Scala => Some(tree_sitter_scala::LANGUAGE.into()),
505            #[cfg(feature = "tree-sitter-php")]
506            Language::Php => Some(tree_sitter_php::LANGUAGE_PHP.into()),
507            #[cfg(feature = "tree-sitter-ocaml")]
508            Language::OCaml => Some(tree_sitter_ocaml::LANGUAGE_OCAML.into()),
509            #[cfg(feature = "tree-sitter-sequel")]
510            Language::Sql => Some(tree_sitter_sequel::LANGUAGE.into()),
511            _ => None,
512        }
513    }
514
515    pub fn highlight_query_source(&self) -> Option<std::borrow::Cow<'static, str>> {
516        match self {
517            #[cfg(feature = "tree-sitter-rust")]
518            Language::Rust => Some(tree_sitter_rust::HIGHLIGHTS_QUERY.into()),
519            #[cfg(feature = "tree-sitter-javascript")]
520            Language::JavaScript => Some(tree_sitter_javascript::HIGHLIGHT_QUERY.into()),
521            #[cfg(all(feature = "tree-sitter-typescript", feature = "tree-sitter-javascript"))]
522            Language::TypeScript => {
523                let combined = format!(
524                    "{}\n{}",
525                    tree_sitter_javascript::HIGHLIGHT_QUERY,
526                    tree_sitter_typescript::HIGHLIGHTS_QUERY
527                );
528                Some(combined.into())
529            }
530            #[cfg(all(
531                feature = "tree-sitter-typescript",
532                not(feature = "tree-sitter-javascript")
533            ))]
534            Language::TypeScript => Some(tree_sitter_typescript::HIGHLIGHTS_QUERY.into()),
535            #[cfg(all(
536                feature = "tree-sitter-javascript",
537                not(feature = "tree-sitter-typescript")
538            ))]
539            Language::TypeScript => Some(tree_sitter_javascript::HIGHLIGHT_QUERY.into()),
540            #[cfg(feature = "tree-sitter-python")]
541            Language::Python => Some(tree_sitter_python::HIGHLIGHTS_QUERY.into()),
542            #[cfg(feature = "tree-sitter-json")]
543            Language::Json => Some(tree_sitter_json::HIGHLIGHTS_QUERY.into()),
544            #[cfg(feature = "tree-sitter-toml-ng")]
545            Language::Toml => Some(tree_sitter_toml_ng::HIGHLIGHTS_QUERY.into()),
546            #[cfg(feature = "tree-sitter-md")]
547            Language::Markdown => Some(tree_sitter_md::HIGHLIGHT_QUERY_BLOCK.into()),
548            #[cfg(feature = "tree-sitter-go")]
549            Language::Go => Some(tree_sitter_go::HIGHLIGHTS_QUERY.into()),
550            #[cfg(feature = "tree-sitter-c")]
551            Language::C => Some(tree_sitter_c::HIGHLIGHT_QUERY.into()),
552            #[cfg(all(feature = "tree-sitter-cpp", feature = "tree-sitter-c"))]
553            Language::Cpp => {
554                let combined = format!(
555                    "{}\n{}",
556                    tree_sitter_c::HIGHLIGHT_QUERY,
557                    tree_sitter_cpp::HIGHLIGHT_QUERY
558                );
559                Some(combined.into())
560            }
561            #[cfg(all(feature = "tree-sitter-cpp", not(feature = "tree-sitter-c")))]
562            Language::Cpp => Some(tree_sitter_cpp::HIGHLIGHT_QUERY.into()),
563            #[cfg(feature = "tree-sitter-java")]
564            Language::Java => Some(tree_sitter_java::HIGHLIGHTS_QUERY.into()),
565            #[cfg(feature = "tree-sitter-ruby")]
566            Language::Ruby => Some(tree_sitter_ruby::HIGHLIGHTS_QUERY.into()),
567            #[cfg(feature = "tree-sitter-bash")]
568            Language::Bash => Some(tree_sitter_bash::HIGHLIGHT_QUERY.into()),
569            #[cfg(feature = "tree-sitter-css")]
570            Language::Css => Some(tree_sitter_css::HIGHLIGHTS_QUERY.into()),
571            #[cfg(feature = "tree-sitter-html")]
572            Language::Html => Some(tree_sitter_html::HIGHLIGHTS_QUERY.into()),
573            #[cfg(feature = "tree-sitter-yaml")]
574            Language::Yaml => Some(tree_sitter_yaml::HIGHLIGHTS_QUERY.into()),
575            #[cfg(feature = "tree-sitter-lua")]
576            Language::Lua => Some(tree_sitter_lua::HIGHLIGHTS_QUERY.into()),
577            #[cfg(feature = "tree-sitter-zig")]
578            Language::Zig => Some(tree_sitter_zig::HIGHLIGHTS_QUERY.into()),
579            #[cfg(feature = "tree-sitter-scala")]
580            Language::Scala => Some(tree_sitter_scala::HIGHLIGHTS_QUERY.into()),
581            #[cfg(feature = "tree-sitter-php")]
582            Language::Php => Some(tree_sitter_php::HIGHLIGHTS_QUERY.into()),
583            #[cfg(feature = "tree-sitter-ocaml")]
584            Language::OCaml => Some(tree_sitter_ocaml::HIGHLIGHTS_QUERY.into()),
585            #[cfg(feature = "tree-sitter-sequel")]
586            Language::Sql => Some(tree_sitter_sequel::HIGHLIGHTS_QUERY.into()),
587            _ => None,
588        }
589    }
590}
591
592pub fn highlight_color_for_capture(capture_name: &str) -> Hsla {
593    match capture_name {
594        "keyword"
595        | "keyword.control"
596        | "keyword.operator"
597        | "keyword.function"
598        | "keyword.return"
599        | "keyword.control.repeat"
600        | "keyword.control.conditional"
601        | "keyword.control.import"
602        | "keyword.control.exception"
603        | "keyword.directive"
604        | "keyword.modifier"
605        | "keyword.type"
606        | "keyword.coroutine"
607        | "keyword.storage.type"
608        | "keyword.storage.modifier"
609        | "conditional"
610        | "repeat"
611        | "include"
612        | "exception" => hsla(0.77, 0.75, 0.70, 1.0),
613
614        "type" | "type.builtin" | "type.definition" | "type.qualifier" | "storageclass"
615        | "structure" => hsla(0.47, 0.60, 0.65, 1.0),
616
617        "function" | "function.call" | "function.method" | "function.builtin"
618        | "function.macro" | "method" | "method.call" | "constructor" => {
619            hsla(0.58, 0.65, 0.70, 1.0)
620        }
621
622        "string"
623        | "string.special"
624        | "string.escape"
625        | "string.regex"
626        | "string.special.url"
627        | "string.special.path"
628        | "character"
629        | "character.special" => hsla(0.25, 0.55, 0.60, 1.0),
630
631        "number" | "float" | "constant.numeric" => hsla(0.08, 0.75, 0.65, 1.0),
632
633        "comment" | "comment.line" | "comment.block" | "comment.documentation" => {
634            hsla(0.0, 0.0, 0.45, 1.0)
635        }
636
637        "operator" => hsla(0.55, 0.50, 0.70, 1.0),
638
639        "variable" | "variable.parameter" | "variable.builtin" | "variable.member"
640        | "parameter" | "field" => hsla(0.0, 0.0, 0.85, 1.0),
641
642        "constant" | "constant.builtin" | "constant.macro" | "boolean" | "define" | "symbol" => {
643            hsla(0.08, 0.75, 0.65, 1.0)
644        }
645
646        "property" | "property.definition" => hsla(0.55, 0.50, 0.70, 1.0),
647
648        "punctuation" | "punctuation.bracket" | "punctuation.delimiter" | "punctuation.special" => {
649            hsla(0.0, 0.0, 0.60, 1.0)
650        }
651
652        "attribute" | "label" | "annotation" | "decorator" => hsla(0.12, 0.60, 0.65, 1.0),
653
654        "namespace" | "module" => hsla(0.08, 0.50, 0.70, 1.0),
655
656        "tag" | "tag.builtin" | "tag.delimiter" | "tag.attribute" => hsla(0.0, 0.65, 0.65, 1.0),
657
658        "text.title" | "markup.heading" | "text.strong" | "markup.bold" => {
659            hsla(0.58, 0.65, 0.80, 1.0)
660        }
661        "text.emphasis" | "markup.italic" => hsla(0.25, 0.55, 0.70, 1.0),
662        "text.uri" | "markup.link.url" | "markup.link" => hsla(0.55, 0.60, 0.65, 1.0),
663        "text.literal" | "markup.raw" => hsla(0.25, 0.55, 0.60, 1.0),
664
665        "embedded" | "injection.content" => hsla(0.0, 0.0, 0.80, 1.0),
666
667        _ => hsla(0.0, 0.0, 0.85, 1.0),
668    }
669}
670
671#[derive(Default)]
672struct ParseCoordinator {
673    revision: u64,
674}
675
676impl ParseCoordinator {
677    fn revision(&self) -> u64 {
678        self.revision
679    }
680
681    fn advance(&mut self) {
682        self.revision = self.revision.wrapping_add(1);
683    }
684
685    fn accepts(&self, revision: u64) -> bool {
686        self.revision == revision
687    }
688}
689
690pub struct EditorState {
691    focus_handle: FocusHandle,
692    rope: Rope,
693    cursor: Position,
694    selection: Option<Selection>,
695
696    undo_stack: Vec<EditOp>,
697    redo_stack: Vec<EditOp>,
698
699    file_path: Option<PathBuf>,
700    is_modified: bool,
701    content_version: u64,
702
703    parser: Parser,
704    syntax_tree: Option<Tree>,
705    highlight_query: Option<Query>,
706    language: Language,
707    parse_coordinator: ParseCoordinator,
708
709    scroll_handle: ScrollHandle,
710    scroll_offset_x: Pixels,
711    max_line_width: Pixels,
712    line_layouts: HashMap<usize, ShapedLine>,
713    line_content_hashes: HashMap<usize, u64>,
714    cached_highlight_spans: Vec<HighlightSpan>,
715    highlight_cache_version: u64,
716    highlight_cache_first_line: usize,
717    highlight_cache_last_line: usize,
718    last_bounds: Option<Bounds<Pixels>>,
719
720    is_selecting: bool,
721    dragging_h_scrollbar: bool,
722    last_mouse_pos: Option<Point<Pixels>>,
723    last_mouse_gutter_width: Pixels,
724    autoscroll_task: Option<Task<()>>,
725    last_click_time: Option<std::time::Instant>,
726
727    marked_range: Option<Range<usize>>,
728
729    pub show_line_numbers: bool,
730    tab_size: usize,
731    read_only: bool,
732
733    pub font_size: Pixels,
734    pub line_height: Pixels,
735    pub font_family_override: Option<SharedString>,
736
737    cursor_visible: bool,
738    blink_task: Option<Task<()>>,
739    last_cursor_move: std::time::Instant,
740    last_blink_cursor: Position,
741
742    overlay_active_check: Option<Box<dyn Fn(&App) -> bool + 'static>>,
743
744    reparse_task: Option<Task<()>>,
745    search_task: Option<Task<()>>,
746    search_generation: u64,
747
748    search_query: String,
749    search_matches: Vec<(usize, usize)>,
750    current_match_idx: Option<usize>,
751    search_case_sensitive: bool,
752    search_use_regex: bool,
753
754    pub cursor_color_override: Option<Hsla>,
755    pub selection_color_override: Option<Hsla>,
756    pub line_number_color_override: Option<Hsla>,
757    pub line_number_active_color_override: Option<Hsla>,
758    pub gutter_bg_override: Option<Hsla>,
759    pub search_match_color_overrides: Option<(Hsla, Hsla)>,
760    pub current_line_color_override: Option<Hsla>,
761    pub bracket_match_color_override: Option<Hsla>,
762    pub word_highlight_color_override: Option<Hsla>,
763    pub indent_guide_color_override: Option<Hsla>,
764    pub indent_guide_active_color_override: Option<Hsla>,
765    pub fold_marker_color_override: Option<Hsla>,
766    pub diagnostic_error_color: Option<Hsla>,
767    pub diagnostic_warning_color: Option<Hsla>,
768    pub diagnostic_info_color: Option<Hsla>,
769    pub diagnostic_hint_color: Option<Hsla>,
770    pub syntax_color_fn: Option<Box<dyn Fn(&str) -> Hsla>>,
771
772    fold_ranges: Vec<FoldRange>,
773    folded: Vec<FoldRange>,
774    cached_display_lines: Option<Rc<Vec<usize>>>,
775
776    diagnostics: Vec<EditorDiagnostic>,
777}
778
779/// Finds case-insensitive matches while keeping ranges in the original text.
780///
781/// Lowercasing a Unicode scalar can produce more than one scalar (for example,
782/// `İ` becomes `i` followed by a combining dot). Searching the lowercased
783/// string directly therefore produces offsets that do not belong to the
784/// original string. Each normalized segment below keeps the original byte
785/// range that produced it, so a match that touches any part of an expansion is
786/// mapped back to the complete source character.
787fn find_case_insensitive_matches(content: &str, query: &str) -> Vec<(usize, usize)> {
788    if query.is_empty() {
789        return Vec::new();
790    }
791
792    let mut normalized_content = String::with_capacity(content.len());
793    let mut source_ranges = Vec::new();
794
795    for (source_start, character) in content.char_indices() {
796        let source_end = source_start + character.len_utf8();
797        let normalized_start = normalized_content.len();
798        normalized_content.extend(character.to_lowercase());
799        let normalized_end = normalized_content.len();
800
801        if normalized_start != normalized_end {
802            source_ranges.push((normalized_start, normalized_end, source_start, source_end));
803        }
804    }
805
806    let normalized_query = query.to_lowercase();
807    if normalized_query.is_empty() || normalized_content.is_empty() {
808        return Vec::new();
809    }
810
811    let mut matches = Vec::new();
812    let mut search_from = 0;
813    while let Some(relative_start) = normalized_content[search_from..].find(&normalized_query) {
814        let match_start = search_from + relative_start;
815        let match_end = match_start + normalized_query.len();
816
817        if let Some((source_start, source_end)) =
818            source_range_for_normalized_range(&source_ranges, match_start, match_end)
819        {
820            matches.push((source_start, source_end));
821        }
822
823        // Preserve overlapping matches, but advance by a complete normalized
824        // character so the next slice always starts on a UTF-8 boundary.
825        let next_char_len = normalized_content[match_start..]
826            .chars()
827            .next()
828            .map(|character| character.len_utf8())
829            .unwrap_or(1);
830        search_from = match_start + next_char_len;
831    }
832
833    matches
834}
835
836fn source_range_for_normalized_range(
837    source_ranges: &[(usize, usize, usize, usize)],
838    normalized_start: usize,
839    normalized_end: usize,
840) -> Option<(usize, usize)> {
841    let first = source_ranges.partition_point(|segment| segment.1 <= normalized_start);
842    let last = source_ranges.partition_point(|segment| segment.0 < normalized_end);
843
844    (first < last).then(|| (source_ranges[first].2, source_ranges[last - 1].3))
845}
846
847#[derive(Debug, Clone)]
848pub struct EditorDiagnostic {
849    pub start_line: u32,
850    pub start_col: u32,
851    pub end_line: u32,
852    pub end_col: u32,
853    pub severity: DiagnosticSeverity,
854    pub message: String,
855}
856
857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
858pub enum DiagnosticSeverity {
859    Error,
860    Warning,
861    Information,
862    Hint,
863}
864
865impl EditorState {
866    pub fn new(cx: &mut Context<Self>) -> Self {
867        let parser = Parser::new();
868
869        Self {
870            focus_handle: cx.focus_handle(),
871            rope: Rope::from_str("\n"),
872            cursor: Position::zero(),
873            selection: None,
874            undo_stack: Vec::new(),
875            redo_stack: Vec::new(),
876            file_path: None,
877            is_modified: false,
878            content_version: 0,
879            parser,
880            syntax_tree: None,
881            highlight_query: None,
882            language: Language::Plain,
883            parse_coordinator: ParseCoordinator::default(),
884            scroll_handle: ScrollHandle::new(),
885            scroll_offset_x: px(0.0),
886            max_line_width: px(0.0),
887            line_layouts: HashMap::new(),
888            line_content_hashes: HashMap::new(),
889            cached_highlight_spans: Vec::new(),
890            highlight_cache_version: u64::MAX,
891            highlight_cache_first_line: 0,
892            highlight_cache_last_line: 0,
893            last_bounds: None,
894            is_selecting: false,
895            dragging_h_scrollbar: false,
896            last_mouse_pos: None,
897            last_mouse_gutter_width: px(80.0),
898            autoscroll_task: None,
899            last_click_time: None,
900            marked_range: None,
901            show_line_numbers: true,
902            tab_size: 4,
903            read_only: false,
904            font_size: px(14.0),
905            line_height: px(20.0),
906            font_family_override: None,
907            cursor_visible: true,
908            blink_task: None,
909            last_cursor_move: std::time::Instant::now(),
910            last_blink_cursor: Position::zero(),
911            overlay_active_check: None,
912            reparse_task: None,
913            search_task: None,
914            search_generation: 0,
915            search_query: String::new(),
916            search_matches: Vec::new(),
917            current_match_idx: None,
918            search_case_sensitive: false,
919            search_use_regex: false,
920            cursor_color_override: None,
921            selection_color_override: None,
922            line_number_color_override: None,
923            line_number_active_color_override: None,
924            gutter_bg_override: None,
925            search_match_color_overrides: None,
926            current_line_color_override: None,
927            bracket_match_color_override: None,
928            word_highlight_color_override: None,
929            indent_guide_color_override: None,
930            indent_guide_active_color_override: None,
931            fold_marker_color_override: None,
932            diagnostic_error_color: None,
933            diagnostic_warning_color: None,
934            diagnostic_info_color: None,
935            diagnostic_hint_color: None,
936            syntax_color_fn: None,
937            fold_ranges: Vec::new(),
938            folded: Vec::new(),
939            cached_display_lines: None,
940            diagnostics: Vec::new(),
941        }
942    }
943
944    pub fn set_cursor_position(&mut self, line: usize, col: usize, cx: &mut Context<Self>) {
945        let max_line = self.total_lines().saturating_sub(1);
946        self.cursor.line = line.min(max_line);
947        let line_text = self.line_text(self.cursor.line);
948        self.cursor.col = floor_char_boundary(&line_text, col.min(line_text.len()));
949        self.selection = None;
950        self.reset_cursor_blink(cx);
951        self.ensure_cursor_visible(cx);
952    }
953
954    pub fn set_font_size(&mut self, size: f32, cx: &mut Context<Self>) {
955        self.font_size = px(size);
956        self.line_height = px((size * 1.5).round());
957        self.line_layouts.clear();
958        self.line_content_hashes.clear();
959        self.max_line_width = px(0.0);
960        cx.notify();
961    }
962
963    pub fn set_font_family(&mut self, family: impl Into<SharedString>, cx: &mut Context<Self>) {
964        self.font_family_override = Some(family.into());
965        self.line_layouts.clear();
966        self.line_content_hashes.clear();
967        self.max_line_width = px(0.0);
968        cx.notify();
969    }
970
971    fn reset_cursor_blink(&mut self, cx: &mut Context<Self>) {
972        self.cursor_visible = true;
973        self.last_cursor_move = std::time::Instant::now();
974        self.blink_task = Some(cx.spawn(async |this, cx| loop {
975            smol::Timer::after(std::time::Duration::from_millis(500)).await;
976            let ok = this
977                .update(cx, |state, cx| {
978                    state.cursor_visible = !state.cursor_visible;
979                    cx.notify();
980                })
981                .is_ok();
982            if !ok {
983                break;
984            }
985        }));
986    }
987
988    pub fn set_diagnostics(&mut self, diagnostics: Vec<EditorDiagnostic>, cx: &mut Context<Self>) {
989        self.diagnostics = diagnostics;
990        cx.notify();
991    }
992
993    pub fn diagnostics(&self) -> &[EditorDiagnostic] {
994        &self.diagnostics
995    }
996
997    pub fn diagnostics_at_line(&self, line: usize) -> Vec<&EditorDiagnostic> {
998        self.diagnostics
999            .iter()
1000            .filter(|d| d.start_line as usize <= line && line <= d.end_line as usize)
1001            .collect()
1002    }
1003
1004    pub fn content(&self) -> String {
1005        self.rope.to_string()
1006    }
1007
1008    pub fn is_empty(&self) -> bool {
1009        self.rope.len_bytes() == 0 || (self.rope.len_bytes() == 1 && self.rope.len_lines() <= 1)
1010    }
1011
1012    pub fn line_count(&self) -> usize {
1013        let lines = self.rope.len_lines();
1014        if lines > 0 && self.rope.len_bytes() > 0 {
1015            let last_line = self.rope.line(lines - 1);
1016            if last_line.len_bytes() == 0 {
1017                return lines.saturating_sub(1).max(1);
1018            }
1019        }
1020        lines.max(1)
1021    }
1022
1023    pub fn cursor(&self) -> Position {
1024        self.cursor
1025    }
1026
1027    pub fn is_modified(&self) -> bool {
1028        self.is_modified
1029    }
1030
1031    pub fn file_path(&self) -> Option<&PathBuf> {
1032        self.file_path.as_ref()
1033    }
1034
1035    pub fn language(&self) -> Language {
1036        self.language
1037    }
1038
1039    pub fn syntax_tree(&self) -> Option<&Tree> {
1040        self.syntax_tree.as_ref()
1041    }
1042
1043    pub fn word_at_cursor(&self) -> Option<(String, usize)> {
1044        let line_text = self.line_text(self.cursor.line);
1045        if line_text.is_empty() || self.cursor.col == 0 {
1046            return None;
1047        }
1048
1049        let bytes = line_text.as_bytes();
1050        let col = self.cursor.col.min(bytes.len());
1051
1052        let mut word_start = col;
1053        while word_start > 0 {
1054            let ch = bytes[word_start - 1];
1055            if !ch.is_ascii_alphanumeric() && ch != b'_' {
1056                break;
1057            }
1058            word_start -= 1;
1059        }
1060
1061        if word_start == col {
1062            return None;
1063        }
1064
1065        let word = line_text[word_start..col].to_string();
1066        Some((word, word_start))
1067    }
1068
1069    pub fn find_matching_bracket(&self) -> Option<(Position, Position)> {
1070        let line_text = self.line_text(self.cursor.line);
1071        let col = self.cursor.col.min(line_text.len());
1072        let bytes = line_text.as_bytes();
1073
1074        let check_positions: &[usize] = if col > 0 { &[col, col - 1] } else { &[col] };
1075
1076        for &check_col in check_positions {
1077            if check_col >= bytes.len() {
1078                continue;
1079            }
1080            let ch = bytes[check_col] as char;
1081            let (opener, closer, forward) = match ch {
1082                '(' => ('(', ')', true),
1083                '[' => ('[', ']', true),
1084                '{' => ('{', '}', true),
1085                ')' => ('(', ')', false),
1086                ']' => ('[', ']', false),
1087                '}' => ('{', '}', false),
1088                _ => continue,
1089            };
1090
1091            let start_pos = Position::new(self.cursor.line, check_col);
1092
1093            if forward {
1094                let mut depth = 1i32;
1095                let mut scan_line = self.cursor.line;
1096                let mut scan_col = check_col + 1;
1097                let total = self.total_lines();
1098                while scan_line < total {
1099                    let scan_text = self.line_text(scan_line);
1100                    let scan_bytes = scan_text.as_bytes();
1101                    while scan_col < scan_bytes.len() {
1102                        let sc = scan_bytes[scan_col] as char;
1103                        if sc == opener {
1104                            depth += 1;
1105                        } else if sc == closer {
1106                            depth -= 1;
1107                            if depth == 0 {
1108                                return Some((start_pos, Position::new(scan_line, scan_col)));
1109                            }
1110                        }
1111                        scan_col += 1;
1112                    }
1113                    scan_line += 1;
1114                    scan_col = 0;
1115                }
1116            } else {
1117                let mut depth = 1i32;
1118                let mut scan_line = self.cursor.line;
1119                let mut scan_col = check_col as i64 - 1;
1120                loop {
1121                    if scan_col < 0 {
1122                        if scan_line == 0 {
1123                            break;
1124                        }
1125                        scan_line -= 1;
1126                        let prev_text = self.line_text(scan_line);
1127                        scan_col = prev_text.len() as i64 - 1;
1128                        continue;
1129                    }
1130                    let scan_text = self.line_text(scan_line);
1131                    let scan_bytes = scan_text.as_bytes();
1132                    if (scan_col as usize) < scan_bytes.len() {
1133                        let sc = scan_bytes[scan_col as usize] as char;
1134                        if sc == closer {
1135                            depth += 1;
1136                        } else if sc == opener {
1137                            depth -= 1;
1138                            if depth == 0 {
1139                                return Some((
1140                                    Position::new(scan_line, scan_col as usize),
1141                                    start_pos,
1142                                ));
1143                            }
1144                        }
1145                    }
1146                    scan_col -= 1;
1147                }
1148            }
1149        }
1150        None
1151    }
1152
1153    pub fn word_under_cursor_full(&self) -> Option<(String, usize, usize)> {
1154        let line_text = self.line_text(self.cursor.line);
1155        if line_text.is_empty() {
1156            return None;
1157        }
1158        let bytes = line_text.as_bytes();
1159        let col = self.cursor.col.min(bytes.len());
1160
1161        let mut word_start = col;
1162        while word_start > 0
1163            && (bytes[word_start - 1].is_ascii_alphanumeric() || bytes[word_start - 1] == b'_')
1164        {
1165            word_start -= 1;
1166        }
1167
1168        let mut word_end = col;
1169        while word_end < bytes.len()
1170            && (bytes[word_end].is_ascii_alphanumeric() || bytes[word_end] == b'_')
1171        {
1172            word_end += 1;
1173        }
1174
1175        if word_start == word_end {
1176            return None;
1177        }
1178
1179        let word = line_text[word_start..word_end].to_string();
1180        if word.len() < 2 {
1181            return None;
1182        }
1183        Some((word, word_start, word_end))
1184    }
1185
1186    pub fn compute_fold_ranges(&mut self) {
1187        let tree = match &self.syntax_tree {
1188            Some(t) => t,
1189            None => {
1190                self.clear_fold_state();
1191                return;
1192            }
1193        };
1194
1195        let mut ranges = Vec::new();
1196        let mut tree_cursor = tree.root_node().walk();
1197        let mut did_enter = true;
1198
1199        loop {
1200            let node = tree_cursor.node();
1201            if did_enter {
1202                let kind = node.kind();
1203                let start_line = node.start_position().row;
1204                let end_line = node.end_position().row;
1205                if end_line > start_line + 1 && Self::is_foldable_kind(kind) {
1206                    ranges.push(FoldRange {
1207                        start_line,
1208                        end_line,
1209                    });
1210                }
1211            }
1212
1213            if did_enter && tree_cursor.goto_first_child() {
1214                did_enter = true;
1215            } else if tree_cursor.goto_next_sibling() {
1216                did_enter = true;
1217            } else if tree_cursor.goto_parent() {
1218                did_enter = false;
1219            } else {
1220                break;
1221            }
1222        }
1223
1224        ranges.sort_by_key(|r| r.start_line);
1225        ranges.dedup_by_key(|r| r.start_line);
1226        self.fold_ranges = ranges;
1227
1228        let current_ranges = &self.fold_ranges;
1229        self.folded = self
1230            .folded
1231            .iter()
1232            .filter_map(|folded| {
1233                current_ranges
1234                    .iter()
1235                    .find(|range| range.start_line == folded.start_line)
1236                    .copied()
1237            })
1238            .collect();
1239
1240        if self.folded.is_empty() {
1241            self.cached_display_lines = None;
1242        } else {
1243            self.cached_display_lines = Some(Rc::new(self.compute_display_lines()));
1244        }
1245    }
1246
1247    fn is_foldable_kind(kind: &str) -> bool {
1248        matches!(
1249            kind,
1250            "function_item"
1251                | "impl_item"
1252                | "struct_item"
1253                | "enum_item"
1254                | "block"
1255                | "if_expression"
1256                | "match_expression"
1257                | "function_declaration"
1258                | "class_declaration"
1259                | "class_definition"
1260                | "method_definition"
1261                | "if_statement"
1262                | "for_statement"
1263                | "while_statement"
1264                | "for_expression"
1265                | "while_expression"
1266                | "object"
1267                | "array"
1268                | "trait_item"
1269                | "mod_item"
1270                | "use_declaration"
1271                | "const_item"
1272                | "static_item"
1273                | "macro_definition"
1274                | "interface_declaration"
1275                | "type_alias_declaration"
1276                | "arrow_function"
1277                | "function_expression"
1278                | "try_statement"
1279                | "switch_statement"
1280                | "match_block"
1281                | "closure_expression"
1282                | "dictionary"
1283                | "list"
1284                | "tuple"
1285        )
1286    }
1287
1288    pub fn toggle_fold_at_line(&mut self, line: usize, cx: &mut Context<Self>) {
1289        if let Some(idx) = self.folded.iter().position(|f| f.start_line == line) {
1290            self.folded.remove(idx);
1291        } else if let Some(range) = self.fold_ranges.iter().find(|r| r.start_line == line) {
1292            self.folded.push(*range);
1293        }
1294        self.invalidate_folds();
1295        self.clamp_scroll_after_fold();
1296        cx.notify();
1297    }
1298
1299    pub fn fold_all(&mut self, cx: &mut Context<Self>) {
1300        self.folded = self.fold_ranges.clone();
1301        self.invalidate_folds();
1302        self.clamp_scroll_after_fold();
1303        cx.notify();
1304    }
1305
1306    pub fn unfold_all(&mut self, cx: &mut Context<Self>) {
1307        self.folded.clear();
1308        self.invalidate_folds();
1309        self.clamp_scroll_after_fold();
1310        cx.notify();
1311    }
1312
1313    fn invalidate_folds(&mut self) {
1314        self.invalidate_all_caches();
1315        if self.folded.is_empty() {
1316            self.cached_display_lines = None;
1317        } else {
1318            self.cached_display_lines = Some(Rc::new(self.compute_display_lines()));
1319        }
1320    }
1321
1322    fn compute_display_lines(&self) -> Vec<usize> {
1323        let total = self.total_lines();
1324        let mut lines = Vec::with_capacity(total);
1325        let mut skip_until: Option<usize> = None;
1326        for line in 0..total {
1327            if let Some(end) = skip_until {
1328                if line <= end {
1329                    continue;
1330                }
1331                skip_until = None;
1332            }
1333            lines.push(line);
1334            if let Some(fold) = self.folded.iter().find(|f| f.start_line == line) {
1335                skip_until = Some(fold.end_line);
1336            }
1337        }
1338        lines
1339    }
1340
1341    fn clamp_scroll_after_fold(&mut self) {
1342        let line_height = self.line_height;
1343        let padding_top = px(12.0);
1344        let padding_bottom = px(12.0);
1345        let display_count = self.display_line_count();
1346        let content_height = padding_top + padding_bottom + line_height * display_count as f32;
1347        let viewport_height = self.scroll_handle.bounds().size.height;
1348
1349        if viewport_height <= px(0.0) {
1350            return;
1351        }
1352
1353        let max_scroll = (content_height - viewport_height).max(px(0.0));
1354        let offset = self.scroll_handle.offset();
1355        let clamped_y = offset.y.max(-max_scroll).min(px(0.0));
1356        if (clamped_y - offset.y).abs() > px(0.1) {
1357            self.scroll_handle.set_offset(point(offset.x, clamped_y));
1358        }
1359    }
1360
1361    pub fn is_line_folded(&self, line: usize) -> bool {
1362        self.folded
1363            .iter()
1364            .any(|f| line > f.start_line && line <= f.end_line)
1365    }
1366
1367    pub fn display_lines(&self) -> Rc<Vec<usize>> {
1368        if let Some(ref cached) = self.cached_display_lines {
1369            return Rc::clone(cached);
1370        }
1371        Rc::new(self.compute_display_lines())
1372    }
1373
1374    pub fn display_line_count(&self) -> usize {
1375        if self.folded.is_empty() {
1376            return self.total_lines();
1377        }
1378        if let Some(ref cached) = self.cached_display_lines {
1379            return cached.len();
1380        }
1381        self.compute_display_lines().len()
1382    }
1383
1384    pub fn buffer_line_to_display_row(&self, buffer_line: usize) -> Option<usize> {
1385        let mut display_row = 0usize;
1386        let mut skip_until: Option<usize> = None;
1387        let total = self.total_lines();
1388        for line in 0..total {
1389            if let Some(end) = skip_until {
1390                if line <= end {
1391                    if line == buffer_line {
1392                        return None;
1393                    }
1394                    continue;
1395                }
1396                skip_until = None;
1397            }
1398            if line == buffer_line {
1399                return Some(display_row);
1400            }
1401            if let Some(fold) = self.folded.iter().find(|f| f.start_line == line) {
1402                skip_until = Some(fold.end_line);
1403            }
1404            display_row += 1;
1405        }
1406        None
1407    }
1408
1409    pub fn display_row_to_buffer_line(&self, display_row: usize) -> usize {
1410        let mut current_display = 0usize;
1411        let mut skip_until: Option<usize> = None;
1412        let total = self.total_lines();
1413        for line in 0..total {
1414            if let Some(end) = skip_until {
1415                if line <= end {
1416                    continue;
1417                }
1418                skip_until = None;
1419            }
1420            if current_display == display_row {
1421                return line;
1422            }
1423            if let Some(fold) = self.folded.iter().find(|f| f.start_line == line) {
1424                skip_until = Some(fold.end_line);
1425            }
1426            current_display += 1;
1427        }
1428        total.saturating_sub(1)
1429    }
1430
1431    pub fn fold_ranges(&self) -> &[FoldRange] {
1432        &self.fold_ranges
1433    }
1434
1435    pub fn folded_ranges(&self) -> &[FoldRange] {
1436        &self.folded
1437    }
1438
1439    pub fn scope_breadcrumbs(&self) -> Vec<(String, usize)> {
1440        let tree = match &self.syntax_tree {
1441            Some(t) => t,
1442            None => return Vec::new(),
1443        };
1444
1445        let byte_offset = self.pos_to_byte_offset(self.cursor);
1446        let ts_point = self.byte_to_ts_point(byte_offset);
1447        let mut node = match tree
1448            .root_node()
1449            .descendant_for_point_range(ts_point, ts_point)
1450        {
1451            Some(n) => n,
1452            None => return Vec::new(),
1453        };
1454
1455        let mut breadcrumbs = Vec::new();
1456        loop {
1457            let kind = node.kind();
1458            if Self::is_scope_kind(kind) {
1459                if let Some(name) = Self::extract_scope_name(&node, &self.rope) {
1460                    let line = node.start_position().row;
1461                    breadcrumbs.push((name, line));
1462                }
1463            }
1464            match node.parent() {
1465                Some(p) => node = p,
1466                None => break,
1467            }
1468        }
1469        breadcrumbs.reverse();
1470        breadcrumbs
1471    }
1472
1473    fn is_scope_kind(kind: &str) -> bool {
1474        matches!(
1475            kind,
1476            "function_item"
1477                | "impl_item"
1478                | "struct_item"
1479                | "enum_item"
1480                | "trait_item"
1481                | "mod_item"
1482                | "function_declaration"
1483                | "class_declaration"
1484                | "class_definition"
1485                | "method_definition"
1486                | "interface_declaration"
1487                | "module"
1488                | "namespace_definition"
1489        )
1490    }
1491
1492    fn extract_scope_name(node: &tree_sitter::Node, rope: &Rope) -> Option<String> {
1493        for i in 0..node.child_count() {
1494            if let Some(child) = node.child(i) {
1495                let kind = child.kind();
1496                if kind == "name"
1497                    || kind == "identifier"
1498                    || kind == "type_identifier"
1499                    || kind == "property_identifier"
1500                {
1501                    let start = child.start_byte();
1502                    let end = child.end_byte().min(rope.len_bytes());
1503                    if start < end {
1504                        let name: String = rope.byte_slice(start..end).into();
1505                        return Some(name);
1506                    }
1507                }
1508            }
1509        }
1510        None
1511    }
1512
1513    fn closing_char_for(&self, ch: char) -> Option<char> {
1514        for &(opener, closer) in AUTO_CLOSE_PAIRS {
1515            if ch == opener {
1516                if opener == closer {
1517                    let line_text = self.line_text(self.cursor.line);
1518                    let col = floor_char_boundary(&line_text, self.cursor.col);
1519                    let before = &line_text[..col];
1520                    let count = before.chars().filter(|&c| c == ch).count();
1521                    if count % 2 != 0 {
1522                        return None;
1523                    }
1524                }
1525                return Some(closer);
1526            }
1527        }
1528        None
1529    }
1530
1531    fn should_skip_closing_char(&self, ch: char) -> bool {
1532        let is_closer = AUTO_CLOSE_PAIRS.iter().any(|&(_, c)| c == ch);
1533        if !is_closer {
1534            return false;
1535        }
1536        let line_text = self.line_text(self.cursor.line);
1537        let col = floor_char_boundary(&line_text, self.cursor.col);
1538        if col < line_text.len() {
1539            let next_ch = line_text[col..].chars().next();
1540            return next_ch == Some(ch);
1541        }
1542        false
1543    }
1544
1545    fn is_between_auto_close_pair(&self) -> bool {
1546        let line_text = self.line_text(self.cursor.line);
1547        let col = self.cursor.col;
1548        if col == 0 || col >= line_text.len() {
1549            return false;
1550        }
1551        let before = line_text.as_bytes()[col - 1];
1552        let after = line_text.as_bytes()[col];
1553        AUTO_CLOSE_PAIRS
1554            .iter()
1555            .any(|&(o, c)| before == o as u8 && after == c as u8)
1556    }
1557
1558    pub fn cursor_screen_position(&self, line_height: Pixels) -> Option<Point<Pixels>> {
1559        let bounds = self.last_bounds?;
1560        let gutter_width = if self.show_line_numbers {
1561            px(80.0)
1562        } else {
1563            px(12.0)
1564        };
1565        let padding_top = px(12.0);
1566
1567        let cursor_y = bounds.top() + padding_top + line_height * (self.cursor.line as f32);
1568
1569        let cursor_x = if let Some(layout) = self.line_layouts.get(&self.cursor.line) {
1570            let line_text = self.line_text(self.cursor.line);
1571            let char_offset = self.cursor.col.min(line_text.len());
1572            let x_offset = layout.x_for_index(char_offset);
1573            bounds.left() + gutter_width + x_offset
1574        } else {
1575            let approx_char_width = px(8.4);
1576            bounds.left() + gutter_width + approx_char_width * (self.cursor.col as f32)
1577        };
1578
1579        Some(Point::new(cursor_x, cursor_y + line_height))
1580    }
1581
1582    pub fn apply_completion(
1583        &mut self,
1584        trigger_col: usize,
1585        insert_text: &str,
1586        cx: &mut Context<Self>,
1587    ) {
1588        if self.read_only {
1589            return;
1590        }
1591
1592        let delete_count = self.cursor.col.saturating_sub(trigger_col);
1593        if delete_count > 0 {
1594            let start_pos = Position::new(self.cursor.line, trigger_col);
1595            let end_pos = self.cursor;
1596            self.delete_selection_internal(Selection::new(start_pos, end_pos), cx);
1597        }
1598
1599        self.insert_text_at_cursor(insert_text, cx);
1600        self.ensure_cursor_visible(cx);
1601        cx.notify();
1602    }
1603
1604    fn line_text(&self, line: usize) -> String {
1605        if line >= self.rope.len_lines() {
1606            return String::new();
1607        }
1608        let line_slice = self.rope.line(line);
1609        let mut s = line_slice.to_string();
1610        if s.ends_with('\n') {
1611            s.pop();
1612        }
1613        if s.ends_with('\r') {
1614            s.pop();
1615        }
1616        s
1617    }
1618
1619    fn line_len(&self, line: usize) -> usize {
1620        self.line_text(line).len()
1621    }
1622
1623    fn rope_insert(&mut self, byte_offset: usize, text: &str) {
1624        let char_offset = self
1625            .rope
1626            .byte_to_char(byte_offset.min(self.rope.len_bytes()));
1627        self.rope.insert(char_offset, text);
1628    }
1629
1630    fn rope_remove(&mut self, byte_start: usize, byte_end: usize) {
1631        let len = self.rope.len_bytes();
1632        let char_start = self.rope.byte_to_char(byte_start.min(len));
1633        let char_end = self.rope.byte_to_char(byte_end.min(len));
1634        self.rope.remove(char_start..char_end);
1635    }
1636
1637    fn total_lines(&self) -> usize {
1638        self.line_count()
1639    }
1640
1641    pub fn set_content(&mut self, content: &str, cx: &mut Context<Self>) {
1642        self.advance_parse_revision();
1643        self.advance_search_generation();
1644        self.content_version = self.content_version.wrapping_add(1);
1645        self.rope = if content.is_empty() {
1646            Rope::from_str("\n")
1647        } else if content.ends_with('\n') {
1648            Rope::from_str(content)
1649        } else {
1650            let mut s = content.to_string();
1651            s.push('\n');
1652            Rope::from_str(&s)
1653        };
1654        self.cursor = Position::zero();
1655        self.selection = None;
1656        self.undo_stack.clear();
1657        self.redo_stack.clear();
1658        self.is_modified = false;
1659        self.clear_search_results();
1660        self.clear_fold_state();
1661        self.invalidate_all_caches();
1662        if self.rope.len_bytes() > 50_000 {
1663            self.parse_async(cx);
1664        } else {
1665            self.update_syntax_tree();
1666        }
1667        cx.notify();
1668    }
1669
1670    pub fn set_language(&mut self, lang: Language) {
1671        if self.language != lang {
1672            self.advance_parse_revision();
1673        }
1674        self.clear_fold_state();
1675        self.language = lang;
1676        if let Some(ts_lang) = lang.tree_sitter_language() {
1677            let _ = self.parser.set_language(&ts_lang);
1678            self.highlight_query = lang
1679                .highlight_query_source()
1680                .filter(|src| !src.is_empty())
1681                .and_then(|src| Query::new(&ts_lang, &src).ok());
1682        } else {
1683            self.highlight_query = None;
1684        }
1685        self.invalidate_all_caches();
1686        self.update_syntax_tree();
1687    }
1688
1689    pub fn set_overlay_active_check(&mut self, check: impl Fn(&App) -> bool + 'static) {
1690        self.overlay_active_check = Some(Box::new(check));
1691    }
1692
1693    fn is_overlay_active(&self, cx: &App) -> bool {
1694        self.overlay_active_check
1695            .as_ref()
1696            .map(|check| check(cx))
1697            .unwrap_or(false)
1698    }
1699
1700    pub fn load_file(&mut self, path: impl Into<PathBuf>, cx: &mut Context<Self>) {
1701        let path = path.into();
1702        let lang = Language::from_path(&path);
1703        self.language = lang;
1704        if let Some(ts_lang) = lang.tree_sitter_language() {
1705            let _ = self.parser.set_language(&ts_lang);
1706            self.highlight_query = lang
1707                .highlight_query_source()
1708                .filter(|src| !src.is_empty())
1709                .and_then(|src| Query::new(&ts_lang, &src).ok());
1710        } else {
1711            self.highlight_query = None;
1712        }
1713
1714        match std::fs::File::open(&path) {
1715            Ok(file) => {
1716                let reader = std::io::BufReader::new(file);
1717                match Rope::from_reader(reader) {
1718                    Ok(rope) => {
1719                        self.advance_parse_revision();
1720                        self.advance_search_generation();
1721                        self.content_version = self.content_version.wrapping_add(1);
1722                        self.file_path = Some(path);
1723                        self.rope = rope;
1724                        self.cursor = Position::zero();
1725                        self.selection = None;
1726                        self.undo_stack.clear();
1727                        self.redo_stack.clear();
1728                        self.is_modified = false;
1729                        self.clear_search_results();
1730                        self.clear_fold_state();
1731                        self.invalidate_all_caches();
1732                        if self.rope.len_bytes() > 50_000 {
1733                            self.parse_async(cx);
1734                        } else {
1735                            self.update_syntax_tree();
1736                        }
1737                        cx.notify();
1738                    }
1739                    Err(_) => {
1740                        self.file_path = Some(path);
1741                        self.set_content("", cx);
1742                        self.is_modified = false;
1743                    }
1744                }
1745            }
1746            Err(_) => {
1747                self.file_path = Some(path);
1748                self.set_content("", cx);
1749                self.is_modified = false;
1750            }
1751        }
1752    }
1753
1754    pub fn save_to_file(&mut self, path: impl Into<PathBuf>, cx: &mut Context<Self>) -> bool {
1755        let path = path.into();
1756        match std::fs::File::create(&path) {
1757            Ok(file) => {
1758                let mut writer = std::io::BufWriter::new(file);
1759                match self.rope.write_to(&mut writer) {
1760                    Ok(()) => {
1761                        self.file_path = Some(path);
1762                        self.is_modified = false;
1763                        cx.notify();
1764                        true
1765                    }
1766                    Err(_) => false,
1767                }
1768            }
1769            Err(_) => false,
1770        }
1771    }
1772
1773    pub fn save(&mut self, cx: &mut Context<Self>) -> bool {
1774        if let Some(path) = self.file_path.clone() {
1775            self.save_to_file(path, cx)
1776        } else {
1777            false
1778        }
1779    }
1780
1781    fn update_syntax_tree(&mut self) {
1782        if self.language.tree_sitter_language().is_none() {
1783            self.replace_syntax_tree(None);
1784            return;
1785        }
1786
1787        let rope = &self.rope;
1788        let tree = self.parser.parse_with_options(
1789            &mut |byte_idx, _pos| -> &[u8] {
1790                if byte_idx >= rope.len_bytes() {
1791                    return &[];
1792                }
1793                let (chunk, start, _, _) = rope.chunk_at_byte(byte_idx);
1794                &chunk.as_bytes()[byte_idx - start..]
1795            },
1796            None,
1797            None,
1798        );
1799        self.replace_syntax_tree(tree);
1800        self.compute_fold_ranges();
1801    }
1802
1803    fn byte_to_ts_point(&self, byte_offset: usize) -> TSPoint {
1804        let line = self.rope.byte_to_line(byte_offset);
1805        let line_start = self.rope.line_to_byte(line);
1806        TSPoint::new(line, byte_offset - line_start)
1807    }
1808
1809    fn update_syntax_tree_incremental(
1810        &mut self,
1811        start_byte: usize,
1812        old_end_byte: usize,
1813        new_end_byte: usize,
1814        old_end_position: TSPoint,
1815        cx: &mut Context<Self>,
1816    ) {
1817        let start_position = self.byte_to_ts_point(start_byte);
1818        let new_end_position = self.byte_to_ts_point(new_end_byte.min(self.rope.len_bytes()));
1819        if let Some(tree) = &mut self.syntax_tree {
1820            tree.edit(&InputEdit {
1821                start_byte,
1822                old_end_byte,
1823                new_end_byte,
1824                start_position,
1825                old_end_position,
1826                new_end_position,
1827            });
1828        }
1829        self.schedule_reparse(cx);
1830    }
1831
1832    fn update_syntax_tree_for_edit(&mut self, plan: TextEditPlan, cx: &mut Context<Self>) {
1833        self.update_syntax_tree_incremental(
1834            plan.range.start,
1835            plan.range.old_end,
1836            plan.range.new_end,
1837            plan.old_end_position,
1838            cx,
1839        );
1840    }
1841
1842    fn parse_async(&mut self, cx: &mut Context<Self>) -> bool {
1843        if self.language.tree_sitter_language().is_none() {
1844            self.replace_syntax_tree(None);
1845            return false;
1846        }
1847
1848        let revision = self.parse_coordinator.revision();
1849        let content = self.rope.to_string();
1850        let lang = self.language;
1851        self.replace_syntax_tree(None);
1852        let (tx, rx) = smol::channel::bounded(1);
1853        std::thread::spawn(move || {
1854            let mut parser = Parser::new();
1855            if let Some(ts_lang) = lang.tree_sitter_language() {
1856                let _ = parser.set_language(&ts_lang);
1857                let tree = parser.parse(&content, None);
1858                let _ = tx.send_blocking(tree);
1859            }
1860        });
1861        cx.spawn(async move |this, cx| {
1862            if let Ok(tree) = rx.recv().await {
1863                let _ = cx.update(|cx| {
1864                    let _ = this.update(cx, |state, cx| {
1865                        if state.commit_parse_result(revision, tree) {
1866                            state.compute_fold_ranges();
1867                            state.invalidate_all_caches();
1868                            cx.notify();
1869                        }
1870                    });
1871                });
1872            }
1873        })
1874        .detach();
1875        true
1876    }
1877
1878    fn schedule_reparse(&mut self, cx: &mut Context<Self>) {
1879        let entity = cx.entity().clone();
1880        self.reparse_task = Some(cx.spawn(async move |_, cx| {
1881            Timer::after(Duration::from_millis(50)).await;
1882            let _ = cx.update(|cx| {
1883                entity.update(cx, |state, cx| {
1884                    if state.syntax_tree.is_none() {
1885                        state.parse_async(cx);
1886                        return;
1887                    }
1888                    state.update_syntax_tree_incremental_now();
1889                    state.compute_fold_ranges();
1890                    // Clear all index-keyed caches (line layouts, content
1891                    // hashes, highlights) so the next render rebuilds them
1892                    // from the updated text and syntax tree.
1893                    state.invalidate_after_edit(false);
1894                    cx.notify();
1895                });
1896            });
1897        }));
1898    }
1899
1900    fn update_syntax_tree_incremental_now(&mut self) {
1901        if self.syntax_tree.is_none() {
1902            return;
1903        }
1904        let rope = &self.rope;
1905        let tree = self.parser.parse_with_options(
1906            &mut |byte_idx, _pos| -> &[u8] {
1907                if byte_idx >= rope.len_bytes() {
1908                    return &[];
1909                }
1910                let (chunk, start, _, _) = rope.chunk_at_byte(byte_idx);
1911                &chunk.as_bytes()[byte_idx - start..]
1912            },
1913            self.syntax_tree.as_ref(),
1914            None,
1915        );
1916        self.replace_syntax_tree(tree);
1917    }
1918
1919    fn pos_to_byte_offset(&self, pos: Position) -> usize {
1920        if pos.line >= self.rope.len_lines() {
1921            return self.rope.len_bytes();
1922        }
1923        let line_start = self.rope.line_to_byte(pos.line);
1924        let line_text = self.line_text(pos.line);
1925        line_start + floor_char_boundary(&line_text, min(pos.col, line_text.len()))
1926    }
1927
1928    fn snapshot_positions(&self) -> PositionSnapshot {
1929        PositionSnapshot {
1930            cursor_offset: self.pos_to_byte_offset(self.cursor),
1931            selection_offsets: self.selection.as_ref().map(|selection| {
1932                (
1933                    self.pos_to_byte_offset(selection.anchor),
1934                    self.pos_to_byte_offset(selection.cursor),
1935                )
1936            }),
1937        }
1938    }
1939
1940    fn restore_positions_after_edit(&mut self, snapshot: PositionSnapshot, edit: TextEditRange) {
1941        self.cursor = self.byte_offset_to_pos(edit.map_cursor_offset(snapshot.cursor_offset));
1942        self.selection = snapshot.selection_offsets.map(|(anchor, cursor)| {
1943            let (anchor, cursor) = edit.map_selection_offsets(anchor, cursor);
1944            Selection::new(
1945                self.byte_offset_to_pos(anchor),
1946                self.byte_offset_to_pos(cursor),
1947            )
1948        });
1949    }
1950
1951    fn byte_offset_to_pos(&self, offset: usize) -> Position {
1952        let offset = min(offset, self.rope.len_bytes());
1953        let line = self.rope.byte_to_line(offset);
1954        let line_start = self.rope.line_to_byte(line);
1955        let col = offset - line_start;
1956        Position::new(line, col)
1957    }
1958
1959    fn clamp_cursor(&mut self) {
1960        let max_line = self.total_lines().saturating_sub(1);
1961        self.cursor.line = min(self.cursor.line, max_line);
1962        let line_text = self.line_text(self.cursor.line);
1963        self.cursor.col = floor_char_boundary(&line_text, min(self.cursor.col, line_text.len()));
1964    }
1965
1966    fn is_parse_result_current(&self, revision: u64) -> bool {
1967        self.parse_coordinator.accepts(revision)
1968    }
1969
1970    fn commit_parse_result(&mut self, revision: u64, tree: Option<Tree>) -> bool {
1971        if !self.is_parse_result_current(revision) {
1972            return false;
1973        }
1974
1975        self.replace_syntax_tree(tree);
1976        true
1977    }
1978
1979    fn replace_syntax_tree(&mut self, tree: Option<Tree>) {
1980        self.syntax_tree = tree;
1981        if self.syntax_tree.is_none() {
1982            self.clear_fold_state();
1983        }
1984    }
1985
1986    fn clear_fold_state(&mut self) {
1987        self.fold_ranges.clear();
1988        self.folded.clear();
1989        self.cached_display_lines = None;
1990    }
1991
1992    fn advance_parse_revision(&mut self) {
1993        self.parse_coordinator.advance();
1994    }
1995
1996    fn mark_modified(&mut self) {
1997        self.is_modified = true;
1998        self.content_version = self.content_version.wrapping_add(1);
1999        self.advance_parse_revision();
2000        self.advance_search_generation();
2001        self.cursor_visible = true;
2002        self.last_cursor_move = std::time::Instant::now();
2003    }
2004
2005    fn advance_search_generation(&mut self) -> u64 {
2006        self.search_generation = self.search_generation.wrapping_add(1);
2007        self.search_generation
2008    }
2009
2010    fn clear_search_results(&mut self) {
2011        self.search_matches.clear();
2012        self.current_match_idx = None;
2013    }
2014
2015    fn group_last_edits(&mut self, count: usize) {
2016        if count == 0 || self.undo_stack.len() < count {
2017            return;
2018        }
2019        let start = self.undo_stack.len() - count;
2020        let edits = self.undo_stack.drain(start..).collect();
2021        self.undo_stack.push(EditOp::Batch(edits));
2022    }
2023
2024    fn line_at_byte(&self, byte_offset: usize) -> usize {
2025        self.rope
2026            .byte_to_line(byte_offset.min(self.rope.len_bytes()))
2027    }
2028
2029    fn apply_primitive_edit(&mut self, op: &EditOp, undo: bool) {
2030        match op {
2031            EditOp::Insert { byte_offset, text } => {
2032                if undo {
2033                    self.rope_remove(*byte_offset, byte_offset.saturating_add(text.len()));
2034                    self.cursor = self.byte_offset_to_pos(*byte_offset);
2035                } else {
2036                    self.rope_insert(*byte_offset, text);
2037                    self.cursor = self.byte_offset_to_pos(byte_offset.saturating_add(text.len()));
2038                }
2039            }
2040            EditOp::Delete { byte_offset, text } => {
2041                if undo {
2042                    self.rope_insert(*byte_offset, text);
2043                    self.cursor = self.byte_offset_to_pos(byte_offset.saturating_add(text.len()));
2044                } else {
2045                    self.rope_remove(*byte_offset, byte_offset.saturating_add(text.len()));
2046                    self.cursor = self.byte_offset_to_pos(*byte_offset);
2047                }
2048            }
2049            EditOp::Batch(_) => unreachable!("batch edits must be applied recursively"),
2050        }
2051    }
2052
2053    fn apply_edit_op_with_fold_state(&mut self, op: &EditOp, undo: bool) {
2054        match op {
2055            EditOp::Insert { byte_offset, text } | EditOp::Delete { byte_offset, text } => {
2056                let start_line = self.line_at_byte(*byte_offset);
2057                let old_end_line = match (matches!(op, EditOp::Insert { .. }), undo) {
2058                    (true, true) | (false, false) => {
2059                        self.line_at_byte(byte_offset.saturating_add(text.len()))
2060                    }
2061                    _ => start_line,
2062                };
2063
2064                self.apply_primitive_edit(op, undo);
2065
2066                if text.contains('\n') {
2067                    let new_end_line = match (matches!(op, EditOp::Insert { .. }), undo) {
2068                        (true, true) | (false, false) => self.line_at_byte(*byte_offset),
2069                        _ => self.line_at_byte(byte_offset.saturating_add(text.len())),
2070                    };
2071                    self.update_fold_state_after_line_edit(LineEditRange {
2072                        start_line,
2073                        old_end_line,
2074                        new_end_line,
2075                    });
2076                }
2077            }
2078            EditOp::Batch(edits) => {
2079                if undo {
2080                    for edit in edits.iter().rev() {
2081                        self.apply_edit_op_with_fold_state(edit, true);
2082                    }
2083                } else {
2084                    for edit in edits {
2085                        self.apply_edit_op_with_fold_state(edit, false);
2086                    }
2087                }
2088            }
2089        }
2090    }
2091
2092    pub fn content_version(&self) -> u64 {
2093        self.content_version
2094    }
2095
2096    fn insert_text_at_cursor(&mut self, text: &str, cx: &mut Context<Self>) {
2097        let replaces_selection = self.selection.as_ref().is_some_and(|selection| {
2098            let (start, end) = selection.range();
2099            self.pos_to_byte_offset(start) < self.pos_to_byte_offset(end)
2100        });
2101        if let Some(selection) = self.selection.take() {
2102            self.delete_selection_internal(selection, cx);
2103        }
2104
2105        let byte_offset = self.pos_to_byte_offset(self.cursor);
2106        let new_end_byte = byte_offset + text.len();
2107        let plan = TextEditPlan::new(self, byte_offset, byte_offset, new_end_byte);
2108        self.undo_stack.push(EditOp::Insert {
2109            byte_offset,
2110            text: text.to_string(),
2111        });
2112        self.redo_stack.clear();
2113
2114        self.rope_insert(byte_offset, text);
2115        self.mark_modified();
2116
2117        self.cursor = self.byte_offset_to_pos(new_end_byte);
2118        self.update_syntax_tree_for_edit(plan, cx);
2119        self.invalidate_after_text_edit(plan, text.contains('\n'));
2120        if replaces_selection {
2121            self.group_last_edits(2);
2122        }
2123    }
2124
2125    fn delete_selection_internal(&mut self, selection: Selection, cx: &mut Context<Self>) {
2126        let (start, end) = selection.range();
2127        let start_offset = self.pos_to_byte_offset(start);
2128        let end_offset = self.pos_to_byte_offset(end);
2129
2130        if start_offset >= end_offset {
2131            self.cursor = start;
2132            return;
2133        }
2134
2135        let plan = TextEditPlan::new(self, start_offset, end_offset, start_offset);
2136        let deleted: String = self.rope.byte_slice(start_offset..end_offset).into();
2137        let line_structure_changed = deleted.contains('\n');
2138        self.undo_stack.push(EditOp::Delete {
2139            byte_offset: start_offset,
2140            text: deleted,
2141        });
2142        self.redo_stack.clear();
2143
2144        self.rope_remove(start_offset, end_offset);
2145        self.mark_modified();
2146        self.cursor = start;
2147        self.clamp_cursor();
2148        self.update_syntax_tree_for_edit(plan, cx);
2149        self.invalidate_after_text_edit(plan, line_structure_changed);
2150    }
2151
2152    fn get_selection_text(&self, selection: &Selection) -> String {
2153        let (start, end) = selection.range();
2154        let start_offset = self.pos_to_byte_offset(start);
2155        let end_offset = self.pos_to_byte_offset(end);
2156        if start_offset >= end_offset {
2157            return String::new();
2158        }
2159        self.rope.byte_slice(start_offset..end_offset).into()
2160    }
2161
2162    fn find_word_boundary_left(&self, pos: Position) -> Position {
2163        if pos.col == 0 {
2164            if pos.line == 0 {
2165                return pos;
2166            }
2167            return Position::new(pos.line - 1, self.line_len(pos.line - 1));
2168        }
2169        let line_text = self.line_text(pos.line);
2170        let boundaries: Vec<usize> = line_text
2171            .char_indices()
2172            .map(|(index, _)| index)
2173            .chain(std::iter::once(line_text.len()))
2174            .collect();
2175        let mut char_index = boundaries
2176            .partition_point(|&boundary| boundary < floor_char_boundary(&line_text, pos.col));
2177
2178        while char_index > 0 {
2179            let char_start = boundaries[char_index - 1];
2180            let ch = line_text[char_start..boundaries[char_index]].chars().next();
2181            if !ch.is_some_and(char::is_whitespace) {
2182                break;
2183            }
2184            char_index -= 1;
2185        }
2186
2187        if char_index > 0 {
2188            let char_start = boundaries[char_index - 1];
2189            let ch = line_text[char_start..boundaries[char_index]].chars().next();
2190            if ch.is_some_and(Self::is_word_char) {
2191                while char_index > 0 {
2192                    let char_start = boundaries[char_index - 1];
2193                    let ch = line_text[char_start..boundaries[char_index]].chars().next();
2194                    if !ch.is_some_and(Self::is_word_char) {
2195                        break;
2196                    }
2197                    char_index -= 1;
2198                }
2199            } else {
2200                char_index -= 1;
2201            }
2202        }
2203
2204        Position::new(pos.line, boundaries[char_index])
2205    }
2206
2207    fn find_word_boundary_right(&self, pos: Position) -> Position {
2208        let line_len = self.line_len(pos.line);
2209        if pos.col >= line_len {
2210            if pos.line >= self.total_lines() - 1 {
2211                return pos;
2212            }
2213            return Position::new(pos.line + 1, 0);
2214        }
2215        let line_text = self.line_text(pos.line);
2216        let boundaries: Vec<usize> = line_text
2217            .char_indices()
2218            .map(|(index, _)| index)
2219            .chain(std::iter::once(line_text.len()))
2220            .collect();
2221        let start_index = boundaries
2222            .partition_point(|&boundary| boundary < floor_char_boundary(&line_text, pos.col));
2223        let mut char_index = start_index;
2224
2225        if char_index < boundaries.len() - 1 {
2226            let char_start = boundaries[char_index];
2227            let ch = line_text[char_start..boundaries[char_index + 1]]
2228                .chars()
2229                .next();
2230            if ch.is_some_and(Self::is_word_char) {
2231                while char_index < boundaries.len() - 1 {
2232                    let char_start = boundaries[char_index];
2233                    let ch = line_text[char_start..boundaries[char_index + 1]]
2234                        .chars()
2235                        .next();
2236                    if !ch.is_some_and(Self::is_word_char) {
2237                        break;
2238                    }
2239                    char_index += 1;
2240                }
2241            }
2242            while char_index < boundaries.len() - 1 {
2243                let char_start = boundaries[char_index];
2244                let ch = line_text[char_start..boundaries[char_index + 1]]
2245                    .chars()
2246                    .next();
2247                if !ch.is_some_and(char::is_whitespace) {
2248                    break;
2249                }
2250                char_index += 1;
2251            }
2252            if char_index == start_index {
2253                char_index += 1;
2254            }
2255        }
2256
2257        Position::new(pos.line, boundaries[char_index.min(boundaries.len() - 1)])
2258    }
2259
2260    fn is_word_char(ch: char) -> bool {
2261        ch.is_alphanumeric() || ch == '_'
2262    }
2263
2264    // UTF-16 conversion helpers for IME support
2265    fn offset_to_utf16(&self, byte_offset: usize) -> usize {
2266        let byte_offset = min(byte_offset, self.rope.len_bytes());
2267        let char_offset = self.rope.byte_to_char(byte_offset);
2268        let mut utf16_offset = 0;
2269        for ch_idx in 0..char_offset {
2270            let ch = self.rope.char(ch_idx);
2271            utf16_offset += ch.len_utf16();
2272        }
2273        utf16_offset
2274    }
2275
2276    fn offset_from_utf16(&self, utf16_offset: usize) -> usize {
2277        let mut utf16_count = 0;
2278        let mut byte_offset = 0;
2279        for ch_idx in 0..self.rope.len_chars() {
2280            if utf16_count >= utf16_offset {
2281                break;
2282            }
2283            let ch = self.rope.char(ch_idx);
2284            utf16_count += ch.len_utf16();
2285            byte_offset += ch.len_utf8();
2286        }
2287        byte_offset
2288    }
2289
2290    fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
2291        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
2292    }
2293
2294    fn range_from_utf16(&self, range: &Range<usize>) -> Range<usize> {
2295        self.offset_from_utf16(range.start)..self.offset_from_utf16(range.end)
2296    }
2297
2298    pub fn undo(&mut self, _: &Undo, _: &mut Window, cx: &mut Context<Self>) {
2299        if let Some(op) = self.undo_stack.pop() {
2300            self.apply_edit_op_with_fold_state(&op, true);
2301            self.redo_stack.push(op);
2302            self.selection = None;
2303            self.mark_modified();
2304            self.update_syntax_tree();
2305            self.invalidate_text_edit_caches();
2306            cx.notify();
2307        }
2308    }
2309
2310    pub fn redo(&mut self, _: &Redo, _: &mut Window, cx: &mut Context<Self>) {
2311        if let Some(op) = self.redo_stack.pop() {
2312            self.apply_edit_op_with_fold_state(&op, false);
2313            self.undo_stack.push(op);
2314            self.selection = None;
2315            self.mark_modified();
2316            self.update_syntax_tree();
2317            self.invalidate_text_edit_caches();
2318            cx.notify();
2319        }
2320    }
2321
2322    pub fn move_up(&mut self, _: &MoveUp, _: &mut Window, cx: &mut Context<Self>) {
2323        if self.is_overlay_active(cx) {
2324            cx.propagate();
2325            return;
2326        }
2327        if self.cursor.line > 0 {
2328            self.cursor.line -= 1;
2329            self.clamp_cursor();
2330        }
2331        self.selection = None;
2332        cx.notify();
2333    }
2334
2335    pub fn move_down(&mut self, _: &MoveDown, _: &mut Window, cx: &mut Context<Self>) {
2336        if self.is_overlay_active(cx) {
2337            cx.propagate();
2338            return;
2339        }
2340        if self.cursor.line < self.total_lines() - 1 {
2341            self.cursor.line += 1;
2342            self.clamp_cursor();
2343        }
2344        self.selection = None;
2345        cx.notify();
2346    }
2347
2348    pub fn move_left(&mut self, _: &MoveLeft, _: &mut Window, cx: &mut Context<Self>) {
2349        if self.cursor.col > 0 {
2350            let line_text = self.line_text(self.cursor.line);
2351            let col = floor_char_boundary(&line_text, self.cursor.col);
2352            self.cursor.col = match line_text[..col].chars().last() {
2353                Some(c) => col - c.len_utf8(),
2354                None => 0,
2355            };
2356        } else if self.cursor.line > 0 {
2357            self.cursor.line -= 1;
2358            self.cursor.col = self.line_len(self.cursor.line);
2359        }
2360        self.selection = None;
2361        cx.notify();
2362    }
2363
2364    pub fn move_right(&mut self, _: &MoveRight, _: &mut Window, cx: &mut Context<Self>) {
2365        let line_text = self.line_text(self.cursor.line);
2366        let col = floor_char_boundary(&line_text, self.cursor.col);
2367        if let Some(c) = line_text[col..].chars().next() {
2368            self.cursor.col = col + c.len_utf8();
2369        } else if self.cursor.line < self.total_lines() - 1 {
2370            self.cursor.line += 1;
2371            self.cursor.col = 0;
2372        }
2373        self.selection = None;
2374        cx.notify();
2375    }
2376
2377    pub fn move_word_left(&mut self, _: &MoveWordLeft, _: &mut Window, cx: &mut Context<Self>) {
2378        self.cursor = self.find_word_boundary_left(self.cursor);
2379        self.selection = None;
2380        cx.notify();
2381    }
2382
2383    pub fn move_word_right(&mut self, _: &MoveWordRight, _: &mut Window, cx: &mut Context<Self>) {
2384        self.cursor = self.find_word_boundary_right(self.cursor);
2385        self.selection = None;
2386        cx.notify();
2387    }
2388
2389    pub fn move_to_line_start(
2390        &mut self,
2391        _: &MoveToLineStart,
2392        _: &mut Window,
2393        cx: &mut Context<Self>,
2394    ) {
2395        self.cursor.col = 0;
2396        self.selection = None;
2397        cx.notify();
2398    }
2399
2400    pub fn move_to_line_end(&mut self, _: &MoveToLineEnd, _: &mut Window, cx: &mut Context<Self>) {
2401        self.cursor.col = self.line_len(self.cursor.line);
2402        self.selection = None;
2403        cx.notify();
2404    }
2405
2406    pub fn move_to_doc_start(
2407        &mut self,
2408        _: &MoveToDocStart,
2409        _: &mut Window,
2410        cx: &mut Context<Self>,
2411    ) {
2412        self.cursor = Position::zero();
2413        self.selection = None;
2414        cx.notify();
2415    }
2416
2417    pub fn move_to_doc_end(&mut self, _: &MoveToDocEnd, _: &mut Window, cx: &mut Context<Self>) {
2418        let last = self.total_lines() - 1;
2419        self.cursor = Position::new(last, self.line_len(last));
2420        self.selection = None;
2421        cx.notify();
2422    }
2423
2424    pub fn page_up(&mut self, _: &PageUp, _: &mut Window, cx: &mut Context<Self>) {
2425        let page_size = 30;
2426        self.cursor.line = self.cursor.line.saturating_sub(page_size);
2427        self.clamp_cursor();
2428        self.selection = None;
2429        cx.notify();
2430    }
2431
2432    pub fn page_down(&mut self, _: &PageDown, _: &mut Window, cx: &mut Context<Self>) {
2433        let page_size = 30;
2434        self.cursor.line = min(self.cursor.line + page_size, self.total_lines() - 1);
2435        self.clamp_cursor();
2436        self.selection = None;
2437        cx.notify();
2438    }
2439
2440    fn start_selection_if_needed(&mut self) {
2441        if self.selection.is_none() {
2442            self.selection = Some(Selection::new(self.cursor, self.cursor));
2443        }
2444    }
2445
2446    pub fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
2447        self.start_selection_if_needed();
2448        if self.cursor.line > 0 {
2449            self.cursor.line -= 1;
2450            self.clamp_cursor();
2451            if let Some(ref mut sel) = self.selection {
2452                sel.cursor = self.cursor;
2453            }
2454            cx.notify();
2455        }
2456    }
2457
2458    pub fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
2459        self.start_selection_if_needed();
2460        if self.cursor.line < self.total_lines() - 1 {
2461            self.cursor.line += 1;
2462            self.clamp_cursor();
2463            if let Some(ref mut sel) = self.selection {
2464                sel.cursor = self.cursor;
2465            }
2466            cx.notify();
2467        }
2468    }
2469
2470    pub fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
2471        self.start_selection_if_needed();
2472        let line_text = self.line_text(self.cursor.line);
2473        let col = floor_char_boundary(&line_text, self.cursor.col);
2474        if col > 0 {
2475            self.cursor.col = line_text[..col]
2476                .chars()
2477                .next_back()
2478                .map(|character| col - character.len_utf8())
2479                .unwrap_or(0);
2480        } else if self.cursor.line > 0 {
2481            self.cursor.line -= 1;
2482            self.cursor.col = self.line_len(self.cursor.line);
2483        } else {
2484            self.cursor.col = 0;
2485        }
2486        if let Some(ref mut sel) = self.selection {
2487            sel.cursor = self.cursor;
2488        }
2489        cx.notify();
2490    }
2491
2492    pub fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
2493        self.start_selection_if_needed();
2494        let line_text = self.line_text(self.cursor.line);
2495        let col = floor_char_boundary(&line_text, self.cursor.col);
2496        if let Some(character) = line_text[col..].chars().next() {
2497            self.cursor.col = col + character.len_utf8();
2498        } else if self.cursor.line < self.total_lines() - 1 {
2499            self.cursor.line += 1;
2500            self.cursor.col = 0;
2501        } else {
2502            self.cursor.col = line_text.len();
2503        }
2504        if let Some(ref mut sel) = self.selection {
2505            sel.cursor = self.cursor;
2506        }
2507        cx.notify();
2508    }
2509
2510    pub fn select_to_line_start(
2511        &mut self,
2512        _: &SelectToLineStart,
2513        _: &mut Window,
2514        cx: &mut Context<Self>,
2515    ) {
2516        self.start_selection_if_needed();
2517        self.cursor.col = 0;
2518        if let Some(ref mut sel) = self.selection {
2519            sel.cursor = self.cursor;
2520        }
2521        cx.notify();
2522    }
2523
2524    pub fn select_to_line_end(
2525        &mut self,
2526        _: &SelectToLineEnd,
2527        _: &mut Window,
2528        cx: &mut Context<Self>,
2529    ) {
2530        self.start_selection_if_needed();
2531        self.cursor.col = self.line_len(self.cursor.line);
2532        if let Some(ref mut sel) = self.selection {
2533            sel.cursor = self.cursor;
2534        }
2535        cx.notify();
2536    }
2537
2538    pub fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
2539        let start = Position::zero();
2540        let last = self.total_lines() - 1;
2541        let end = Position::new(last, self.line_len(last));
2542        self.selection = Some(Selection::new(start, end));
2543        self.cursor = end;
2544        cx.notify();
2545    }
2546
2547    pub fn backspace(&mut self, _: &Backspace, _: &mut Window, cx: &mut Context<Self>) {
2548        if self.read_only {
2549            return;
2550        }
2551        if let Some(selection) = self.selection.take() {
2552            self.delete_selection_internal(selection, cx);
2553            cx.notify();
2554            return;
2555        }
2556        let offset = self.pos_to_byte_offset(self.cursor);
2557        if offset == 0 {
2558            return;
2559        }
2560
2561        let delete_pair = self.is_between_auto_close_pair();
2562        let char_idx = self.rope.byte_to_char(offset);
2563        let prev_char_byte = self.rope.char_to_byte(char_idx.saturating_sub(1));
2564        let del_start = prev_char_byte;
2565        let del_end = if delete_pair {
2566            let next_char_byte = if char_idx < self.rope.len_chars() {
2567                self.rope.char_to_byte(char_idx + 1)
2568            } else {
2569                self.rope.len_bytes()
2570            };
2571            next_char_byte.min(self.rope.len_bytes())
2572        } else {
2573            offset
2574        };
2575
2576        let plan = TextEditPlan::new(self, del_start, del_end, del_start);
2577        let deleted: String = self.rope.byte_slice(del_start..del_end).into();
2578        let line_structure_changed = deleted.contains('\n');
2579        self.undo_stack.push(EditOp::Delete {
2580            byte_offset: del_start,
2581            text: deleted,
2582        });
2583        self.redo_stack.clear();
2584        self.rope_remove(del_start, del_end);
2585        self.mark_modified();
2586        self.cursor = self.byte_offset_to_pos(del_start);
2587        self.update_syntax_tree_for_edit(plan, cx);
2588        self.invalidate_after_text_edit(plan, line_structure_changed);
2589        cx.notify();
2590    }
2591
2592    pub fn delete(&mut self, _: &Delete, _: &mut Window, cx: &mut Context<Self>) {
2593        if self.read_only {
2594            return;
2595        }
2596        if let Some(selection) = self.selection.take() {
2597            self.delete_selection_internal(selection, cx);
2598            cx.notify();
2599            return;
2600        }
2601        let offset = self.pos_to_byte_offset(self.cursor);
2602        if offset >= self.rope.len_bytes() {
2603            return;
2604        }
2605        let char_idx = self.rope.byte_to_char(offset);
2606        let next_char_byte = if char_idx + 1 <= self.rope.len_chars() {
2607            self.rope.char_to_byte(char_idx + 1)
2608        } else {
2609            self.rope.len_bytes()
2610        };
2611        let del_end = min(next_char_byte, self.rope.len_bytes());
2612        let plan = TextEditPlan::new(self, offset, del_end, offset);
2613        let deleted: String = self.rope.byte_slice(offset..del_end).into();
2614        let line_structure_changed = deleted.contains('\n');
2615        self.undo_stack.push(EditOp::Delete {
2616            byte_offset: offset,
2617            text: deleted,
2618        });
2619        self.redo_stack.clear();
2620        self.rope_remove(offset, del_end);
2621        self.mark_modified();
2622        self.update_syntax_tree_for_edit(plan, cx);
2623        self.invalidate_after_text_edit(plan, line_structure_changed);
2624        cx.notify();
2625    }
2626
2627    pub fn delete_word(&mut self, _: &DeleteWord, _: &mut Window, cx: &mut Context<Self>) {
2628        if self.read_only {
2629            return;
2630        }
2631        let word_start = self.find_word_boundary_left(self.cursor);
2632        if word_start == self.cursor {
2633            return;
2634        }
2635        let start_offset = self.pos_to_byte_offset(word_start);
2636        let end_offset = self.pos_to_byte_offset(self.cursor);
2637        let plan = TextEditPlan::new(self, start_offset, end_offset, start_offset);
2638        let deleted: String = self.rope.byte_slice(start_offset..end_offset).into();
2639        let line_structure_changed = deleted.contains('\n');
2640        self.undo_stack.push(EditOp::Delete {
2641            byte_offset: start_offset,
2642            text: deleted,
2643        });
2644        self.redo_stack.clear();
2645        self.rope_remove(start_offset, end_offset);
2646        self.mark_modified();
2647        self.cursor = word_start;
2648        self.update_syntax_tree_for_edit(plan, cx);
2649        self.invalidate_after_text_edit(plan, line_structure_changed);
2650        cx.notify();
2651    }
2652
2653    pub fn enter(&mut self, _: &Enter, _: &mut Window, cx: &mut Context<Self>) {
2654        if self.is_overlay_active(cx) {
2655            cx.propagate();
2656            return;
2657        }
2658        if self.read_only {
2659            return;
2660        }
2661
2662        let line_text = self.line_text(self.cursor.line);
2663        let col = floor_char_boundary(&line_text, self.cursor.col);
2664        let before_cursor = &line_text[..col];
2665        let after_cursor = &line_text[col..];
2666
2667        let base_indent = before_cursor.len() - before_cursor.trim_start().len();
2668        let trimmed = before_cursor.trim_end();
2669        let increase = matches!(trimmed.as_bytes().last(), Some(b'{' | b'(' | b'[' | b':'));
2670
2671        let indent_str = " ".repeat(base_indent);
2672        let extra_indent = " ".repeat(self.tab_size);
2673
2674        let after_trimmed = after_cursor.trim_start();
2675        let between_pair = increase
2676            && !after_trimmed.is_empty()
2677            && matches!(
2678                (trimmed.as_bytes().last(), after_trimmed.as_bytes().first()),
2679                (Some(b'{'), Some(b'}')) | (Some(b'('), Some(b')')) | (Some(b'['), Some(b']'))
2680            );
2681
2682        if between_pair {
2683            let text = format!("\n{}{}\n{}", indent_str, extra_indent, indent_str);
2684            self.insert_text_at_cursor(&text, cx);
2685            let target_line = self.cursor.line - 1;
2686            let target_col = base_indent + self.tab_size;
2687            self.cursor = Position::new(target_line, target_col);
2688        } else if increase {
2689            let text = format!("\n{}{}", indent_str, extra_indent);
2690            self.insert_text_at_cursor(&text, cx);
2691        } else {
2692            let text = format!("\n{}", indent_str);
2693            self.insert_text_at_cursor(&text, cx);
2694        }
2695        self.ensure_cursor_visible(cx);
2696    }
2697
2698    pub fn tab(&mut self, _: &Tab, _: &mut Window, cx: &mut Context<Self>) {
2699        if self.is_overlay_active(cx) {
2700            cx.propagate();
2701            return;
2702        }
2703        if self.read_only {
2704            return;
2705        }
2706        let spaces = " ".repeat(self.tab_size);
2707        self.insert_text_at_cursor(&spaces, cx);
2708    }
2709
2710    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2711        if let Some(selection) = &self.selection {
2712            let text = self.get_selection_text(selection);
2713            cx.write_to_clipboard(ClipboardItem::new_string(text));
2714        }
2715    }
2716
2717    pub fn cut(&mut self, _: &Cut, _: &mut Window, cx: &mut Context<Self>) {
2718        if self.read_only {
2719            return;
2720        }
2721        if let Some(selection) = self.selection.take() {
2722            let text = self.get_selection_text(&selection);
2723            cx.write_to_clipboard(ClipboardItem::new_string(text));
2724            self.delete_selection_internal(selection, cx);
2725            cx.notify();
2726        }
2727    }
2728
2729    pub fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
2730        if self.read_only {
2731            return;
2732        }
2733        if let Some(item) = cx.read_from_clipboard() {
2734            if let Some(text) = item.text() {
2735                self.insert_text_at_cursor(&text, cx);
2736                self.marked_range = None;
2737            }
2738        }
2739    }
2740
2741    pub fn selection_text(&self) -> Option<String> {
2742        self.selection
2743            .as_ref()
2744            .map(|sel| self.get_selection_text(sel))
2745            .filter(|s| !s.is_empty())
2746    }
2747
2748    pub fn search_query(&self) -> &str {
2749        &self.search_query
2750    }
2751
2752    pub fn search_match_count(&self) -> usize {
2753        self.search_matches.len()
2754    }
2755
2756    pub fn current_match_index(&self) -> Option<usize> {
2757        self.current_match_idx
2758    }
2759
2760    pub fn search_case_sensitive(&self) -> bool {
2761        self.search_case_sensitive
2762    }
2763
2764    pub fn search_use_regex(&self) -> bool {
2765        self.search_use_regex
2766    }
2767
2768    pub fn find_all(&mut self, query: &str, cx: &mut Context<Self>) {
2769        self.search_query = query.to_string();
2770
2771        if query.is_empty() {
2772            self.advance_search_generation();
2773            self.clear_search_results();
2774            self.search_task = None;
2775            cx.notify();
2776            return;
2777        }
2778
2779        // Schedule a debounced search — any new call cancels the previous one.
2780        // This ensures typing always takes priority; search only runs after
2781        // the user stops typing for 200ms.
2782        self.schedule_search(cx);
2783    }
2784
2785    fn schedule_search(&mut self, cx: &mut Context<Self>) {
2786        let search_generation = self.advance_search_generation();
2787        let query_owned = self.search_query.clone();
2788        let use_regex = self.search_use_regex;
2789        let case_sensitive = self.search_case_sensitive;
2790        let entity = cx.entity().clone();
2791
2792        // Cancel any in-flight search
2793        self.search_task = Some(cx.spawn(async move |_, cx| {
2794            // Wait for user to stop typing
2795            Timer::after(Duration::from_millis(200)).await;
2796
2797            // Snapshot content and cursor on the main thread, then search in background
2798            let search_input = cx.update(|cx| {
2799                let state = entity.read(cx);
2800                let content = state.rope.to_string();
2801                let cursor_byte = state.pos_to_byte_offset(state.cursor);
2802                (content, cursor_byte, state.content_version)
2803            });
2804
2805            let Ok((content, cursor_byte, content_version)) = search_input else {
2806                return;
2807            };
2808
2809            let query_for_commit = query_owned.clone();
2810            let matches = smol::unblock(move || {
2811                let mut results = Vec::new();
2812                if use_regex {
2813                    let pattern = if case_sensitive {
2814                        query_owned.to_string()
2815                    } else {
2816                        format!("(?i){}", query_owned)
2817                    };
2818                    if let Ok(re) = Regex::new(&pattern) {
2819                        for m in re.find_iter(&content) {
2820                            results.push((m.start(), m.end()));
2821                        }
2822                    }
2823                } else {
2824                    if case_sensitive {
2825                        let needle_len = query_owned.len();
2826                        let mut start = 0;
2827                        while let Some(pos) = content[start..].find(&query_owned) {
2828                            let match_start = start + pos;
2829                            let match_end = match_start + needle_len;
2830                            results.push((match_start, match_end));
2831                            // Keep overlapping matches while advancing on a
2832                            // UTF-8 boundary. `match_start + 1` can point
2833                            // into a multi-byte character and panic on the
2834                            // next slice.
2835                            let next_char_len = content[match_start..]
2836                                .chars()
2837                                .next()
2838                                .map(|character| character.len_utf8())
2839                                .unwrap_or(1);
2840                            start = match_start + next_char_len;
2841                        }
2842                    } else {
2843                        results = find_case_insensitive_matches(&content, &query_owned);
2844                    }
2845                }
2846                results
2847            })
2848            .await;
2849
2850            let _ = cx.update(|cx| {
2851                entity.update(cx, |state, cx| {
2852                    if state.commit_search_result(
2853                        search_generation,
2854                        content_version,
2855                        &query_for_commit,
2856                        use_regex,
2857                        case_sensitive,
2858                        cursor_byte,
2859                        matches,
2860                    ) {
2861                        cx.notify();
2862                    }
2863                });
2864            });
2865        }));
2866    }
2867
2868    fn commit_search_result(
2869        &mut self,
2870        generation: u64,
2871        content_version: u64,
2872        query: &str,
2873        use_regex: bool,
2874        case_sensitive: bool,
2875        cursor_byte: usize,
2876        matches: Vec<(usize, usize)>,
2877    ) -> bool {
2878        if generation != self.search_generation
2879            || content_version != self.content_version
2880            || query != self.search_query
2881            || use_regex != self.search_use_regex
2882            || case_sensitive != self.search_case_sensitive
2883        {
2884            return false;
2885        }
2886
2887        self.search_matches = matches;
2888        if !self.search_matches.is_empty() {
2889            let idx = self
2890                .search_matches
2891                .iter()
2892                .position(|(start, _)| *start >= cursor_byte)
2893                .unwrap_or(0);
2894            self.current_match_idx = Some(idx);
2895            self.scroll_to_match(idx);
2896        } else {
2897            self.current_match_idx = None;
2898        }
2899        true
2900    }
2901
2902    pub fn find_next(&mut self, cx: &mut Context<Self>) {
2903        if self.search_matches.is_empty() {
2904            return;
2905        }
2906        let next = match self.current_match_idx {
2907            Some(idx) => (idx + 1) % self.search_matches.len(),
2908            None => 0,
2909        };
2910        self.current_match_idx = Some(next);
2911        let (start, _) = self.search_matches[next];
2912        self.cursor = self.byte_offset_to_pos(start);
2913        self.selection = None;
2914        self.scroll_to_match(next);
2915        cx.notify();
2916    }
2917
2918    pub fn find_previous(&mut self, cx: &mut Context<Self>) {
2919        if self.search_matches.is_empty() {
2920            return;
2921        }
2922        let prev = match self.current_match_idx {
2923            Some(0) | None => self.search_matches.len() - 1,
2924            Some(idx) => idx - 1,
2925        };
2926        self.current_match_idx = Some(prev);
2927        let (start, _) = self.search_matches[prev];
2928        self.cursor = self.byte_offset_to_pos(start);
2929        self.selection = None;
2930        self.scroll_to_match(prev);
2931        cx.notify();
2932    }
2933
2934    fn is_valid_match_range(&self, start: usize, end: usize) -> bool {
2935        if start > end || end > self.rope.len_bytes() {
2936            return false;
2937        }
2938        self.rope.char_to_byte(self.rope.byte_to_char(start)) == start
2939            && self.rope.char_to_byte(self.rope.byte_to_char(end)) == end
2940    }
2941
2942    pub fn replace_current(&mut self, replacement: &str, cx: &mut Context<Self>) {
2943        if self.read_only {
2944            return;
2945        }
2946        let idx = match self.current_match_idx {
2947            Some(i) if i < self.search_matches.len() => i,
2948            _ => return,
2949        };
2950        let (start, end) = self.search_matches[idx];
2951        if !self.is_valid_match_range(start, end) {
2952            let query = self.search_query.clone();
2953            self.find_all(&query, cx);
2954            return;
2955        }
2956        let positions = self.snapshot_positions();
2957        let new_end = start + replacement.len();
2958        let plan = TextEditPlan::new(self, start, end, new_end);
2959        let deleted: String = self.rope.byte_slice(start..end).into();
2960        let line_structure_changed = deleted.contains('\n') || replacement.contains('\n');
2961        self.undo_stack.push(EditOp::Delete {
2962            byte_offset: start,
2963            text: deleted,
2964        });
2965        self.rope_remove(start, end);
2966        self.undo_stack.push(EditOp::Insert {
2967            byte_offset: start,
2968            text: replacement.to_string(),
2969        });
2970        self.rope_insert(start, replacement);
2971        self.redo_stack.clear();
2972        self.group_last_edits(2);
2973        self.mark_modified();
2974        self.update_syntax_tree_for_edit(plan, cx);
2975        self.restore_positions_after_edit(positions, plan.range);
2976        self.invalidate_after_text_edit(plan, line_structure_changed);
2977        let query = self.search_query.clone();
2978        self.find_all(&query, cx);
2979    }
2980
2981    pub fn replace_all(&mut self, replacement: &str, cx: &mut Context<Self>) {
2982        if self.read_only || self.search_matches.is_empty() {
2983            return;
2984        }
2985        let matches: Vec<_> = self.search_matches.iter().rev().copied().collect();
2986        if matches
2987            .iter()
2988            .any(|&(start, end)| !self.is_valid_match_range(start, end))
2989        {
2990            let query = self.search_query.clone();
2991            self.find_all(&query, cx);
2992            return;
2993        }
2994        let mut line_structure_changed = replacement.contains('\n');
2995        for (start, end) in matches {
2996            let positions = self.snapshot_positions();
2997            let deleted: String = self.rope.byte_slice(start..end).into();
2998            line_structure_changed |= deleted.contains('\n');
2999            self.undo_stack.push(EditOp::Delete {
3000                byte_offset: start,
3001                text: deleted,
3002            });
3003            self.rope_remove(start, end);
3004            self.undo_stack.push(EditOp::Insert {
3005                byte_offset: start,
3006                text: replacement.to_string(),
3007            });
3008            self.rope_insert(start, replacement);
3009            self.restore_positions_after_edit(
3010                positions,
3011                TextEditRange {
3012                    start,
3013                    old_end: end,
3014                    new_end: start + replacement.len(),
3015                },
3016            );
3017        }
3018        self.redo_stack.clear();
3019        self.group_last_edits(self.search_matches.len().saturating_mul(2));
3020        self.mark_modified();
3021        self.update_syntax_tree();
3022        self.invalidate_after_edit(line_structure_changed);
3023        let query = self.search_query.clone();
3024        self.find_all(&query, cx);
3025    }
3026
3027    /// Full invalidation — clears all caches. Use for structural changes
3028    /// (file load, language change, fold/unfold).
3029    fn invalidate_all_caches(&mut self) {
3030        self.line_layouts.clear();
3031        self.line_content_hashes.clear();
3032        self.highlight_cache_version = u64::MAX;
3033        self.max_line_width = px(0.0);
3034    }
3035
3036    fn map_fold_ranges(ranges: &[FoldRange], edit: LineEditRange) -> Vec<FoldRange> {
3037        ranges
3038            .iter()
3039            .filter_map(|range| edit.map_fold_range(*range))
3040            .collect()
3041    }
3042
3043    fn update_fold_state_after_line_edit(&mut self, edit: LineEditRange) {
3044        self.fold_ranges = Self::map_fold_ranges(&self.fold_ranges, edit);
3045        self.folded = Self::map_fold_ranges(&self.folded, edit);
3046        self.cached_display_lines = if self.folded.is_empty() {
3047            None
3048        } else {
3049            Some(Rc::new(self.compute_display_lines()))
3050        };
3051        self.clamp_scroll_after_fold();
3052    }
3053
3054    fn invalidate_text_edit_caches(&mut self) {
3055        self.line_layouts.clear();
3056        self.line_content_hashes.clear();
3057        self.highlight_cache_version = u64::MAX;
3058        // Search matches hold byte ranges into the old content and are
3059        // dropped after every committed text edit.
3060        self.clear_search_results();
3061    }
3062
3063    /// Invalidation for text edits. Clears all caches since line indices
3064    /// shift on insert/delete, making index-keyed caches stale. Search
3065    /// matches hold byte ranges into the old content and are dropped too.
3066    fn invalidate_after_edit(&mut self, line_structure_changed: bool) {
3067        self.invalidate_text_edit_caches();
3068        if line_structure_changed {
3069            self.clear_fold_state();
3070        }
3071        // Keep the previous maximum during incremental edits. Clearing it
3072        // would underestimate off-screen long lines until they are rendered
3073        // again, temporarily shrinking the horizontal scroll range. Full
3074        // document replacement still resets it via invalidate_all_caches.
3075    }
3076
3077    fn invalidate_after_line_edit(&mut self, edit: LineEditRange) {
3078        self.invalidate_text_edit_caches();
3079        self.update_fold_state_after_line_edit(edit);
3080    }
3081
3082    fn invalidate_after_text_edit(&mut self, plan: TextEditPlan, line_structure_changed: bool) {
3083        if line_structure_changed {
3084            self.invalidate_after_line_edit(plan.line_edit_range(self));
3085        } else {
3086            self.invalidate_after_edit(false);
3087        }
3088    }
3089
3090    pub fn invalidate_line_layouts(&mut self, cx: &mut Context<Self>) {
3091        self.invalidate_all_caches();
3092        cx.notify();
3093    }
3094
3095    pub fn clear_search(&mut self, cx: &mut Context<Self>) {
3096        self.search_query.clear();
3097        self.advance_search_generation();
3098        self.clear_search_results();
3099        self.search_task = None;
3100        cx.notify();
3101    }
3102
3103    pub fn set_search_case_sensitive(&mut self, val: bool, cx: &mut Context<Self>) {
3104        self.search_case_sensitive = val;
3105        if !self.search_query.is_empty() {
3106            let query = self.search_query.clone();
3107            self.find_all(&query, cx);
3108        } else {
3109            cx.notify();
3110        }
3111    }
3112
3113    pub fn set_search_regex(&mut self, val: bool, cx: &mut Context<Self>) {
3114        self.search_use_regex = val;
3115        if !self.search_query.is_empty() {
3116            let query = self.search_query.clone();
3117            self.find_all(&query, cx);
3118        } else {
3119            cx.notify();
3120        }
3121    }
3122
3123    pub fn goto_line(&mut self, line: usize, cx: &mut Context<Self>) {
3124        let target = line
3125            .saturating_sub(1)
3126            .min(self.total_lines().saturating_sub(1));
3127        self.cursor = Position::new(target, 0);
3128        self.selection = None;
3129        self.ensure_cursor_visible(cx);
3130    }
3131
3132    fn scroll_to_match(&mut self, idx: usize) {
3133        if idx >= self.search_matches.len() {
3134            return;
3135        }
3136        let (start, _) = self.search_matches[idx];
3137        let pos = self.byte_offset_to_pos(start);
3138        let line_height = self.line_height;
3139        let padding_top = px(12.0);
3140        let viewport_bounds = self.scroll_handle.bounds();
3141        let viewport_height = viewport_bounds.size.height;
3142        let offset = self.scroll_handle.offset();
3143        let target_y = padding_top + line_height * (pos.line as f32);
3144        let current_top = -offset.y;
3145        let current_bottom = current_top + viewport_height;
3146
3147        let mut new_offset_y = offset.y;
3148        if target_y < current_top || target_y + line_height > current_bottom {
3149            new_offset_y = -(target_y - viewport_height / 2.0 + line_height / 2.0);
3150            let max_offset = self.scroll_handle.max_offset().height;
3151            new_offset_y = new_offset_y.max(-max_offset).min(px(0.0));
3152        }
3153
3154        if (new_offset_y - offset.y).abs() > px(0.0) {
3155            self.scroll_handle.set_offset(point(offset.x, new_offset_y));
3156        }
3157    }
3158
3159    fn ensure_cursor_visible(&mut self, cx: &mut Context<Self>) {
3160        let line_height = self.line_height;
3161        let padding_top = px(12.0);
3162        let viewport_bounds = self.scroll_handle.bounds();
3163        let viewport_height = viewport_bounds.size.height;
3164        let viewport_width = viewport_bounds.size.width;
3165        let gutter_width = if self.show_line_numbers {
3166            px(80.0)
3167        } else {
3168            px(12.0)
3169        };
3170        let content_width = viewport_width - gutter_width;
3171        let offset = self.scroll_handle.offset();
3172        let mut new_offset_y = offset.y;
3173        let display_row = self
3174            .buffer_line_to_display_row(self.cursor.line)
3175            .unwrap_or(0);
3176        let cursor_y = padding_top + line_height * (display_row as f32);
3177        let current_top = -offset.y;
3178        let current_bottom = current_top + viewport_height;
3179
3180        if cursor_y < current_top {
3181            new_offset_y = -cursor_y;
3182        } else if cursor_y + line_height > current_bottom {
3183            new_offset_y = -(cursor_y + line_height - viewport_height);
3184        }
3185
3186        let max_offset = self.scroll_handle.max_offset().height;
3187        new_offset_y = new_offset_y.max(-max_offset).min(px(0.0));
3188
3189        if (new_offset_y - offset.y).abs() > px(0.0) {
3190            self.scroll_handle.set_offset(point(offset.x, new_offset_y));
3191        }
3192
3193        if let Some(layout) = self.line_layouts.get(&self.cursor.line) {
3194            let cursor_x = layout.x_for_index(self.cursor.col);
3195            let visible_left = self.scroll_offset_x;
3196            let visible_right = visible_left + content_width - px(20.0);
3197
3198            if cursor_x < visible_left {
3199                self.scroll_offset_x = (cursor_x - px(20.0)).max(px(0.0));
3200            } else if cursor_x > visible_right {
3201                self.scroll_offset_x = cursor_x - content_width + px(40.0);
3202            }
3203        }
3204
3205        cx.notify();
3206    }
3207
3208    pub fn scroll_horizontal(&mut self, delta: Pixels, cx: &mut Context<Self>) {
3209        let viewport_bounds = self.scroll_handle.bounds();
3210        let gutter_width = if self.show_line_numbers {
3211            px(80.0)
3212        } else {
3213            px(12.0)
3214        };
3215        let content_width = viewport_bounds.size.width - gutter_width;
3216        let max_scroll = (self.max_line_width - content_width + px(40.0)).max(px(0.0));
3217
3218        self.scroll_offset_x = (self.scroll_offset_x + delta).max(px(0.0)).min(max_scroll);
3219        cx.notify();
3220    }
3221
3222    pub fn scroll_offset_x(&self) -> Pixels {
3223        self.scroll_offset_x
3224    }
3225
3226    pub fn max_line_width(&self) -> Pixels {
3227        self.max_line_width
3228    }
3229
3230    fn position_for_mouse(
3231        &self,
3232        mouse_pos: Point<Pixels>,
3233        bounds: Bounds<Pixels>,
3234        gutter_width: Pixels,
3235        line_height: Pixels,
3236    ) -> Position {
3237        let padding_top = px(12.0);
3238        let relative_y = mouse_pos.y - bounds.top() - padding_top;
3239        let display_row_f = (relative_y / line_height).floor();
3240        let display_lines = self.display_lines();
3241        let display_count = display_lines.len();
3242        let display_row = if display_row_f < 0.0 {
3243            0
3244        } else {
3245            min(display_row_f as usize, display_count.saturating_sub(1))
3246        };
3247        let line = display_lines.get(display_row).copied().unwrap_or(0);
3248
3249        let relative_x = mouse_pos.x - bounds.left() - gutter_width + self.scroll_offset_x;
3250        let col = if let Some(layout) = self.line_layouts.get(&line) {
3251            let idx = layout.closest_index_for_x(relative_x);
3252            idx.min(self.line_len(line))
3253        } else {
3254            let approx_char_width = px(8.4);
3255            if relative_x > px(0.0) {
3256                let col = (relative_x / approx_char_width).round() as usize;
3257                floor_char_boundary(&self.line_text(line), col)
3258            } else {
3259                0
3260            }
3261        };
3262
3263        Position::new(line, col)
3264    }
3265
3266    fn start_autoscroll(&mut self, cx: &mut Context<Self>) {
3267        let entity = cx.entity().clone();
3268        let line_height = self.line_height;
3269        self.autoscroll_task = Some(cx.spawn(async move |_, cx| loop {
3270            Timer::after(Duration::from_millis(50)).await;
3271            let should_continue = cx
3272                .update(|cx| {
3273                    entity.update(cx, |state, cx| {
3274                        if !state.is_selecting {
3275                            return false;
3276                        }
3277                        let Some(mouse_pos) = state.last_mouse_pos else {
3278                            return true;
3279                        };
3280                        let Some(bounds) = state.last_bounds else {
3281                            return true;
3282                        };
3283
3284                        let viewport_bounds = state.scroll_handle.bounds();
3285                        if viewport_bounds.size.height == px(0.0) {
3286                            return true;
3287                        }
3288                        let viewport_top = viewport_bounds.top();
3289                        let viewport_bottom = viewport_bounds.bottom();
3290                        let mouse_y = mouse_pos.y;
3291                        let edge_zone = line_height * 1.5;
3292                        let mut scrolled = false;
3293
3294                        if mouse_y < viewport_top + edge_zone {
3295                            let speed = ((viewport_top + edge_zone - mouse_y) / edge_zone)
3296                                .max(0.5)
3297                                .min(5.0);
3298                            let offset = state.scroll_handle.offset();
3299                            let new_y = (offset.y + line_height * speed).min(px(0.0));
3300                            state.scroll_handle.set_offset(point(offset.x, new_y));
3301                            scrolled = true;
3302                        } else if mouse_y > viewport_bottom - edge_zone {
3303                            let speed = ((mouse_y - (viewport_bottom - edge_zone)) / edge_zone)
3304                                .max(0.5)
3305                                .min(5.0);
3306                            let offset = state.scroll_handle.offset();
3307                            let max_offset = state.scroll_handle.max_offset().height;
3308                            let new_y = (offset.y - line_height * speed).max(-max_offset);
3309                            state.scroll_handle.set_offset(point(offset.x, new_y));
3310                            scrolled = true;
3311                        }
3312
3313                        if scrolled {
3314                            let gutter_width = state.last_mouse_gutter_width;
3315                            let pos = state.position_for_mouse(
3316                                mouse_pos,
3317                                bounds,
3318                                gutter_width,
3319                                line_height,
3320                            );
3321                            if let Some(ref mut sel) = state.selection {
3322                                sel.cursor = pos;
3323                            } else {
3324                                state.selection = Some(Selection::new(state.cursor, pos));
3325                            }
3326                            state.cursor = pos;
3327                            cx.notify();
3328                        }
3329                        true
3330                    })
3331                })
3332                .unwrap_or(false);
3333            if !should_continue {
3334                break;
3335            }
3336        }));
3337    }
3338
3339    fn on_mouse_down(
3340        &mut self,
3341        event: &MouseDownEvent,
3342        bounds: Bounds<Pixels>,
3343        gutter_width: Pixels,
3344        line_height: Pixels,
3345        _window: &Window,
3346        cx: &mut Context<Self>,
3347    ) {
3348        let click_x = event.position.x - bounds.left();
3349        let padding_top = px(12.0);
3350        let display_row = ((event.position.y - bounds.top() - padding_top) / line_height)
3351            .floor()
3352            .max(0.0) as usize;
3353        let dl = self.display_lines();
3354        let click_line = dl.get(display_row).copied().unwrap_or(0);
3355
3356        if click_x >= gutter_width - px(16.0) && click_x <= gutter_width {
3357            if self.fold_ranges.iter().any(|f| f.start_line == click_line) {
3358                self.toggle_fold_at_line(click_line, cx);
3359                return;
3360            }
3361        }
3362
3363        let pos = self.position_for_mouse(event.position, bounds, gutter_width, line_height);
3364
3365        let now = std::time::Instant::now();
3366        let is_double_click = if let Some(last_time) = self.last_click_time {
3367            now.duration_since(last_time).as_millis() < 500
3368        } else {
3369            false
3370        };
3371        self.last_click_time = Some(now);
3372
3373        if is_double_click {
3374            self.selection = Some(Selection::new(
3375                Position::new(pos.line, 0),
3376                Position::new(pos.line, self.line_len(pos.line)),
3377            ));
3378            self.cursor = Position::new(pos.line, self.line_len(pos.line));
3379        } else if event.modifiers.shift {
3380            if let Some(ref mut sel) = self.selection {
3381                sel.cursor = pos;
3382                self.cursor = pos;
3383            } else {
3384                self.selection = Some(Selection::new(self.cursor, pos));
3385                self.cursor = pos;
3386            }
3387        } else {
3388            self.cursor = pos;
3389            self.selection = None;
3390            self.is_selecting = true;
3391            self.last_mouse_pos = Some(event.position);
3392            self.last_mouse_gutter_width = gutter_width;
3393            self.start_autoscroll(cx);
3394        }
3395
3396        cx.notify();
3397    }
3398
3399    fn on_mouse_move(
3400        &mut self,
3401        event: &MouseMoveEvent,
3402        bounds: Bounds<Pixels>,
3403        gutter_width: Pixels,
3404        line_height: Pixels,
3405        _window: &Window,
3406        cx: &mut Context<Self>,
3407    ) {
3408        if self.dragging_h_scrollbar {
3409            if event.pressed_button != Some(MouseButton::Left) {
3410                self.dragging_h_scrollbar = false;
3411                cx.notify();
3412                return;
3413            }
3414            let max_w = self.max_line_width;
3415            let vp = self.scroll_handle.bounds();
3416            let gw = if self.show_line_numbers {
3417                px(80.0)
3418            } else {
3419                px(12.0)
3420            };
3421            let cw = vp.size.width - gw;
3422            let scroll_range = max_w - cw;
3423
3424            if scroll_range > px(0.0) {
3425                let track_width = vp.size.width;
3426                let click_ratio = (event.position.x - vp.left()) / track_width;
3427                let new_scroll = scroll_range * click_ratio;
3428                self.scroll_offset_x = new_scroll.max(px(0.0)).min(scroll_range);
3429                cx.notify();
3430            }
3431            return;
3432        }
3433
3434        if !self.is_selecting || event.pressed_button != Some(MouseButton::Left) {
3435            if self.is_selecting && event.pressed_button != Some(MouseButton::Left) {
3436                self.is_selecting = false;
3437                self.last_mouse_pos = None;
3438                cx.notify();
3439            }
3440            return;
3441        }
3442
3443        self.last_mouse_pos = Some(event.position);
3444        self.last_mouse_gutter_width = gutter_width;
3445
3446        let pos = self.position_for_mouse(event.position, bounds, gutter_width, line_height);
3447        if let Some(ref mut sel) = self.selection {
3448            sel.cursor = pos;
3449        } else {
3450            self.selection = Some(Selection::new(self.cursor, pos));
3451        }
3452        self.cursor = pos;
3453        self.ensure_cursor_visible(cx);
3454    }
3455
3456    fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, cx: &mut Context<Self>) {
3457        self.is_selecting = false;
3458        self.dragging_h_scrollbar = false;
3459        self.autoscroll_task = None;
3460        self.last_mouse_pos = None;
3461        cx.notify();
3462    }
3463}
3464
3465impl Focusable for EditorState {
3466    fn focus_handle(&self, _: &App) -> FocusHandle {
3467        self.focus_handle.clone()
3468    }
3469}
3470
3471impl EntityInputHandler for EditorState {
3472    fn text_for_range(
3473        &mut self,
3474        range_utf16: Range<usize>,
3475        actual_range: &mut Option<Range<usize>>,
3476        _window: &mut Window,
3477        _cx: &mut Context<Self>,
3478    ) -> Option<String> {
3479        let range = self.range_from_utf16(&range_utf16);
3480        actual_range.replace(self.range_to_utf16(&range));
3481        let start_pos = self.byte_offset_to_pos(range.start);
3482        let end_pos = self.byte_offset_to_pos(range.end);
3483        Some(self.get_selection_text(&Selection::new(start_pos, end_pos)))
3484    }
3485
3486    fn selected_text_range(
3487        &mut self,
3488        _ignore_disabled_input: bool,
3489        _window: &mut Window,
3490        _cx: &mut Context<Self>,
3491    ) -> Option<UTF16Selection> {
3492        if let Some(selection) = &self.selection {
3493            let start_offset = self.pos_to_byte_offset(selection.anchor);
3494            let end_offset = self.pos_to_byte_offset(selection.cursor);
3495            let range = self.range_to_utf16(&(start_offset..end_offset));
3496            Some(UTF16Selection {
3497                range,
3498                reversed: selection.anchor > selection.cursor,
3499            })
3500        } else {
3501            let cursor_offset = self.pos_to_byte_offset(self.cursor);
3502            let range = self.range_to_utf16(&(cursor_offset..cursor_offset));
3503            Some(UTF16Selection {
3504                range,
3505                reversed: false,
3506            })
3507        }
3508    }
3509
3510    fn marked_text_range(
3511        &self,
3512        _window: &mut Window,
3513        _cx: &mut Context<Self>,
3514    ) -> Option<Range<usize>> {
3515        self.marked_range
3516            .as_ref()
3517            .map(|range| self.range_to_utf16(range))
3518    }
3519
3520    fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
3521        self.marked_range = None;
3522    }
3523
3524    fn replace_text_in_range(
3525        &mut self,
3526        range_utf16: Option<Range<usize>>,
3527        new_text: &str,
3528        _window: &mut Window,
3529        cx: &mut Context<Self>,
3530    ) {
3531        if self.read_only {
3532            return;
3533        }
3534        let range_utf8 = range_utf16
3535            .as_ref()
3536            .map(|r| self.range_from_utf16(r))
3537            .or_else(|| self.marked_range.clone())
3538            .or_else(|| {
3539                if let Some(sel) = &self.selection {
3540                    let start = self.pos_to_byte_offset(sel.anchor);
3541                    let end = self.pos_to_byte_offset(sel.cursor);
3542                    Some(start.min(end)..start.max(end))
3543                } else {
3544                    let cursor_offset = self.pos_to_byte_offset(self.cursor);
3545                    Some(cursor_offset..cursor_offset)
3546                }
3547            });
3548
3549        if let Some(range) = range_utf8 {
3550            let start_pos = self.byte_offset_to_pos(range.start);
3551            let end_pos = self.byte_offset_to_pos(range.end);
3552
3553            if start_pos != end_pos {
3554                self.delete_selection_internal(Selection::new(start_pos, end_pos), cx);
3555            }
3556
3557            if new_text.len() == 1 && self.selection.is_none() {
3558                let ch = new_text.chars().next().unwrap();
3559
3560                if let Some(closer) = self.closing_char_for(ch) {
3561                    let pair_text = format!("{}{}", ch, closer);
3562                    self.insert_text_at_cursor(&pair_text, cx);
3563                    self.cursor.col = self.cursor.col.saturating_sub(1);
3564                    self.marked_range = None;
3565                    return;
3566                }
3567
3568                if self.should_skip_closing_char(ch) {
3569                    self.cursor.col += 1;
3570                    self.marked_range = None;
3571                    cx.notify();
3572                    return;
3573                }
3574            }
3575
3576            self.insert_text_at_cursor(new_text, cx);
3577        }
3578        self.marked_range = None;
3579    }
3580
3581    fn replace_and_mark_text_in_range(
3582        &mut self,
3583        range_utf16: Option<Range<usize>>,
3584        new_text: &str,
3585        new_selected_range_utf16: Option<Range<usize>>,
3586        _window: &mut Window,
3587        cx: &mut Context<Self>,
3588    ) {
3589        if self.read_only {
3590            return;
3591        }
3592
3593        let range_utf8 = range_utf16
3594            .map(|r| self.range_from_utf16(&r))
3595            .unwrap_or_else(|| {
3596                let cursor_offset = self.pos_to_byte_offset(self.cursor);
3597                cursor_offset..cursor_offset
3598            });
3599
3600        let start_pos = self.byte_offset_to_pos(range_utf8.start);
3601        let end_pos = self.byte_offset_to_pos(range_utf8.end);
3602
3603        if start_pos != end_pos {
3604            self.delete_selection_internal(Selection::new(start_pos, end_pos), cx);
3605        }
3606
3607        let insert_start = self.pos_to_byte_offset(self.cursor);
3608        self.insert_text_at_cursor(new_text, cx);
3609        let insert_end = self.pos_to_byte_offset(self.cursor);
3610
3611        if !new_text.is_empty() {
3612            self.marked_range = Some(insert_start..insert_end);
3613        }
3614
3615        if let Some(new_sel_utf16) = new_selected_range_utf16 {
3616            let new_sel_utf8 = self.range_from_utf16(&new_sel_utf16);
3617            let sel_start = self.byte_offset_to_pos(insert_start + new_sel_utf8.start);
3618            let sel_end = self.byte_offset_to_pos(insert_start + new_sel_utf8.end);
3619            self.selection = Some(Selection::new(sel_start, sel_end));
3620            self.cursor = sel_end;
3621        }
3622        cx.notify();
3623    }
3624
3625    fn bounds_for_range(
3626        &mut self,
3627        _range_utf16: Range<usize>,
3628        _bounds: Bounds<Pixels>,
3629        _window: &mut Window,
3630        _cx: &mut Context<Self>,
3631    ) -> Option<Bounds<Pixels>> {
3632        self.last_bounds
3633    }
3634
3635    fn character_index_for_point(
3636        &mut self,
3637        point: Point<Pixels>,
3638        _window: &mut Window,
3639        _cx: &mut Context<Self>,
3640    ) -> Option<usize> {
3641        if let Some(bounds) = self.last_bounds {
3642            let gutter_width = if self.show_line_numbers {
3643                px(80.0)
3644            } else {
3645                px(12.0)
3646            };
3647            let line_height = self.line_height;
3648            let pos = self.position_for_mouse(point, bounds, gutter_width, line_height);
3649            let offset = self.pos_to_byte_offset(pos);
3650            Some(self.offset_to_utf16(offset))
3651        } else {
3652            None
3653        }
3654    }
3655}
3656
3657impl Render for EditorState {
3658    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3659        EditorElement { state: cx.entity() }
3660    }
3661}
3662
3663struct EditorElement {
3664    state: Entity<EditorState>,
3665}
3666
3667struct PrepaintState {
3668    gutter_width: Pixels,
3669    line_height: Pixels,
3670}
3671
3672impl IntoElement for EditorElement {
3673    type Element = Self;
3674    fn into_element(self) -> Self::Element {
3675        self
3676    }
3677}
3678
3679impl Element for EditorElement {
3680    type RequestLayoutState = ();
3681    type PrepaintState = PrepaintState;
3682
3683    fn id(&self) -> Option<ElementId> {
3684        None
3685    }
3686
3687    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
3688        None
3689    }
3690
3691    fn request_layout(
3692        &mut self,
3693        _id: Option<&GlobalElementId>,
3694        _inspector_id: Option<&gpui::InspectorElementId>,
3695        window: &mut Window,
3696        cx: &mut App,
3697    ) -> (LayoutId, Self::RequestLayoutState) {
3698        let line_height = self.state.read(cx).line_height;
3699        let padding_top = px(12.0);
3700        let padding_bottom = px(12.0);
3701        let num_lines = self.state.read(cx).display_line_count();
3702        let content_height = padding_top + padding_bottom + (line_height * num_lines as f32);
3703        let viewport_height = self.state.read(cx).scroll_handle.bounds().size.height;
3704        let overscroll = if viewport_height > line_height * 5.0 {
3705            viewport_height / 2.0
3706        } else {
3707            px(100.0)
3708        };
3709        let final_height = content_height + overscroll;
3710
3711        let mut layout_style = gpui::Style::default();
3712        layout_style.size.width = relative(1.).into();
3713        layout_style.size.height = final_height.into();
3714
3715        (window.request_layout(layout_style, [], cx), ())
3716    }
3717
3718    fn prepaint(
3719        &mut self,
3720        _id: Option<&GlobalElementId>,
3721        _inspector_id: Option<&gpui::InspectorElementId>,
3722        _bounds: Bounds<Pixels>,
3723        _request_layout: &mut Self::RequestLayoutState,
3724        _window: &mut Window,
3725        cx: &mut App,
3726    ) -> Self::PrepaintState {
3727        let state = self.state.read(cx);
3728        let show_line_numbers = state.show_line_numbers;
3729        let line_height = state.line_height;
3730        PrepaintState {
3731            gutter_width: if show_line_numbers {
3732                px(80.0)
3733            } else {
3734                px(12.0)
3735            },
3736            line_height,
3737        }
3738    }
3739
3740    fn paint(
3741        &mut self,
3742        _id: Option<&GlobalElementId>,
3743        _inspector_id: Option<&gpui::InspectorElementId>,
3744        bounds: Bounds<Pixels>,
3745        _request_layout: &mut Self::RequestLayoutState,
3746        prepaint: &mut Self::PrepaintState,
3747        window: &mut Window,
3748        cx: &mut App,
3749    ) {
3750        let focus_handle = self.state.read(cx).focus_handle.clone();
3751        let theme = use_theme(cx);
3752        let padding_top = px(12.0);
3753        let line_height = prepaint.line_height;
3754        let gutter_width = prepaint.gutter_width;
3755        let font_size = self.state.read(cx).font_size;
3756
3757        window.handle_input(
3758            &focus_handle,
3759            ElementInputHandler::new(bounds, self.state.clone()),
3760            cx,
3761        );
3762
3763        self.state.update(cx, |state, _| {
3764            state.last_bounds = Some(bounds);
3765        });
3766
3767        let scroll_offset = self.state.read(cx).scroll_handle.offset();
3768        let viewport_height = self.state.read(cx).scroll_handle.bounds().size.height;
3769
3770        let display_lines_vec = self.state.read(cx).display_lines();
3771        let display_count = display_lines_vec.len();
3772        let buf_to_disp =
3773            |line: usize| -> Option<usize> { display_lines_vec.binary_search(&line).ok() };
3774
3775        let first_visible_display_row = ((-scroll_offset.y - padding_top) / line_height)
3776            .floor()
3777            .max(0.0) as usize;
3778        let visible_rows = ((viewport_height / line_height).ceil() as usize + 2).max(1);
3779        let last_visible_display_row = min(first_visible_display_row + visible_rows, display_count);
3780
3781        let visible_buffer_lines = if first_visible_display_row < display_count
3782            && last_visible_display_row <= display_count
3783        {
3784            &display_lines_vec[first_visible_display_row..last_visible_display_row]
3785        } else {
3786            &[]
3787        };
3788
3789        let (cursor, selection, show_line_numbers, scroll_offset_x) = {
3790            let state = self.state.read(cx);
3791            (
3792                state.cursor,
3793                state.selection,
3794                state.show_line_numbers,
3795                state.scroll_offset_x,
3796            )
3797        };
3798
3799        let (
3800            gutter_bg_color,
3801            line_num_color,
3802            line_num_active_color,
3803            current_line_color,
3804            bracket_match_color,
3805            word_highlight_color,
3806            indent_guide_color,
3807            indent_guide_active_color,
3808            fold_marker_color,
3809            tab_size,
3810            folded_ranges,
3811            fold_ranges,
3812        ) = {
3813            let s = self.state.read(cx);
3814            (
3815                s.gutter_bg_override.unwrap_or(theme.tokens.background),
3816                s.line_number_color_override
3817                    .unwrap_or(theme.tokens.muted_foreground),
3818                s.line_number_active_color_override
3819                    .unwrap_or(theme.tokens.foreground),
3820                s.current_line_color_override
3821                    .unwrap_or(hsla(0.0, 0.0, 1.0, 0.06)),
3822                s.bracket_match_color_override
3823                    .unwrap_or(hsla(0.58, 0.70, 0.65, 0.60)),
3824                s.word_highlight_color_override
3825                    .unwrap_or(hsla(0.0, 0.0, 1.0, 0.08)),
3826                s.indent_guide_color_override
3827                    .unwrap_or(hsla(0.0, 0.0, 1.0, 0.06)),
3828                s.indent_guide_active_color_override
3829                    .unwrap_or(hsla(0.0, 0.0, 1.0, 0.15)),
3830                s.fold_marker_color_override
3831                    .unwrap_or(theme.tokens.muted_foreground),
3832                s.tab_size,
3833                s.folded.clone(),
3834                s.fold_ranges.clone(),
3835            )
3836        };
3837
3838        let is_focused = focus_handle.is_focused(window);
3839        let is_single_cursor =
3840            selection.is_none() || selection.as_ref().map(|s| s.is_empty()).unwrap_or(true);
3841
3842        if is_focused && is_single_cursor {
3843            if let Some(display_row) = buf_to_disp(cursor.line) {
3844                if display_row >= first_visible_display_row
3845                    && display_row < last_visible_display_row
3846                {
3847                    let hl_y = bounds.top() + padding_top + line_height * display_row as f32;
3848                    window.paint_quad(fill(
3849                        Bounds::new(
3850                            point(bounds.left(), hl_y),
3851                            size(bounds.size.width, line_height),
3852                        ),
3853                        current_line_color,
3854                    ));
3855                }
3856            }
3857        }
3858
3859        // Cache highlight spans — only recompute when content changes or visible range shifts
3860        let content_version = self.state.read(cx).content_version;
3861        let first_buf = visible_buffer_lines.first().copied().unwrap_or(0);
3862        let last_buf = visible_buffer_lines.last().copied().unwrap_or(0) + 1;
3863        {
3864            let state = self.state.read(cx);
3865            let needs_rehighlight = state.highlight_cache_version != content_version
3866                || first_buf < state.highlight_cache_first_line
3867                || last_buf > state.highlight_cache_last_line;
3868            if needs_rehighlight {
3869                let spans = self.collect_highlight_spans_for_lines(visible_buffer_lines, cx);
3870                self.state.update(cx, |state, _| {
3871                    state.cached_highlight_spans = spans;
3872                    state.highlight_cache_version = content_version;
3873                    state.highlight_cache_first_line = first_buf;
3874                    state.highlight_cache_last_line = last_buf;
3875                });
3876            }
3877        }
3878
3879        let text_style = window.text_style();
3880        let mut shaped_layouts: Vec<(usize, Option<ShapedLine>, u64)> =
3881            Vec::with_capacity(visible_buffer_lines.len());
3882        let mut max_line_width = px(0.0);
3883
3884        let char_width = {
3885            let space_run = TextRun {
3886                len: 1,
3887                font: text_style.font(),
3888                color: theme.tokens.foreground,
3889                background_color: None,
3890                underline: None,
3891                strikethrough: None,
3892            };
3893            let shaped_space =
3894                window
3895                    .text_system()
3896                    .shape_line(" ".into(), font_size, &[space_run], None);
3897            shaped_space.x_for_index(1)
3898        };
3899
3900        let cursor_indent = if tab_size > 0 {
3901            let cursor_line_text = self.state.read(cx).line_text(cursor.line);
3902            let cursor_leading = cursor_line_text.len() - cursor_line_text.trim_start().len();
3903            cursor_leading / tab_size
3904        } else {
3905            0
3906        };
3907
3908        for display_row in first_visible_display_row..last_visible_display_row {
3909            let line_idx = display_lines_vec[display_row];
3910            let y = bounds.top() + padding_top + line_height * display_row as f32;
3911
3912            let line_text = self.state.read(cx).line_text(line_idx);
3913            let leading_spaces = line_text.len() - line_text.trim_start().len();
3914            let indent_levels = if tab_size > 0 {
3915                leading_spaces / tab_size
3916            } else {
3917                0
3918            };
3919
3920            for level in 0..indent_levels {
3921                let guide_x = bounds.left() + gutter_width + char_width * (level * tab_size) as f32
3922                    - scroll_offset_x;
3923                let color = if level == cursor_indent.saturating_sub(1) && is_focused {
3924                    indent_guide_active_color
3925                } else {
3926                    indent_guide_color
3927                };
3928                window.paint_quad(fill(
3929                    Bounds::new(point(guide_x, y), size(px(1.0), line_height)),
3930                    color,
3931                ));
3932            }
3933
3934            // Content-hash-based cache: only re-shape lines whose content changed
3935            let line_hash = {
3936                use std::hash::{Hash, Hasher};
3937                let mut hasher = std::collections::hash_map::DefaultHasher::new();
3938                line_text.hash(&mut hasher);
3939                hasher.finish()
3940            };
3941            let cached_layout = {
3942                let state = self.state.read(cx);
3943                if state.line_content_hashes.get(&line_idx) == Some(&line_hash) {
3944                    state.line_layouts.get(&line_idx).cloned()
3945                } else {
3946                    None
3947                }
3948            };
3949            if let Some(cached) = cached_layout {
3950                let line_width = cached.x_for_index(cached.len());
3951                if line_width > max_line_width {
3952                    max_line_width = line_width;
3953                }
3954                let _ = cached.paint(
3955                    point(bounds.left() + gutter_width - scroll_offset_x, y),
3956                    line_height,
3957                    window,
3958                    cx,
3959                );
3960                continue;
3961            }
3962
3963            if line_text.is_empty() {
3964                shaped_layouts.push((line_idx, None, line_hash));
3965                continue;
3966            }
3967
3968            let highlight_spans = &self.state.read(cx).cached_highlight_spans;
3969            let text_runs =
3970                self.build_text_runs(&line_text, line_idx, highlight_spans, &text_style, &theme);
3971
3972            let line_len = line_text.len();
3973            let shaped =
3974                window
3975                    .text_system()
3976                    .shape_line(line_text.into(), font_size, &text_runs, None);
3977
3978            let line_width = shaped.x_for_index(line_len);
3979            if line_width > max_line_width {
3980                max_line_width = line_width;
3981            }
3982
3983            let _ = shaped.paint(
3984                point(bounds.left() + gutter_width - scroll_offset_x, y),
3985                line_height,
3986                window,
3987                cx,
3988            );
3989
3990            shaped_layouts.push((line_idx, Some(shaped), line_hash));
3991        }
3992
3993        self.state.update(cx, |state, _| {
3994            state
3995                .line_layouts
3996                .retain(|&line_idx, _| line_idx >= first_buf && line_idx < last_buf);
3997            state
3998                .line_content_hashes
3999                .retain(|&line_idx, _| line_idx >= first_buf && line_idx < last_buf);
4000            for (idx, layout, hash) in shaped_layouts {
4001                if let Some(shaped) = layout {
4002                    state.line_layouts.insert(idx, shaped);
4003                }
4004                state.line_content_hashes.insert(idx, hash);
4005            }
4006            if max_line_width > state.max_line_width {
4007                state.max_line_width = max_line_width;
4008            }
4009            let content_width = bounds.size.width - gutter_width;
4010            let max_scroll = (state.max_line_width - content_width + px(40.0)).max(px(0.0));
4011            state.scroll_offset_x = state.scroll_offset_x.max(px(0.0)).min(max_scroll);
4012        });
4013
4014        if show_line_numbers {
4015            window.paint_quad(PaintQuad {
4016                bounds: Bounds {
4017                    origin: bounds.origin,
4018                    size: Size {
4019                        width: gutter_width,
4020                        height: bounds.size.height,
4021                    },
4022                },
4023                corner_radii: Corners::default(),
4024                background: gutter_bg_color.into(),
4025                border_widths: Edges::default(),
4026                border_color: Hsla::transparent_black(),
4027                border_style: BorderStyle::default(),
4028                continuous_corners: false,
4029                transform: Default::default(),
4030                blend_mode: Default::default(),
4031            });
4032
4033            let mut line_num_buf2 = String::with_capacity(8);
4034            for display_row in first_visible_display_row..last_visible_display_row {
4035                let line_idx = display_lines_vec[display_row];
4036                let y = bounds.top() + padding_top + line_height * display_row as f32;
4037                let is_current_line = line_idx == cursor.line;
4038                let num_color = if is_current_line && is_focused {
4039                    line_num_active_color
4040                } else {
4041                    line_num_color
4042                };
4043                line_num_buf2.clear();
4044                use std::fmt::Write;
4045                let _ = write!(line_num_buf2, "{:>4}", line_idx + 1);
4046                let num_font = if is_current_line && is_focused {
4047                    let mut f = text_style.font();
4048                    f.weight = FontWeight::BOLD;
4049                    f
4050                } else {
4051                    text_style.font()
4052                };
4053                let line_num_run = TextRun {
4054                    len: line_num_buf2.len(),
4055                    font: num_font,
4056                    color: num_color,
4057                    background_color: None,
4058                    underline: None,
4059                    strikethrough: None,
4060                };
4061                let shaped = window.text_system().shape_line(
4062                    SharedString::from(line_num_buf2.clone()),
4063                    font_size,
4064                    &[line_num_run],
4065                    None,
4066                );
4067                let _ = shaped.paint(point(bounds.left() + px(6.0), y), line_height, window, cx);
4068
4069                let fold_start = fold_ranges.iter().any(|f| f.start_line == line_idx);
4070                let is_folded = folded_ranges.iter().any(|f| f.start_line == line_idx);
4071                if fold_start {
4072                    let icon_name = if is_folded {
4073                        "chevron-right"
4074                    } else {
4075                        "chevron-down"
4076                    };
4077                    let icon_path = SharedString::from(resolve_icon_path(icon_name));
4078                    let icon_size = px(16.0);
4079                    let icon_x = bounds.left() + gutter_width - px(18.0);
4080                    let icon_y = y + (line_height - icon_size) / 2.0;
4081                    let icon_bounds =
4082                        Bounds::new(point(icon_x, icon_y), size(icon_size, icon_size));
4083                    let _ = window.paint_svg(
4084                        icon_bounds,
4085                        icon_path,
4086                        TransformationMatrix::default(),
4087                        fold_marker_color,
4088                        cx,
4089                    );
4090                }
4091            }
4092        }
4093
4094        if is_focused && is_single_cursor {
4095            let word_occurrences = self.find_word_occurrences(visible_buffer_lines, cx);
4096            for (occ_line, occ_start, occ_end) in &word_occurrences {
4097                if let Some(dr) = buf_to_disp(*occ_line) {
4098                    if let Some(layout) = self.state.read(cx).line_layouts.get(occ_line) {
4099                        let occ_y = bounds.top() + padding_top + line_height * dr as f32;
4100                        let x_start = layout.x_for_index(*occ_start);
4101                        let x_end = layout.x_for_index(*occ_end);
4102                        window.paint_quad(fill(
4103                            Bounds::new(
4104                                point(
4105                                    bounds.left() + gutter_width + x_start - scroll_offset_x,
4106                                    occ_y,
4107                                ),
4108                                size(x_end - x_start, line_height),
4109                            ),
4110                            word_highlight_color,
4111                        ));
4112                    }
4113                }
4114            }
4115        }
4116
4117        let sel_color = self
4118            .state
4119            .read(cx)
4120            .selection_color_override
4121            .unwrap_or(theme.tokens.primary.opacity(0.25));
4122
4123        if let Some(selection) = &selection {
4124            let (start, end) = selection.range();
4125            for line_idx in start.line..=end.line {
4126                let dr = match buf_to_disp(line_idx) {
4127                    Some(d) => d,
4128                    None => continue,
4129                };
4130                if dr < first_visible_display_row || dr >= last_visible_display_row {
4131                    continue;
4132                }
4133                let line_y = bounds.top() + padding_top + line_height * dr as f32;
4134                let line_len = self.state.read(cx).line_len(line_idx);
4135                let start_col = if line_idx == start.line { start.col } else { 0 };
4136                let end_col = if line_idx == end.line {
4137                    end.col
4138                } else {
4139                    line_len
4140                };
4141
4142                let (sel_x, sel_width) =
4143                    if let Some(layout) = self.state.read(cx).line_layouts.get(&line_idx) {
4144                        let x_start = layout.x_for_index(start_col);
4145                        let x_end = layout.x_for_index(end_col);
4146                        (
4147                            bounds.left() + gutter_width + x_start - scroll_offset_x,
4148                            x_end - x_start,
4149                        )
4150                    } else {
4151                        (bounds.left() + gutter_width - scroll_offset_x, px(0.0))
4152                    };
4153
4154                window.paint_quad(fill(
4155                    Bounds::new(point(sel_x, line_y), size(sel_width, line_height)),
4156                    sel_color,
4157                ));
4158            }
4159        }
4160
4161        {
4162            let state = self.state.read(cx);
4163            let (search_normal, search_active) = state
4164                .search_match_color_overrides
4165                .unwrap_or((rgba(0xFFD70040).into(), rgba(0xFF990060).into()));
4166            let current_match = state.current_match_idx;
4167            for (match_idx, &(match_start, match_end)) in state.search_matches.iter().enumerate() {
4168                let start_pos = state.byte_offset_to_pos(match_start);
4169                let end_pos = state.byte_offset_to_pos(match_end);
4170                let is_current = current_match == Some(match_idx);
4171                let color = if is_current {
4172                    search_active
4173                } else {
4174                    search_normal
4175                };
4176
4177                for line_idx in start_pos.line..=end_pos.line {
4178                    let dr = match buf_to_disp(line_idx) {
4179                        Some(d) => d,
4180                        None => continue,
4181                    };
4182                    if dr < first_visible_display_row || dr >= last_visible_display_row {
4183                        continue;
4184                    }
4185                    let line_y = bounds.top() + padding_top + line_height * dr as f32;
4186                    let sc = if line_idx == start_pos.line {
4187                        start_pos.col
4188                    } else {
4189                        0
4190                    };
4191                    let ec = if line_idx == end_pos.line {
4192                        end_pos.col
4193                    } else {
4194                        state.line_len(line_idx)
4195                    };
4196
4197                    let (hx, hw) = if let Some(layout) = state.line_layouts.get(&line_idx) {
4198                        let x_start = layout.x_for_index(sc);
4199                        let x_end = layout.x_for_index(ec);
4200                        (
4201                            bounds.left() + gutter_width + x_start - scroll_offset_x,
4202                            x_end - x_start,
4203                        )
4204                    } else {
4205                        continue;
4206                    };
4207
4208                    window.paint_quad(fill(
4209                        Bounds::new(point(hx, line_y), size(hw, line_height)),
4210                        color,
4211                    ));
4212                }
4213            }
4214        }
4215
4216        if is_focused {
4217            if let Some((pos_a, pos_b)) = self.state.read(cx).find_matching_bracket() {
4218                for pos in [pos_a, pos_b] {
4219                    if let Some(dr) = buf_to_disp(pos.line) {
4220                        if dr >= first_visible_display_row && dr < last_visible_display_row {
4221                            if let Some(layout) = self.state.read(cx).line_layouts.get(&pos.line) {
4222                                let bx = bounds.left() + gutter_width + layout.x_for_index(pos.col)
4223                                    - scroll_offset_x;
4224                                let by = bounds.top() + padding_top + line_height * dr as f32;
4225                                let bw =
4226                                    layout.x_for_index(pos.col + 1) - layout.x_for_index(pos.col);
4227                                let bracket_bounds =
4228                                    Bounds::new(point(bx, by), size(bw, line_height));
4229                                window.paint_quad(PaintQuad {
4230                                    bounds: bracket_bounds,
4231                                    corner_radii: Corners::default(),
4232                                    background: bracket_match_color.opacity(0.3).into(),
4233                                    border_widths: Edges::all(px(1.0)),
4234                                    border_color: bracket_match_color,
4235                                    border_style: BorderStyle::default(),
4236                                    continuous_corners: false,
4237                                    transform: Default::default(),
4238                                    blend_mode: Default::default(),
4239                                });
4240                            }
4241                        }
4242                    }
4243                }
4244            }
4245        }
4246
4247        {
4248            let diagnostics = &self.state.read(cx).diagnostics;
4249            if !diagnostics.is_empty() {
4250                for diag in diagnostics {
4251                    let diag_line = diag.start_line as usize;
4252                    let dr = match buf_to_disp(diag_line) {
4253                        Some(d) => d,
4254                        None => continue,
4255                    };
4256                    if dr < first_visible_display_row || dr >= last_visible_display_row {
4257                        continue;
4258                    }
4259
4260                    let underline_color = match diag.severity {
4261                        DiagnosticSeverity::Error => self
4262                            .state
4263                            .read(cx)
4264                            .diagnostic_error_color
4265                            .unwrap_or(hsla(0.0, 0.85, 0.6, 1.0)),
4266                        DiagnosticSeverity::Warning => self
4267                            .state
4268                            .read(cx)
4269                            .diagnostic_warning_color
4270                            .unwrap_or(hsla(0.12, 0.85, 0.55, 1.0)),
4271                        DiagnosticSeverity::Information => self
4272                            .state
4273                            .read(cx)
4274                            .diagnostic_info_color
4275                            .unwrap_or(hsla(0.6, 0.7, 0.6, 1.0)),
4276                        DiagnosticSeverity::Hint => self
4277                            .state
4278                            .read(cx)
4279                            .diagnostic_hint_color
4280                            .unwrap_or(hsla(0.0, 0.0, 0.5, 0.6)),
4281                    };
4282
4283                    let diag_y = bounds.top() + padding_top + line_height * dr as f32 + line_height
4284                        - px(2.0);
4285
4286                    if let Some(layout) = self.state.read(cx).line_layouts.get(&diag_line) {
4287                        let start_col = diag.start_col as usize;
4288                        let end_col = if diag.end_line == diag.start_line {
4289                            (diag.end_col as usize).max(start_col + 1)
4290                        } else {
4291                            self.state.read(cx).line_len(diag_line)
4292                        };
4293                        let x_start = layout.x_for_index(start_col);
4294                        let x_end = layout.x_for_index(end_col);
4295                        let underline_width = (x_end - x_start).max(char_width);
4296                        window.paint_quad(fill(
4297                            Bounds::new(
4298                                point(
4299                                    bounds.left() + gutter_width + x_start - scroll_offset_x,
4300                                    diag_y,
4301                                ),
4302                                size(underline_width, px(2.0)),
4303                            ),
4304                            underline_color,
4305                        ));
4306                    }
4307
4308                    if show_line_numbers {
4309                        let dot_size = px(6.0);
4310                        let dot_x = bounds.left() + px(2.0);
4311                        let dot_y = bounds.top()
4312                            + padding_top
4313                            + line_height * dr as f32
4314                            + (line_height - dot_size) / 2.0;
4315                        window.paint_quad(PaintQuad {
4316                            bounds: Bounds::new(point(dot_x, dot_y), size(dot_size, dot_size)),
4317                            corner_radii: Corners::all(dot_size / 2.0),
4318                            background: underline_color.into(),
4319                            border_widths: Edges::default(),
4320                            border_color: Hsla::transparent_black(),
4321                            border_style: BorderStyle::default(),
4322                            continuous_corners: false,
4323                            transform: Default::default(),
4324                            blend_mode: Default::default(),
4325                        });
4326                    }
4327                }
4328            }
4329        }
4330
4331        if is_focused {
4332            let cursor_moved = {
4333                let state = self.state.read(cx);
4334                state.last_blink_cursor != cursor
4335            };
4336            if cursor_moved {
4337                self.state.update(cx, |state, cx| {
4338                    state.last_blink_cursor = cursor;
4339                    state.reset_cursor_blink(cx);
4340                });
4341            } else if self.state.read(cx).blink_task.is_none() {
4342                self.state.update(cx, |state, cx| {
4343                    state.reset_cursor_blink(cx);
4344                });
4345            }
4346
4347            let cursor_visible = self.state.read(cx).cursor_visible;
4348            if cursor_visible {
4349                if let Some(cursor_display_row) = buf_to_disp(cursor.line) {
4350                    let total = self.state.read(cx).total_lines();
4351                    let cursor_col = if cursor.line < total {
4352                        cursor.col.min(self.state.read(cx).line_len(cursor.line))
4353                    } else {
4354                        0
4355                    };
4356                    let cursor_y =
4357                        bounds.top() + padding_top + line_height * cursor_display_row as f32;
4358                    let cursor_x =
4359                        if let Some(layout) = self.state.read(cx).line_layouts.get(&cursor.line) {
4360                            bounds.left() + gutter_width + layout.x_for_index(cursor_col)
4361                                - scroll_offset_x
4362                        } else {
4363                            bounds.left() + gutter_width - scroll_offset_x
4364                        };
4365
4366                    let cursor_draw_color = self
4367                        .state
4368                        .read(cx)
4369                        .cursor_color_override
4370                        .unwrap_or(theme.tokens.primary);
4371
4372                    window.paint_quad(fill(
4373                        Bounds::new(point(cursor_x, cursor_y), size(px(2.0), line_height)),
4374                        cursor_draw_color,
4375                    ));
4376                }
4377            }
4378        }
4379    }
4380}
4381
4382struct HighlightSpan {
4383    line: usize,
4384    start_col: usize,
4385    end_col: usize,
4386    color: Hsla,
4387}
4388
4389impl EditorElement {
4390    fn find_word_occurrences(
4391        &self,
4392        visible_lines: &[usize],
4393        cx: &App,
4394    ) -> Vec<(usize, usize, usize)> {
4395        let state = self.state.read(cx);
4396        let word = match state.word_under_cursor_full() {
4397            Some((w, _, _)) => w,
4398            None => return Vec::new(),
4399        };
4400        let mut results = Vec::new();
4401        for &line_idx in visible_lines {
4402            let line_text = state.line_text(line_idx);
4403            let mut search_from = 0;
4404            while let Some(pos) = line_text[search_from..].find(&word) {
4405                let abs_start = search_from + pos;
4406                let abs_end = abs_start + word.len();
4407                let before_ok = abs_start == 0
4408                    || !line_text.as_bytes()[abs_start - 1].is_ascii_alphanumeric()
4409                        && line_text.as_bytes()[abs_start - 1] != b'_';
4410                let after_ok = abs_end >= line_text.len()
4411                    || !line_text.as_bytes()[abs_end].is_ascii_alphanumeric()
4412                        && line_text.as_bytes()[abs_end] != b'_';
4413                if before_ok && after_ok {
4414                    results.push((line_idx, abs_start, abs_end));
4415                }
4416                let next_char_len = line_text[abs_start..]
4417                    .chars()
4418                    .next()
4419                    .map(|character| character.len_utf8())
4420                    .unwrap_or(1);
4421                search_from = abs_start + next_char_len;
4422            }
4423        }
4424        results
4425    }
4426
4427    fn collect_highlight_spans_for_lines(
4428        &self,
4429        visible_lines: &[usize],
4430        cx: &App,
4431    ) -> Vec<HighlightSpan> {
4432        if visible_lines.is_empty() {
4433            return Vec::new();
4434        }
4435
4436        let state = self.state.read(cx);
4437        let tree = match &state.syntax_tree {
4438            Some(t) => t,
4439            None => return Vec::new(),
4440        };
4441
4442        let query = match &state.highlight_query {
4443            Some(q) => q,
4444            None => return Vec::new(),
4445        };
4446
4447        let rope = &state.rope;
4448        let total_lines = rope.len_lines();
4449        let mut spans = Vec::new();
4450
4451        let mut chunk_start = 0usize;
4452        while chunk_start < visible_lines.len() {
4453            let mut chunk_end = chunk_start;
4454            while chunk_end + 1 < visible_lines.len()
4455                && visible_lines[chunk_end + 1] == visible_lines[chunk_end] + 1
4456            {
4457                chunk_end += 1;
4458            }
4459
4460            let first_line = visible_lines[chunk_start];
4461            let last_line = visible_lines[chunk_end] + 1;
4462
4463            let first_byte = rope.line_to_byte(first_line);
4464            let last_byte = if last_line < total_lines {
4465                rope.line_to_byte(last_line)
4466            } else {
4467                rope.len_bytes()
4468            };
4469
4470            let mut cursor = QueryCursor::new();
4471            cursor.set_byte_range(first_byte..last_byte);
4472
4473            let mut matches = cursor.matches(query, tree.root_node(), |node: tree_sitter::Node| {
4474                let range = node.byte_range();
4475                let text: String = rope
4476                    .byte_slice(range.start..range.end.min(rope.len_bytes()))
4477                    .into();
4478                std::iter::once(text)
4479            });
4480
4481            while let Some(m) = matches.next() {
4482                for capture in m.captures {
4483                    let capture_name = &query.capture_names()[capture.index as usize];
4484                    let node = capture.node;
4485                    let start_byte = node.start_byte();
4486                    let end_byte = node.end_byte();
4487                    let color = if let Some(ref color_fn) = state.syntax_color_fn {
4488                        color_fn(capture_name)
4489                    } else {
4490                        highlight_color_for_capture(capture_name)
4491                    };
4492
4493                    let start_line = rope.byte_to_line(start_byte);
4494                    let end_line =
4495                        rope.byte_to_line(end_byte.min(rope.len_bytes().saturating_sub(1)));
4496
4497                    for line in start_line..=end_line {
4498                        if line < first_line || line >= last_line {
4499                            continue;
4500                        }
4501                        let line_start_byte = rope.line_to_byte(line);
4502                        let line_text = state.line_text(line);
4503                        let line_end_byte = line_start_byte + line_text.len();
4504
4505                        let span_start = start_byte.max(line_start_byte) - line_start_byte;
4506                        let span_end = end_byte.min(line_end_byte) - line_start_byte;
4507
4508                        if span_start < span_end {
4509                            spans.push(HighlightSpan {
4510                                line,
4511                                start_col: span_start,
4512                                end_col: span_end,
4513                                color,
4514                            });
4515                        }
4516                    }
4517                }
4518            }
4519
4520            chunk_start = chunk_end + 1;
4521        }
4522
4523        spans
4524    }
4525
4526    fn build_text_runs(
4527        &self,
4528        line_text: &str,
4529        line_idx: usize,
4530        highlight_spans: &[HighlightSpan],
4531        text_style: &gpui::TextStyle,
4532        theme: &crate::capabilities::foundation::theme::Theme,
4533    ) -> Vec<TextRun> {
4534        let mut line_spans: Vec<&HighlightSpan> = highlight_spans
4535            .iter()
4536            .filter(|s| s.line == line_idx)
4537            .collect();
4538        line_spans.sort_by_key(|s| s.start_col);
4539
4540        if line_spans.is_empty() {
4541            return vec![TextRun {
4542                len: line_text.len(),
4543                font: text_style.font(),
4544                color: theme.tokens.foreground,
4545                background_color: None,
4546                underline: None,
4547                strikethrough: None,
4548            }];
4549        }
4550
4551        let text_len = line_text.len();
4552        let mut runs = Vec::new();
4553        let mut pos = 0;
4554
4555        for span in &line_spans {
4556            let start = span.start_col.min(text_len).max(pos);
4557            let end = span.end_col.min(text_len);
4558            if end <= start {
4559                continue;
4560            }
4561            if start > pos {
4562                runs.push(TextRun {
4563                    len: start - pos,
4564                    font: text_style.font(),
4565                    color: theme.tokens.foreground,
4566                    background_color: None,
4567                    underline: None,
4568                    strikethrough: None,
4569                });
4570            }
4571            runs.push(TextRun {
4572                len: end - start,
4573                font: text_style.font(),
4574                color: span.color,
4575                background_color: None,
4576                underline: None,
4577                strikethrough: None,
4578            });
4579            pos = end;
4580        }
4581
4582        if pos < text_len {
4583            runs.push(TextRun {
4584                len: text_len - pos,
4585                font: text_style.font(),
4586                color: theme.tokens.foreground,
4587                background_color: None,
4588                underline: None,
4589                strikethrough: None,
4590            });
4591        }
4592
4593        let total_len: usize = runs.iter().map(|r| r.len).sum();
4594        if runs.is_empty() || total_len != text_len {
4595            return vec![TextRun {
4596                len: text_len,
4597                font: text_style.font(),
4598                color: theme.tokens.foreground,
4599                background_color: None,
4600                underline: None,
4601                strikethrough: None,
4602            }];
4603        }
4604
4605        runs
4606    }
4607}
4608
4609#[derive(IntoElement)]
4610pub struct Editor {
4611    state: Entity<EditorState>,
4612    min_lines: Option<usize>,
4613    max_lines: Option<usize>,
4614    show_border: bool,
4615    style: StyleRefinement,
4616    cursor_color: Option<Hsla>,
4617    selection_color: Option<Hsla>,
4618    line_number_color: Option<Hsla>,
4619    line_number_active_color: Option<Hsla>,
4620    gutter_bg: Option<Hsla>,
4621    search_match_colors: Option<(Hsla, Hsla)>,
4622    current_line_color: Option<Hsla>,
4623    bracket_match_color: Option<Hsla>,
4624    word_highlight_color: Option<Hsla>,
4625    indent_guide_color: Option<Hsla>,
4626    indent_guide_active_color: Option<Hsla>,
4627    fold_marker_color: Option<Hsla>,
4628    syntax_color_fn: Option<Box<dyn Fn(&str) -> Hsla>>,
4629}
4630
4631impl Editor {
4632    pub fn new(state: &Entity<EditorState>) -> Self {
4633        Self {
4634            state: state.clone(),
4635            min_lines: None,
4636            max_lines: None,
4637            show_border: true,
4638            style: StyleRefinement::default(),
4639            cursor_color: None,
4640            selection_color: None,
4641            line_number_color: None,
4642            line_number_active_color: None,
4643            gutter_bg: None,
4644            search_match_colors: None,
4645            current_line_color: None,
4646            bracket_match_color: None,
4647            word_highlight_color: None,
4648            indent_guide_color: None,
4649            indent_guide_active_color: None,
4650            fold_marker_color: None,
4651            syntax_color_fn: None,
4652        }
4653    }
4654
4655    pub fn content(self, content: impl Into<String>, cx: &mut App) -> Self {
4656        self.state.update(cx, |state, cx| {
4657            state.set_content(&content.into(), cx);
4658        });
4659        self
4660    }
4661
4662    pub fn min_lines(mut self, lines: usize) -> Self {
4663        self.min_lines = Some(lines);
4664        self
4665    }
4666
4667    pub fn max_lines(mut self, lines: usize) -> Self {
4668        self.max_lines = Some(lines);
4669        self
4670    }
4671
4672    pub fn show_border(mut self, show: bool) -> Self {
4673        self.show_border = show;
4674        self
4675    }
4676
4677    pub fn show_line_numbers(self, show: bool, cx: &mut App) -> Self {
4678        self.state.update(cx, |state, cx| {
4679            state.show_line_numbers = show;
4680            cx.notify();
4681        });
4682        self
4683    }
4684
4685    pub fn cursor_color(mut self, color: Hsla) -> Self {
4686        self.cursor_color = Some(color);
4687        self
4688    }
4689
4690    pub fn selection_color(mut self, color: Hsla) -> Self {
4691        self.selection_color = Some(color);
4692        self
4693    }
4694
4695    pub fn line_number_color(mut self, color: Hsla) -> Self {
4696        self.line_number_color = Some(color);
4697        self
4698    }
4699
4700    pub fn line_number_active_color(mut self, color: Hsla) -> Self {
4701        self.line_number_active_color = Some(color);
4702        self
4703    }
4704
4705    pub fn gutter_bg(mut self, color: Hsla) -> Self {
4706        self.gutter_bg = Some(color);
4707        self
4708    }
4709
4710    pub fn search_match_colors(mut self, normal: Hsla, active: Hsla) -> Self {
4711        self.search_match_colors = Some((normal, active));
4712        self
4713    }
4714
4715    pub fn current_line_color(mut self, color: Hsla) -> Self {
4716        self.current_line_color = Some(color);
4717        self
4718    }
4719
4720    pub fn bracket_match_color(mut self, color: Hsla) -> Self {
4721        self.bracket_match_color = Some(color);
4722        self
4723    }
4724
4725    pub fn word_highlight_color(mut self, color: Hsla) -> Self {
4726        self.word_highlight_color = Some(color);
4727        self
4728    }
4729
4730    pub fn indent_guide_colors(mut self, normal: Hsla, active: Hsla) -> Self {
4731        self.indent_guide_color = Some(normal);
4732        self.indent_guide_active_color = Some(active);
4733        self
4734    }
4735
4736    pub fn fold_marker_color(mut self, color: Hsla) -> Self {
4737        self.fold_marker_color = Some(color);
4738        self
4739    }
4740
4741    pub fn syntax_color_fn(mut self, f: impl Fn(&str) -> Hsla + 'static) -> Self {
4742        self.syntax_color_fn = Some(Box::new(f));
4743        self
4744    }
4745
4746    pub fn get_content(&self, cx: &App) -> String {
4747        self.state.read(cx).content()
4748    }
4749}
4750
4751impl Styled for Editor {
4752    fn style(&mut self) -> &mut StyleRefinement {
4753        &mut self.style
4754    }
4755}
4756
4757impl RenderOnce for Editor {
4758    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
4759        let syn_fn = self.syntax_color_fn.take();
4760        self.state.update(cx, |state, _| {
4761            state.cursor_color_override = self.cursor_color;
4762            state.selection_color_override = self.selection_color;
4763            state.line_number_color_override = self.line_number_color;
4764            state.line_number_active_color_override = self.line_number_active_color;
4765            state.gutter_bg_override = self.gutter_bg;
4766            state.search_match_color_overrides = self.search_match_colors;
4767            state.current_line_color_override = self.current_line_color;
4768            state.bracket_match_color_override = self.bracket_match_color;
4769            state.word_highlight_color_override = self.word_highlight_color;
4770            state.indent_guide_color_override = self.indent_guide_color;
4771            state.indent_guide_active_color_override = self.indent_guide_active_color;
4772            state.fold_marker_color_override = self.fold_marker_color;
4773            state.syntax_color_fn = syn_fn;
4774        });
4775        let theme = use_theme(cx);
4776        let font_family_for_editor = self
4777            .state
4778            .read(cx)
4779            .font_family_override
4780            .clone()
4781            .unwrap_or_else(|| theme.tokens.font_mono.clone());
4782        // Track the state's line height instead of a literal 20px so that
4783        // `set_font_size` keeps min/max line counts and line-based wheel
4784        // scrolling consistent with the rendered layout.
4785        let line_height = self.state.read(cx).line_height;
4786        let min_height = self.min_lines.map(|lines| line_height * lines as f32);
4787        let max_height = self.max_lines.map(|lines| line_height * lines as f32);
4788        let scroll_handle = self.state.read(cx).scroll_handle.clone();
4789
4790        let mut base = div()
4791            .id(("editor", self.state.entity_id()))
4792            .key_context("Editor")
4793            .track_focus(&self.state.read(cx).focus_handle(cx))
4794            .w_full()
4795            .h_full()
4796            .max_h_full();
4797
4798        if let Some(h) = min_height {
4799            base = base.min_h(h);
4800        }
4801        if let Some(h) = max_height {
4802            base = base.max_h(h);
4803        }
4804
4805        let styled_base = base
4806            .bg(theme.tokens.background)
4807            .rounded(theme.tokens.radius_md);
4808
4809        let final_base = if self.show_border {
4810            styled_base.border_1().border_color(theme.tokens.border)
4811        } else {
4812            styled_base
4813        };
4814
4815        let user_style = self.style;
4816
4817        final_base
4818            .map(|this| {
4819                let mut d = this;
4820                d.style().refine(&user_style);
4821                d
4822            })
4823            .font_family(font_family_for_editor.clone())
4824            .on_action(window.listener_for(&self.state, EditorState::move_up))
4825            .on_action(window.listener_for(&self.state, EditorState::move_down))
4826            .on_action(window.listener_for(&self.state, EditorState::move_left))
4827            .on_action(window.listener_for(&self.state, EditorState::move_right))
4828            .on_action(window.listener_for(&self.state, EditorState::move_word_left))
4829            .on_action(window.listener_for(&self.state, EditorState::move_word_right))
4830            .on_action(window.listener_for(&self.state, EditorState::move_to_line_start))
4831            .on_action(window.listener_for(&self.state, EditorState::move_to_line_end))
4832            .on_action(window.listener_for(&self.state, EditorState::move_to_doc_start))
4833            .on_action(window.listener_for(&self.state, EditorState::move_to_doc_end))
4834            .on_action(window.listener_for(&self.state, EditorState::page_up))
4835            .on_action(window.listener_for(&self.state, EditorState::page_down))
4836            .on_action(window.listener_for(&self.state, EditorState::select_up))
4837            .on_action(window.listener_for(&self.state, EditorState::select_down))
4838            .on_action(window.listener_for(&self.state, EditorState::select_left))
4839            .on_action(window.listener_for(&self.state, EditorState::select_right))
4840            .on_action(window.listener_for(&self.state, EditorState::select_to_line_start))
4841            .on_action(window.listener_for(&self.state, EditorState::select_to_line_end))
4842            .on_action(window.listener_for(&self.state, EditorState::select_all))
4843            .on_action(window.listener_for(&self.state, EditorState::backspace))
4844            .on_action(window.listener_for(&self.state, EditorState::delete))
4845            .on_action(window.listener_for(&self.state, EditorState::delete_word))
4846            .on_action(window.listener_for(&self.state, EditorState::enter))
4847            .on_action(window.listener_for(&self.state, EditorState::tab))
4848            .on_action(window.listener_for(&self.state, EditorState::copy))
4849            .on_action(window.listener_for(&self.state, EditorState::cut))
4850            .on_action(window.listener_for(&self.state, EditorState::paste))
4851            .on_action(window.listener_for(&self.state, EditorState::undo))
4852            .on_action(window.listener_for(&self.state, EditorState::redo))
4853            .on_mouse_down(MouseButton::Left, {
4854                let state = self.state.clone();
4855                move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| {
4856                    let (bounds, gutter_width, line_height) = {
4857                        let s = state.read(cx);
4858                        let b = s.last_bounds.unwrap_or_default();
4859                        let gw = if s.show_line_numbers {
4860                            px(80.0)
4861                        } else {
4862                            px(12.0)
4863                        };
4864                        let lh = s.line_height;
4865                        (b, gw, lh)
4866                    };
4867                    state.update(cx, |s, cx| {
4868                        s.on_mouse_down(event, bounds, gutter_width, line_height, window, cx);
4869                    });
4870                    window.focus(&state.read(cx).focus_handle(cx));
4871                }
4872            })
4873            .on_mouse_move({
4874                let state = self.state.clone();
4875                move |event: &MouseMoveEvent, window: &mut Window, cx: &mut App| {
4876                    let (bounds, gutter_width, line_height) = {
4877                        let s = state.read(cx);
4878                        let b = s.last_bounds.unwrap_or_default();
4879                        let gw = if s.show_line_numbers {
4880                            px(80.0)
4881                        } else {
4882                            px(12.0)
4883                        };
4884                        let lh = s.line_height;
4885                        (b, gw, lh)
4886                    };
4887                    state.update(cx, |s, cx| {
4888                        s.on_mouse_move(event, bounds, gutter_width, line_height, window, cx);
4889                    });
4890                }
4891            })
4892            .on_mouse_up(
4893                MouseButton::Left,
4894                window.listener_for(&self.state, EditorState::on_mouse_up),
4895            )
4896            .on_scroll_wheel({
4897                let state = self.state.clone();
4898                move |event: &ScrollWheelEvent, _window: &mut Window, cx: &mut App| {
4899                    let delta_x = match event.delta {
4900                        ScrollDelta::Pixels(p) => p.x,
4901                        ScrollDelta::Lines(l) => line_height * l.x,
4902                    };
4903                    if delta_x.abs() > px(0.5) {
4904                        state.update(cx, |s, cx| {
4905                            s.scroll_horizontal(-delta_x, cx);
4906                        });
4907                    }
4908                }
4909            })
4910            .child(
4911                div()
4912                    .flex()
4913                    .flex_col()
4914                    .size_full()
4915                    .child(div().flex_1().overflow_hidden().child(
4916                        scrollable_vertical(self.state.clone()).with_scroll_handle(scroll_handle),
4917                    ))
4918                    .child(HorizontalScrollbar::new(self.state.clone(), cx)),
4919            )
4920    }
4921}
4922
4923#[derive(IntoElement)]
4924struct HorizontalScrollbar {
4925    state: Entity<EditorState>,
4926    needs_scrollbar: bool,
4927    thumb_width_pct: f32,
4928    thumb_left_pct: f32,
4929}
4930
4931impl HorizontalScrollbar {
4932    fn new(state: Entity<EditorState>, cx: &App) -> Self {
4933        let s = state.read(cx);
4934        let max_width = s.max_line_width;
4935        let scroll_x = s.scroll_offset_x;
4936        let viewport_bounds = s.scroll_handle.bounds();
4937        let gutter_width = if s.show_line_numbers {
4938            px(80.0)
4939        } else {
4940            px(12.0)
4941        };
4942        let content_width = viewport_bounds.size.width - gutter_width;
4943        let needs_scrollbar = max_width > content_width && content_width > px(0.0);
4944
4945        let (thumb_width_pct, thumb_left_pct) = if needs_scrollbar {
4946            let visible_ratio = (content_width / max_width).min(1.0);
4947            let twp = (visible_ratio * 100.0).max(5.0);
4948            let scroll_range = max_width - content_width;
4949            let tlp = if scroll_range > px(0.0) {
4950                ((scroll_x / scroll_range) * (100.0 - twp)).max(0.0)
4951            } else {
4952                0.0
4953            };
4954            (twp, tlp)
4955        } else {
4956            (0.0, 0.0)
4957        };
4958
4959        Self {
4960            state,
4961            needs_scrollbar,
4962            thumb_width_pct,
4963            thumb_left_pct,
4964        }
4965    }
4966}
4967
4968impl RenderOnce for HorizontalScrollbar {
4969    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
4970        if !self.needs_scrollbar {
4971            return div().h(px(0.0)).into_any_element();
4972        }
4973
4974        let theme = use_theme(cx);
4975        let editor_state = self.state.clone();
4976
4977        div()
4978            .id("h-scrollbar")
4979            .w_full()
4980            .h(px(12.0))
4981            .bg(theme.tokens.muted.opacity(0.3))
4982            .cursor(CursorStyle::PointingHand)
4983            .on_mouse_down(MouseButton::Left, {
4984                let state = editor_state.clone();
4985                move |event: &MouseDownEvent, _window, cx| {
4986                    cx.stop_propagation();
4987                    state.update(cx, |s, cx| {
4988                        s.dragging_h_scrollbar = true;
4989                        let max_w = s.max_line_width;
4990                        let vp = s.scroll_handle.bounds();
4991                        let gw = if s.show_line_numbers {
4992                            px(80.0)
4993                        } else {
4994                            px(12.0)
4995                        };
4996                        let cw = vp.size.width - gw;
4997                        let scroll_range = max_w - cw;
4998
4999                        if scroll_range > px(0.0) {
5000                            let track_width = vp.size.width;
5001                            let click_ratio = (event.position.x - vp.left()) / track_width;
5002                            let new_scroll = scroll_range * click_ratio;
5003                            s.scroll_offset_x = new_scroll.max(px(0.0)).min(scroll_range);
5004                        }
5005                        cx.notify();
5006                    });
5007                }
5008            })
5009            .on_mouse_up(MouseButton::Left, {
5010                let state = editor_state.clone();
5011                move |_: &MouseUpEvent, _window, cx| {
5012                    state.update(cx, |s, cx| {
5013                        s.dragging_h_scrollbar = false;
5014                        cx.notify();
5015                    });
5016                }
5017            })
5018            .child(
5019                div()
5020                    .absolute()
5021                    .top(px(2.0))
5022                    .bottom(px(2.0))
5023                    .left(relative(self.thumb_left_pct / 100.0))
5024                    .w(relative(self.thumb_width_pct / 100.0))
5025                    .bg(theme.tokens.muted_foreground.opacity(0.6))
5026                    .rounded(px(3.0))
5027                    .hover(|s| s.bg(theme.tokens.muted_foreground.opacity(0.8))),
5028            )
5029            .into_any_element()
5030    }
5031}
5032
5033#[cfg(test)]
5034mod tests {
5035    use super::*;
5036
5037    #[::core::prelude::v1::test]
5038    fn text_edit_range_maps_cursor_and_selection_offsets() {
5039        let insertion = TextEditRange {
5040            start: 3,
5041            old_end: 3,
5042            new_end: 5,
5043        };
5044
5045        assert_eq!(insertion.map_cursor_offset(2), 2);
5046        assert_eq!(insertion.map_cursor_offset(3), 3);
5047        assert_eq!(insertion.map_cursor_offset(6), 8);
5048
5049        assert_eq!(insertion.map_selection_offsets(1, 3), (1, 3));
5050        assert_eq!(insertion.map_selection_offsets(3, 6), (5, 8));
5051        assert_eq!(insertion.map_selection_offsets(6, 3), (8, 5));
5052
5053        let replacement = TextEditRange {
5054            start: 3,
5055            old_end: 7,
5056            new_end: 5,
5057        };
5058        assert_eq!(replacement.map_cursor_offset(5), 5);
5059        assert_eq!(replacement.map_selection_offsets(1, 9), (1, 7));
5060    }
5061
5062    #[::core::prelude::v1::test]
5063    fn line_edit_range_preserves_shifts_and_drops_overlaps() {
5064        let insertion = LineEditRange {
5065            start_line: 2,
5066            old_end_line: 2,
5067            new_end_line: 4,
5068        };
5069        assert_eq!(
5070            insertion.map_fold_range(FoldRange {
5071                start_line: 0,
5072                end_line: 1,
5073            }),
5074            Some(FoldRange {
5075                start_line: 0,
5076                end_line: 1,
5077            })
5078        );
5079        assert_eq!(
5080            insertion.map_fold_range(FoldRange {
5081                start_line: 4,
5082                end_line: 6,
5083            }),
5084            Some(FoldRange {
5085                start_line: 6,
5086                end_line: 8,
5087            })
5088        );
5089        assert_eq!(
5090            insertion.map_fold_range(FoldRange {
5091                start_line: 1,
5092                end_line: 3,
5093            }),
5094            None
5095        );
5096
5097        let deletion = LineEditRange {
5098            start_line: 2,
5099            old_end_line: 5,
5100            new_end_line: 3,
5101        };
5102        assert_eq!(
5103            deletion.map_fold_range(FoldRange {
5104                start_line: 5,
5105                end_line: 7,
5106            }),
5107            Some(FoldRange {
5108                start_line: 3,
5109                end_line: 5,
5110            })
5111        );
5112        assert_eq!(
5113            deletion.map_fold_range(FoldRange {
5114                start_line: 3,
5115                end_line: 6,
5116            }),
5117            None
5118        );
5119    }
5120
5121    #[cfg(feature = "tree-sitter-rust")]
5122    fn parse_rust(source: &str) -> Tree {
5123        let mut parser = Parser::new();
5124        parser
5125            .set_language(&tree_sitter_rust::LANGUAGE.into())
5126            .expect("set Rust language");
5127        parser.parse(source, None).expect("parse Rust source")
5128    }
5129
5130    #[gpui::test]
5131    fn stale_parse_revisions_are_rejected_after_input_changes() {
5132        let mut app = TestApp::new();
5133        let editor = app.update(|cx| cx.new(EditorState::new));
5134
5135        app.update(|cx| {
5136            editor.update(cx, |state, cx| {
5137                let initial_revision = state.parse_coordinator.revision();
5138                assert!(state.is_parse_result_current(initial_revision));
5139
5140                state.set_content("short content", cx);
5141                assert!(!state.is_parse_result_current(initial_revision));
5142                let content_revision = state.parse_coordinator.revision();
5143
5144                state.set_language(Language::Rust);
5145                assert!(!state.is_parse_result_current(content_revision));
5146                let language_revision = state.parse_coordinator.revision();
5147
5148                state.insert_text_at_cursor("edited ", cx);
5149                assert!(!state.is_parse_result_current(language_revision));
5150            });
5151        });
5152    }
5153
5154    #[gpui::test]
5155    fn plain_text_does_not_start_async_parse() {
5156        let mut app = TestApp::new();
5157        let editor = app.update(|cx| cx.new(EditorState::new));
5158
5159        app.update(|cx| {
5160            editor.update(cx, |state, cx| {
5161                assert_eq!(state.language, Language::Plain);
5162                assert!(!state.parse_async(cx));
5163            });
5164        });
5165    }
5166
5167    #[gpui::test]
5168    fn loading_a_file_invalidates_an_older_parse_revision() {
5169        let path = std::env::temp_dir().join(format!(
5170            "fc-editor-parse-revision-{}.txt",
5171            std::process::id()
5172        ));
5173        std::fs::write(&path, "fresh file content").expect("write editor test file");
5174
5175        let mut app = TestApp::new();
5176        let editor = app.update(|cx| cx.new(EditorState::new));
5177        app.update(|cx| {
5178            editor.update(cx, |state, cx| {
5179                let old_revision = state.parse_coordinator.revision();
5180                state.load_file(&path, cx);
5181                assert!(!state.is_parse_result_current(old_revision));
5182            });
5183        });
5184
5185        std::fs::remove_file(path).expect("remove editor test file");
5186    }
5187
5188    #[cfg(feature = "tree-sitter-rust")]
5189    #[gpui::test]
5190    fn stale_async_parse_result_cannot_replace_current_tree() {
5191        let mut app = TestApp::new();
5192        let editor = app.update(|cx| cx.new(EditorState::new));
5193
5194        app.update(|cx| {
5195            editor.update(cx, |state, cx| {
5196                state.set_language(Language::Rust);
5197                state.set_content("fn stale() { let value = 1; }", cx);
5198                let stale_revision = state.parse_coordinator.revision();
5199                let stale_tree = parse_rust("fn stale() { let value = 1; }");
5200
5201                state.set_content("struct Current;", cx);
5202                let current_tree = state
5203                    .syntax_tree
5204                    .as_ref()
5205                    .expect("current content should be parsed")
5206                    .root_node()
5207                    .to_sexp();
5208
5209                assert!(!state.commit_parse_result(stale_revision, Some(stale_tree)));
5210                assert_eq!(
5211                    state
5212                        .syntax_tree
5213                        .as_ref()
5214                        .expect("stale result must not clear the current tree")
5215                        .root_node()
5216                        .to_sexp(),
5217                    current_tree
5218                );
5219            });
5220        });
5221    }
5222
5223    struct EditorTestView {
5224        state: Entity<EditorState>,
5225    }
5226
5227    impl Render for EditorTestView {
5228        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
5229            div()
5230        }
5231    }
5232
5233    #[gpui::test]
5234    fn cjk_cursor_movement_stays_on_char_boundaries() {
5235        let mut app = TestApp::new();
5236        let editor = app.update(|cx| cx.new(EditorState::new));
5237        let mut window = app.open_window(|_, _| EditorTestView {
5238            state: editor.clone(),
5239        });
5240
5241        window.update(|view, window, cx| {
5242            view.state.update(cx, |state, cx| {
5243                state.set_content("读读写写", cx);
5244                let line = "读读写写";
5245
5246                // 修复前 col += 1,会停在汉字字节中间
5247                for _ in 0..4 {
5248                    state.move_right(&MoveRight, window, cx);
5249                    assert!(
5250                        line.is_char_boundary(state.cursor().col),
5251                        "move_right landed mid-char at col {}",
5252                        state.cursor().col
5253                    );
5254                }
5255                assert_eq!(state.cursor(), Position::new(0, line.len()));
5256
5257                // 行尾且无下一行:继续右移不应越界仍停在行尾
5258                state.move_right(&MoveRight, window, cx);
5259                assert_eq!(state.cursor(), Position::new(0, line.len()));
5260
5261                for _ in 0..4 {
5262                    state.move_left(&MoveLeft, window, cx);
5263                    assert!(
5264                        line.is_char_boundary(state.cursor().col),
5265                        "move_left landed mid-char at col {}",
5266                        state.cursor().col
5267                    );
5268                }
5269                assert_eq!(state.cursor(), Position::zero());
5270            });
5271        });
5272    }
5273
5274    #[gpui::test]
5275    fn selecting_and_clamping_cursor_stay_on_unicode_boundaries() {
5276        let mut app = TestApp::new();
5277        let editor = app.update(|cx| cx.new(EditorState::new));
5278        let mut window = app.open_window(|_, _| EditorTestView {
5279            state: editor.clone(),
5280        });
5281
5282        window.update(|view, window, cx| {
5283            view.state.update(cx, |state, cx| {
5284                state.set_content("读", cx);
5285                state.set_cursor_position(0, 2, cx);
5286                assert_eq!(state.cursor(), Position::zero());
5287
5288                state.set_cursor_position(0, "读".len(), cx);
5289                state.select_left(&SelectLeft, window, cx);
5290                assert_eq!(state.cursor(), Position::zero());
5291                assert_eq!(state.selection_text().as_deref(), Some("读"));
5292                assert!(state.line_text(0).is_char_boundary(state.cursor().col));
5293
5294                state.select_right(&SelectRight, window, cx);
5295                assert_eq!(state.cursor(), Position::new(0, "读".len()));
5296                assert!(state.line_text(0).is_char_boundary(state.cursor().col));
5297
5298                state.set_content("a\n界", cx);
5299                state.set_cursor_position(0, 1, cx);
5300                state.move_down(&MoveDown, window, cx);
5301                assert_eq!(state.cursor(), Position::new(1, 0));
5302                assert!(state.line_text(1).is_char_boundary(state.cursor().col));
5303            });
5304        });
5305    }
5306
5307    #[gpui::test]
5308    fn mixed_cjk_cursor_crosses_lines_and_enter_splits_on_boundaries() {
5309        let mut app = TestApp::new();
5310        let editor = app.update(|cx| cx.new(EditorState::new));
5311        let mut window = app.open_window(|_, _| EditorTestView {
5312            state: editor.clone(),
5313        });
5314
5315        window.update(|view, window, cx| {
5316            view.state.update(cx, |state, cx| {
5317                state.set_content("ab读cd\n第二行", cx);
5318                let first = "ab读cd";
5319                // 3 个 ASCII + 1 个 CJK 共 5 个 char,再右移一次跨到下一行
5320                for _ in 0..first.chars().count() + 1 {
5321                    state.move_right(&MoveRight, window, cx);
5322                    assert!(
5323                        first.is_char_boundary(state.cursor().col) || state.cursor().line > 0,
5324                        "move_right landed mid-char at col {}",
5325                        state.cursor().col
5326                    );
5327                }
5328                assert_eq!(state.cursor(), Position::new(1, 0));
5329
5330                state.move_left(&MoveLeft, window, cx);
5331                assert_eq!(state.cursor(), Position::new(0, first.len()));
5332
5333                // CJK 字符中间回车:修复前按非法边界切片会 panic
5334                state.set_content("读读写写", cx);
5335                state.move_right(&MoveRight, window, cx);
5336                assert_eq!(state.cursor(), Position::new(0, 3));
5337                state.enter(&Enter, window, cx);
5338                assert_eq!(state.content(), "读\n读写写\n");
5339                assert_eq!(state.cursor(), Position::new(1, 0));
5340
5341                // 连续移动 + enter 不 panic
5342                state.move_right(&MoveRight, window, cx);
5343                state.move_left(&MoveLeft, window, cx);
5344                state.enter(&Enter, window, cx);
5345                state.move_up(&MoveUp, window, cx);
5346                state.move_down(&MoveDown, window, cx);
5347            });
5348        });
5349    }
5350
5351    #[gpui::test]
5352    fn word_cursor_movement_stays_on_unicode_boundaries() {
5353        let mut app = TestApp::new();
5354        let editor = app.update(|cx| cx.new(EditorState::new));
5355        let mut window = app.open_window(|_, _| EditorTestView {
5356            state: editor.clone(),
5357        });
5358
5359        window.update(|view, window, cx| {
5360            view.state.update(cx, |state, cx| {
5361                state.set_content("中文 abc", cx);
5362                state.set_cursor_position(0, "中文 abc".len(), cx);
5363
5364                state.move_word_left(&MoveWordLeft, window, cx);
5365                assert_eq!(state.cursor(), Position::new(0, "中文 ".len()));
5366                assert!(state.line_text(0).is_char_boundary(state.cursor().col));
5367
5368                state.move_word_left(&MoveWordLeft, window, cx);
5369                assert_eq!(state.cursor(), Position::zero());
5370                assert!(state.line_text(0).is_char_boundary(state.cursor().col));
5371
5372                state.move_word_right(&MoveWordRight, window, cx);
5373                assert_eq!(state.cursor(), Position::new(0, "中文 ".len()));
5374                assert!(state.line_text(0).is_char_boundary(state.cursor().col));
5375            });
5376        });
5377    }
5378
5379    #[gpui::test]
5380    fn stale_search_matches_after_shrinking_document_do_not_panic() {
5381        let mut app = TestApp::new();
5382        let editor = app.update(|cx| cx.new(EditorState::new));
5383
5384        app.update(|cx| {
5385            editor.update(cx, |state, cx| {
5386                state.set_content("hello world hello", cx);
5387                // 模拟在旧文档上完成、但迟于编辑到达的异步搜索结果
5388                state.search_query = "hello".to_string();
5389                state.search_matches = vec![(0, 5), (12, 17)];
5390                state.current_match_idx = Some(1);
5391
5392                // 通过公开编辑路径把文档剪短,使上述字节区间全部失效
5393                state.set_content("hi", cx);
5394                assert!(state.rope.len_bytes() < 12);
5395
5396                // 修复前:直接对失效区间做 rope 切片/删除会 panic
5397                state.replace_current("bye", cx);
5398                assert_eq!(state.content(), "hi\n");
5399
5400                state.search_matches = vec![(0, 5), (12, 17)];
5401                state.current_match_idx = Some(1);
5402                state.replace_all("bye", cx);
5403                assert_eq!(state.content(), "hi\n");
5404            });
5405        });
5406    }
5407
5408    #[gpui::test]
5409    fn stale_async_search_results_are_rejected_after_content_changes() {
5410        let mut app = TestApp::new();
5411        let editor = app.update(|cx| cx.new(EditorState::new));
5412
5413        app.update(|cx| {
5414            editor.update(cx, |state, cx| {
5415                state.set_content("old document", cx);
5416                state.search_query = "old".to_string();
5417                let generation = state.search_generation;
5418                let content_version = state.content_version;
5419
5420                state.set_content("new document", cx);
5421
5422                assert!(!state.commit_search_result(
5423                    generation,
5424                    content_version,
5425                    "old",
5426                    false,
5427                    false,
5428                    0,
5429                    vec![(0, 3)],
5430                ));
5431                assert!(state.search_matches.is_empty());
5432            });
5433        });
5434    }
5435
5436    #[gpui::test]
5437    fn case_insensitive_search_maps_unicode_lowercase_expansions() {
5438        // `İ` lowercases to `i` plus a combining dot (three normalized bytes,
5439        // but only two bytes in the original source). Every returned range
5440        // must remain a valid range in the original string.
5441        let content = "İxİ";
5442        assert_eq!(
5443            find_case_insensitive_matches(content, "i"),
5444            vec![(0, "İ".len()), ("İx".len(), content.len())]
5445        );
5446        assert_eq!(
5447            find_case_insensitive_matches(content, "i\u{307}"),
5448            vec![(0, "İ".len()), ("İx".len(), content.len())]
5449        );
5450
5451        // A regular multi-byte case conversion must also map to source byte
5452        // offsets, while overlapping matches continue to work.
5453        assert_eq!(
5454            find_case_insensitive_matches("Éé", "é"),
5455            vec![(0, "É".len()), ("É".len(), "Éé".len())]
5456        );
5457    }
5458
5459    #[gpui::test]
5460    fn case_insensitive_search_keeps_unicode_casefold_scope_explicit() {
5461        // The editor uses Rust's lowercase mapping, rather than full Unicode
5462        // case folding. Thus `ẞ`/`ß` work, while the multi-character uppercase
5463        // form `SS` is intentionally not treated as equivalent to `ß`.
5464        assert_eq!(find_case_insensitive_matches("Straße", "ß"), vec![(4, 6)]);
5465        assert_eq!(find_case_insensitive_matches("ẞ", "ß"), vec![(0, 3)]);
5466        assert!(find_case_insensitive_matches("Straße", "SS").is_empty());
5467    }
5468
5469    #[gpui::test]
5470    fn replacing_content_resets_cached_max_line_width() {
5471        let mut app = TestApp::new();
5472        let editor = app.update(|cx| cx.new(EditorState::new));
5473
5474        app.update(|cx| {
5475            editor.update(cx, |state, cx| {
5476                state.max_line_width = px(900.0);
5477                state.set_content("short", cx);
5478                assert_eq!(state.max_line_width, px(0.0));
5479            });
5480        });
5481    }
5482
5483    #[gpui::test]
5484    fn incremental_edits_preserve_cached_max_line_width() {
5485        let mut app = TestApp::new();
5486        let editor = app.update(|cx| cx.new(EditorState::new));
5487        let mut window = app.open_window(|_, _| EditorTestView {
5488            state: editor.clone(),
5489        });
5490
5491        window.update(|view, _window, cx| {
5492            view.state.update(cx, |state, cx| {
5493                state.set_content("short", cx);
5494                state.max_line_width = px(900.0);
5495                state.set_cursor_position(0, 5, cx);
5496                state.insert_text_at_cursor("!", cx);
5497
5498                assert_eq!(state.max_line_width, px(900.0));
5499            });
5500        });
5501    }
5502
5503    #[gpui::test]
5504    fn undo_and_redo_round_trip_a_text_edit() {
5505        let mut app = TestApp::new();
5506        let editor = app.update(|cx| cx.new(EditorState::new));
5507        let mut window = app.open_window(|_, _| EditorTestView {
5508            state: editor.clone(),
5509        });
5510
5511        window.update(|view, window, cx| {
5512            view.state.update(cx, |state, cx| {
5513                state.set_content("hello", cx);
5514                state.set_cursor_position(0, 5, cx);
5515                state.insert_text_at_cursor("!", cx);
5516                assert_eq!(state.content(), "hello!\n");
5517
5518                state.undo(&Undo, window, cx);
5519                assert_eq!(state.content(), "hello\n");
5520
5521                state.redo(&Redo, window, cx);
5522                assert_eq!(state.content(), "hello!\n");
5523            });
5524        });
5525    }
5526
5527    #[gpui::test]
5528    fn replacing_a_selection_is_undone_as_one_edit() {
5529        let mut app = TestApp::new();
5530        let editor = app.update(|cx| cx.new(EditorState::new));
5531        let mut window = app.open_window(|_, _| EditorTestView {
5532            state: editor.clone(),
5533        });
5534
5535        window.update(|view, window, cx| {
5536            view.state.update(cx, |state, cx| {
5537                state.set_content("hello world", cx);
5538                state.selection = Some(Selection::new(Position::zero(), Position::new(0, 5)));
5539                state.cursor = Position::new(0, 5);
5540                state.insert_text_at_cursor("hi", cx);
5541                assert_eq!(state.content(), "hi world\n");
5542
5543                state.undo(&Undo, window, cx);
5544                assert_eq!(state.content(), "hello world\n");
5545
5546                state.redo(&Redo, window, cx);
5547                assert_eq!(state.content(), "hi world\n");
5548            });
5549        });
5550    }
5551
5552    #[gpui::test]
5553    fn replace_all_is_undone_as_one_edit() {
5554        let mut app = TestApp::new();
5555        let editor = app.update(|cx| cx.new(EditorState::new));
5556        let mut window = app.open_window(|_, _| EditorTestView {
5557            state: editor.clone(),
5558        });
5559
5560        window.update(|view, window, cx| {
5561            view.state.update(cx, |state, cx| {
5562                state.set_content("a a a", cx);
5563                state.search_query = "a".to_string();
5564                state.search_matches = vec![(0, 1), (2, 3), (4, 5)];
5565                state.replace_all("b", cx);
5566                assert_eq!(state.content(), "b b b\n");
5567
5568                state.undo(&Undo, window, cx);
5569                assert_eq!(state.content(), "a a a\n");
5570
5571                state.redo(&Redo, window, cx);
5572                assert_eq!(state.content(), "b b b\n");
5573            });
5574        });
5575    }
5576
5577    #[gpui::test]
5578    fn multiline_replace_all_is_one_undo_and_clears_stale_folds() {
5579        let mut app = TestApp::new();
5580        let editor = app.update(|cx| cx.new(EditorState::new));
5581        let mut window = app.open_window(|_, _| EditorTestView {
5582            state: editor.clone(),
5583        });
5584
5585        window.update(|view, window, cx| {
5586            view.state.update(cx, |state, cx| {
5587                state.set_content("a\nx\na\nx\n", cx);
5588                state.search_query = "x\n".to_string();
5589                state.search_matches = vec![(2, 4), (6, 8)];
5590                state.current_match_idx = Some(0);
5591                state.fold_ranges = vec![FoldRange {
5592                    start_line: 1,
5593                    end_line: 3,
5594                }];
5595                state.folded = state.fold_ranges.clone();
5596                state.cached_display_lines = Some(Rc::new(vec![0, 1]));
5597
5598                state.replace_all("y\nz\n", cx);
5599
5600                assert_eq!(state.content(), "a\ny\nz\na\ny\nz\n");
5601                assert!(state.fold_ranges.is_empty());
5602                assert!(state.folded.is_empty());
5603                assert!(state.cached_display_lines.is_none());
5604
5605                state.undo(&Undo, window, cx);
5606                assert_eq!(state.content(), "a\nx\na\nx\n");
5607
5608                state.redo(&Redo, window, cx);
5609                assert_eq!(state.content(), "a\ny\nz\na\ny\nz\n");
5610            });
5611        });
5612    }
5613
5614    #[gpui::test]
5615    fn editing_after_load_and_save_updates_modified_state() {
5616        let path =
5617            std::env::temp_dir().join(format!("fc-editor-save-state-{}.txt", std::process::id()));
5618        std::fs::write(&path, "saved").expect("write editor test file");
5619
5620        let mut app = TestApp::new();
5621        let editor = app.update(|cx| cx.new(EditorState::new));
5622        let mut window = app.open_window(|_, _| EditorTestView {
5623            state: editor.clone(),
5624        });
5625
5626        window.update(|view, _window, cx| {
5627            view.state.update(cx, |state, cx| {
5628                state.load_file(&path, cx);
5629                assert!(!state.is_modified());
5630
5631                state.set_cursor_position(0, 5, cx);
5632                state.insert_text_at_cursor("!", cx);
5633                assert!(state.is_modified());
5634                assert!(state.save(cx));
5635                assert!(!state.is_modified());
5636            });
5637        });
5638
5639        assert_eq!(
5640            std::fs::read_to_string(&path).expect("read saved file"),
5641            "saved!"
5642        );
5643        std::fs::remove_file(path).expect("remove editor test file");
5644    }
5645
5646    #[gpui::test]
5647    fn replace_current_with_fresh_matches_updates_content() {
5648        let mut app = TestApp::new();
5649        let editor = app.update(|cx| cx.new(EditorState::new));
5650
5651        app.update(|cx| {
5652            editor.update(cx, |state, cx| {
5653                state.set_content("hello world hello", cx);
5654                state.search_query = "hello".to_string();
5655                state.search_matches = vec![(0, 5), (12, 17)];
5656                state.current_match_idx = Some(0);
5657
5658                state.replace_current("bye", cx);
5659                assert_eq!(state.content(), "bye world hello\n");
5660                assert_eq!(state.cursor(), Position::zero());
5661            });
5662        });
5663    }
5664
5665    #[gpui::test]
5666    fn line_replacements_adjust_cursor_and_selection_offsets() {
5667        let mut app = TestApp::new();
5668        let editor = app.update(|cx| cx.new(EditorState::new));
5669
5670        app.update(|cx| {
5671            editor.update(cx, |state, cx| {
5672                state.set_content("a\nb\nc", cx);
5673                state.set_cursor_position(2, 1, cx);
5674                state.selection = Some(Selection::new(Position::new(2, 0), Position::new(2, 1)));
5675                state.search_query = "\n".to_string();
5676                state.search_matches = vec![(1, 2)];
5677                state.current_match_idx = Some(0);
5678
5679                state.replace_current("x\ny\nz", cx);
5680
5681                assert_eq!(state.content(), "ax\ny\nzb\nc\n");
5682                assert_eq!(state.cursor(), Position::new(3, 1));
5683                assert_eq!(
5684                    state.selection,
5685                    Some(Selection::new(Position::new(3, 0), Position::new(3, 1)))
5686                );
5687
5688                state.set_content("a\nb\nc", cx);
5689                state.set_cursor_position(2, 1, cx);
5690                state.selection = Some(Selection::new(Position::new(2, 0), Position::new(2, 1)));
5691                state.search_query = "\n".to_string();
5692                state.search_matches = vec![(1, 2)];
5693                state.current_match_idx = Some(0);
5694
5695                state.replace_current("", cx);
5696
5697                assert_eq!(state.content(), "ab\nc\n");
5698                assert_eq!(state.cursor(), Position::new(1, 1));
5699                assert_eq!(
5700                    state.selection,
5701                    Some(Selection::new(Position::new(1, 0), Position::new(1, 1)))
5702                );
5703            });
5704        });
5705    }
5706
5707    #[cfg(feature = "tree-sitter-rust")]
5708    #[gpui::test]
5709    fn switching_to_plain_text_clears_the_syntax_tree() {
5710        let mut app = TestApp::new();
5711        let editor = app.update(|cx| cx.new(EditorState::new));
5712
5713        app.update(|cx| {
5714            editor.update(cx, |state, cx| {
5715                state.set_language(Language::Rust);
5716                state.set_content("fn main() {}", cx);
5717                assert!(state.syntax_tree.is_some());
5718                state.fold_ranges.push(FoldRange {
5719                    start_line: 0,
5720                    end_line: 2,
5721                });
5722                state.folded.push(FoldRange {
5723                    start_line: 0,
5724                    end_line: 2,
5725                });
5726                state.cached_display_lines = Some(Rc::new(vec![0]));
5727
5728                state.set_language(Language::Plain);
5729
5730                assert!(state.syntax_tree.is_none());
5731                assert!(state.fold_ranges.is_empty());
5732                assert!(state.folded.is_empty());
5733                assert!(state.cached_display_lines.is_none());
5734            });
5735        });
5736    }
5737
5738    #[cfg(feature = "tree-sitter-rust")]
5739    #[gpui::test]
5740    fn replacing_content_clears_stale_fold_state() {
5741        let mut app = TestApp::new();
5742        let editor = app.update(|cx| cx.new(EditorState::new));
5743
5744        app.update(|cx| {
5745            editor.update(cx, |state, cx| {
5746                state.set_language(Language::Rust);
5747                state.set_content("fn main() {\n    let value = 1;\n}\n", cx);
5748                state.fold_ranges.push(FoldRange {
5749                    start_line: 0,
5750                    end_line: 2,
5751                });
5752                state.folded.push(FoldRange {
5753                    start_line: 0,
5754                    end_line: 2,
5755                });
5756                state.cached_display_lines = Some(Rc::new(vec![0]));
5757
5758                state.set_content("fn main() {}", cx);
5759
5760                assert!(state.fold_ranges.is_empty());
5761                assert!(state.folded.is_empty());
5762                assert!(state.cached_display_lines.is_none());
5763            });
5764        });
5765    }
5766
5767    #[gpui::test]
5768    fn line_edits_clear_stale_fold_state() {
5769        let mut app = TestApp::new();
5770        let editor = app.update(|cx| cx.new(EditorState::new));
5771
5772        app.update(|cx| {
5773            editor.update(cx, |state, cx| {
5774                state.set_content("line", cx);
5775                state.fold_ranges.push(FoldRange {
5776                    start_line: 0,
5777                    end_line: 2,
5778                });
5779                state.folded.push(FoldRange {
5780                    start_line: 0,
5781                    end_line: 2,
5782                });
5783                state.cached_display_lines = Some(Rc::new(vec![0]));
5784                state.set_cursor_position(0, 4, cx);
5785
5786                state.insert_text_at_cursor("\n", cx);
5787
5788                assert!(state.fold_ranges.is_empty());
5789                assert!(state.folded.is_empty());
5790                assert!(state.cached_display_lines.is_none());
5791            });
5792        });
5793    }
5794
5795    #[gpui::test]
5796    fn line_edits_shift_unaffected_fold_ranges() {
5797        let mut app = TestApp::new();
5798        let editor = app.update(|cx| cx.new(EditorState::new));
5799        let mut window = app.open_window(|_, _| EditorTestView {
5800            state: editor.clone(),
5801        });
5802
5803        window.update(|view, window, cx| {
5804            view.state.update(cx, |state, cx| {
5805                state.set_content("a\nb\nc\nd", cx);
5806                state.fold_ranges = vec![FoldRange {
5807                    start_line: 2,
5808                    end_line: 3,
5809                }];
5810                state.folded = state.fold_ranges.clone();
5811                state.cached_display_lines = Some(Rc::new(vec![0, 1, 2]));
5812                state.set_cursor_position(0, 0, cx);
5813
5814                state.insert_text_at_cursor("\n", cx);
5815
5816                assert_eq!(
5817                    state.fold_ranges,
5818                    vec![FoldRange {
5819                        start_line: 3,
5820                        end_line: 4,
5821                    }]
5822                );
5823                assert_eq!(state.folded, state.fold_ranges);
5824
5825                state.set_content("a\nb\nc\nd", cx);
5826                state.fold_ranges = vec![FoldRange {
5827                    start_line: 2,
5828                    end_line: 3,
5829                }];
5830                state.folded = state.fold_ranges.clone();
5831                state.cached_display_lines = Some(Rc::new(vec![0, 1, 2]));
5832                state.set_cursor_position(0, 1, cx);
5833
5834                state.delete(&Delete, window, cx);
5835
5836                assert_eq!(
5837                    state.fold_ranges,
5838                    vec![FoldRange {
5839                        start_line: 1,
5840                        end_line: 2,
5841                    }]
5842                );
5843                assert_eq!(state.folded, state.fold_ranges);
5844            });
5845        });
5846    }
5847
5848    #[cfg(feature = "tree-sitter-rust")]
5849    #[gpui::test]
5850    fn undo_and_redo_migrate_unaffected_fold_ranges() {
5851        let mut app = TestApp::new();
5852        let editor = app.update(|cx| cx.new(EditorState::new));
5853        let mut window = app.open_window(|_, _| EditorTestView {
5854            state: editor.clone(),
5855        });
5856
5857        window.update(|view, window, cx| {
5858            view.state.update(cx, |state, cx| {
5859                state.set_language(Language::Rust);
5860                state.set_content("fn before() {}\nfn folded() {\n    let value = 1;\n}\n", cx);
5861                state.fold_ranges = vec![FoldRange {
5862                    start_line: 1,
5863                    end_line: 3,
5864                }];
5865                state.folded = state.fold_ranges.clone();
5866                state.cached_display_lines = Some(Rc::new(vec![0, 1, 4]));
5867                state.set_cursor_position(0, 0, cx);
5868
5869                state.insert_text_at_cursor("\n", cx);
5870                assert_eq!(
5871                    state.folded,
5872                    vec![FoldRange {
5873                        start_line: 2,
5874                        end_line: 4,
5875                    }]
5876                );
5877
5878                state.undo(&Undo, window, cx);
5879                assert_eq!(
5880                    state.folded,
5881                    vec![FoldRange {
5882                        start_line: 1,
5883                        end_line: 3,
5884                    }]
5885                );
5886
5887                state.redo(&Redo, window, cx);
5888                assert_eq!(
5889                    state.folded,
5890                    vec![FoldRange {
5891                        start_line: 2,
5892                        end_line: 4,
5893                    }]
5894                );
5895            });
5896        });
5897    }
5898}