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