Skip to main content

gpui_deck/input/base/
state.rs

1// Modified for GPUI Deck: remove window-wide rich-text selection and spinbutton-only state.
2//! A text input field that allows the user to enter text.
3//!
4//! Based on the `Input` example from the `gpui` crate.
5//! https://github.com/zed-industries/zed/blob/main/crates/gpui/examples/input.rs
6use gpui::TextAlign;
7use gpui::{
8    Action, App, AppContext, Bounds, ClipboardItem, Context, Edges, Entity, EntityInputHandler,
9    EventEmitter, FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding,
10    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point,
11    Render, ScrollEvent, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _,
12    Subscription, UTF16Selection, WeakFocusHandle, Window, actions, div, point,
13    prelude::FluentBuilder as _, px,
14};
15use gpui::{Autocapitalize, TextInputAction, TextInputConfiguration};
16use ropey::{Rope, RopeSlice};
17use serde::Deserialize;
18use std::borrow::Cow;
19use std::cell::Cell;
20use std::ops::Range;
21use std::rc::Rc;
22use sum_tree::Bias;
23use unicode_segmentation::*;
24
25use super::{
26    DiagnosticSet, DisplayMap, InputContextMenuCapabilities, InputEditorStyle,
27    InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, WrappingIndent,
28    blink_cursor::BlinkCursor,
29    change::Change,
30    cursor::{CursorSelection, Selections},
31    element::{
32        EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, OverviewRulerRows, TextElement,
33        clamp_horizontal_scroll_offset,
34    },
35    kind::InputModeKind,
36    mask_pattern::normalize_number_input,
37    mode::LayoutMode,
38    undo_manager::{EditIntent, UndoManager},
39};
40use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
41use crate::input::blink_cursor::CURSOR_WIDTH;
42use crate::input::movement::MoveDirection;
43use crate::input::rope_ext::{next_grapheme_boundary, previous_grapheme_boundary};
44use crate::input::{
45    InputEdit, InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout,
46};
47use crate::overscroll::Overscroll;
48use crate::{AutoScroll, TestSupportExt as _};
49
50pub(super) const EDITOR_ELEMENT_ID: &str = "input-state";
51
52/// Vertical clearance to retain when revealing a text position.
53pub(crate) enum ScrollPadding {
54    Minimal,
55    SurroundingLines,
56}
57
58#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
59#[action(namespace = input, no_json)]
60pub struct Enter {
61    /// Is confirm with secondary.
62    pub secondary: bool,
63    /// Whether the Shift modifier was held when Enter was pressed.
64    pub shift: bool,
65}
66
67impl Enter {
68    /// Returns true if `action` is a primary `Enter` action (`secondary: false`),
69    /// regardless of whether Shift was held.
70    pub fn is_primary(action: &dyn Action) -> bool {
71        action.partial_eq(&Enter {
72            secondary: false,
73            shift: false,
74        }) || action.partial_eq(&Enter {
75            secondary: false,
76            shift: true,
77        })
78    }
79}
80
81actions!(
82    input,
83    [
84        ActivateToken,
85        Backspace,
86        Delete,
87        DeleteToBeginningOfLine,
88        DeleteToEndOfLine,
89        DeleteToPreviousWordStart,
90        DeleteToNextWordEnd,
91        Indent,
92        Outdent,
93        IndentInline,
94        OutdentInline,
95        MoveUp,
96        MoveDown,
97        MoveLeft,
98        MoveRight,
99        MoveHome,
100        MoveEnd,
101        MovePageUp,
102        MovePageDown,
103        AddCursorAbove,
104        AddCursorBelow,
105        SelectAll,
106        SelectToStartOfLine,
107        SelectToEndOfLine,
108        SelectToStart,
109        SelectToEnd,
110        SelectToPreviousWordStart,
111        SelectToNextWordEnd,
112        ShowCharacterPalette,
113        Copy,
114        Cut,
115        Paste,
116        Undo,
117        Redo,
118        MoveToStartOfLine,
119        MoveToEndOfLine,
120        MoveToStart,
121        MoveToEnd,
122        MoveToPreviousWord,
123        MoveToNextWord,
124        Escape,
125        ToggleCodeActions,
126        ShowCompletions,
127        Search,
128        Replace,
129        GoToDefinition,
130    ]
131);
132
133/// An event emitted by an input.
134///
135/// Subscribe to [`InputEditsEvent`] for the immutable edits associated with a
136/// change. `Change` itself remains available for consumers that only need a
137/// notification.
138#[derive(Clone)]
139pub enum InputEvent {
140    Change,
141    PressEnter { secondary: bool, shift: bool },
142    Focus,
143    Blur,
144}
145
146/// An immutable batch of text edits emitted for one input change.
147///
148/// Each entry contains the edit and the document immediately after it, in
149/// application order. Unlike reading the input state in a `Change` subscriber,
150/// this snapshot remains associated with its event when updates are queued.
151#[derive(Clone)]
152pub struct InputEditsEvent {
153    edits: Vec<(InputEdit, Rope)>,
154}
155
156impl InputEditsEvent {
157    /// The edits and the text after each edit, in application order.
158    pub fn edits(&self) -> &[(InputEdit, Rope)] {
159        &self.edits
160    }
161}
162
163pub(super) const CONTEXT: &str = "Input";
164
165pub(crate) fn init(cx: &mut App) {
166    cx.bind_keys([
167        KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
168        KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
169        #[cfg(target_os = "macos")]
170        KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
171        KeyBinding::new("delete", Delete, Some(CONTEXT)),
172        KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
173        #[cfg(target_os = "macos")]
174        KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
175        #[cfg(target_os = "macos")]
176        KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
177        #[cfg(target_os = "macos")]
178        KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
179        #[cfg(not(target_os = "macos"))]
180        KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
181        #[cfg(target_os = "macos")]
182        KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
183        #[cfg(not(target_os = "macos"))]
184        KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
185        KeyBinding::new(
186            "enter",
187            Enter {
188                secondary: false,
189                shift: false,
190            },
191            Some(CONTEXT),
192        ),
193        KeyBinding::new(
194            "shift-enter",
195            Enter {
196                secondary: false,
197                shift: true,
198            },
199            Some(CONTEXT),
200        ),
201        KeyBinding::new(
202            if cx.platform_info().is_mac() {
203                "cmd-enter"
204            } else {
205                "ctrl-enter"
206            },
207            Enter {
208                secondary: true,
209                shift: false,
210            },
211            Some(CONTEXT),
212        ),
213        KeyBinding::new("escape", Escape, Some(CONTEXT)),
214        KeyBinding::new("up", MoveUp, Some(CONTEXT)),
215        KeyBinding::new("down", MoveDown, Some(CONTEXT)),
216        KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
217        KeyBinding::new("right", MoveRight, Some(CONTEXT)),
218        KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
219        KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
220        KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
221        KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
222        #[cfg(target_os = "macos")]
223        KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
224        #[cfg(not(target_os = "macos"))]
225        KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
226        #[cfg(target_os = "macos")]
227        KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
228        #[cfg(not(target_os = "macos"))]
229        KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
230        KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
231        KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
232        KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
233        KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
234        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
235        KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
236        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
237        KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
238        // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them.
239        #[cfg(target_os = "macos")]
240        KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
241        #[cfg(target_os = "macos")]
242        KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
243        #[cfg(target_os = "windows")]
244        KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
245        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
246        KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
247        #[cfg(target_os = "windows")]
248        KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
249        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
250        KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
251        KeyBinding::new("home", MoveHome, Some(CONTEXT)),
252        KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
253        #[cfg(not(target_os = "macos"))]
254        KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
255        #[cfg(not(target_os = "macos"))]
256        KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
257        #[cfg(not(target_os = "macos"))]
258        KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
259        #[cfg(not(target_os = "macos"))]
260        KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
261        KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
262        KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
263        #[cfg(target_os = "macos")]
264        KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
265        #[cfg(target_os = "macos")]
266        KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
267        #[cfg(target_os = "macos")]
268        KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
269        #[cfg(target_os = "macos")]
270        KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
271        #[cfg(any(target_os = "macos", target_os = "linux"))]
272        KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
273        #[cfg(not(target_os = "macos"))]
274        KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
275        #[cfg(any(target_os = "macos", target_os = "linux"))]
276        KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
277        #[cfg(not(target_os = "macos"))]
278        KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
279        #[cfg(target_os = "macos")]
280        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
281        #[cfg(target_os = "macos")]
282        KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
283        #[cfg(not(target_os = "macos"))]
284        KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
285        #[cfg(target_os = "macos")]
286        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
287        #[cfg(not(target_os = "macos"))]
288        KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
289        #[cfg(target_os = "macos")]
290        KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
291        #[cfg(not(target_os = "macos"))]
292        KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
293        #[cfg(target_os = "macos")]
294        KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
295        #[cfg(not(target_os = "macos"))]
296        KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
297        #[cfg(target_os = "macos")]
298        KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
299        #[cfg(target_os = "macos")]
300        KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
301        #[cfg(target_os = "macos")]
302        KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
303        #[cfg(target_os = "macos")]
304        KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
305        #[cfg(target_os = "macos")]
306        KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
307        #[cfg(target_os = "macos")]
308        KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
309        #[cfg(target_os = "macos")]
310        KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
311        #[cfg(target_os = "macos")]
312        KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
313        #[cfg(target_os = "macos")]
314        KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
315        #[cfg(target_os = "macos")]
316        KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
317        #[cfg(not(target_os = "macos"))]
318        KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
319        #[cfg(not(target_os = "macos"))]
320        KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
321        #[cfg(target_os = "macos")]
322        KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
323        #[cfg(target_os = "macos")]
324        KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
325        #[cfg(not(target_os = "macos"))]
326        KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
327        #[cfg(not(target_os = "macos"))]
328        KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
329        #[cfg(target_os = "macos")]
330        KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
331        #[cfg(not(target_os = "macos"))]
332        KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
333        #[cfg(target_os = "macos")]
334        KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
335        #[cfg(not(target_os = "macos"))]
336        KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
337        #[cfg(target_os = "macos")]
338        KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
339        #[cfg(not(target_os = "macos"))]
340        KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
341    ]);
342}
343
344/// A mouse position resolved for a columnar (block) selection.
345///
346/// A position past the end of a short row has no glyph to land on, so `offset` clips to
347/// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they
348/// say which column the pointer really reached, which is what a block spanning rows of
349/// different lengths has to be measured in.
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
351pub(super) struct ColumnarPoint {
352    offset: usize,
353    columns_past_line_end: usize,
354}
355
356impl ColumnarPoint {
357    pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
358        Self {
359            offset,
360            columns_past_line_end,
361        }
362    }
363}
364
365/// The document and selections a paste was asked to replace, taken when the
366/// `Paste` action ran so a clipboard read that resolves later can tell
367/// whether it still applies. See [`InputBaseState::paste_target`].
368#[derive(Debug, PartialEq)]
369struct PasteTarget {
370    document_revision: u64,
371    selections: Vec<CursorSelection>,
372}
373
374/// Caret positioning geometry from the input's latest prepaint.
375///
376/// Unlike `last_layout` (published at paint time), this is stashed during
377/// prepaint so caret-anchored popups can position themselves from the
378/// current frame's geometry in their deferred prepaint, instead of the
379/// previous frame's paint.
380#[derive(Clone, Copy, Debug)]
381#[doc(hidden)]
382pub struct PrepaintCaretGeometry {
383    cursor_bounds: Bounds<Pixels>,
384    line_height: Pixels,
385    input_bounds: Bounds<Pixels>,
386    scroll_offset: Point<Pixels>,
387    /// A resize owns visibility while its requested repaint settles.
388    pub(super) resize_reveal_owned: bool,
389}
390
391impl PrepaintCaretGeometry {
392    pub(super) fn new(
393        cursor_bounds: Bounds<Pixels>,
394        line_height: Pixels,
395        input_bounds: Bounds<Pixels>,
396        scroll_offset: Point<Pixels>,
397    ) -> Self {
398        Self {
399            cursor_bounds,
400            line_height,
401            input_bounds,
402            scroll_offset,
403            resize_reveal_owned: false,
404        }
405    }
406
407    /// The active caret's bounds from the fresh prepaint layout.
408    pub fn cursor_bounds(&self) -> Bounds<Pixels> {
409        self.cursor_bounds
410    }
411
412    /// Line height from the fresh prepaint layout.
413    pub fn line_height(&self) -> Pixels {
414        self.line_height
415    }
416
417    /// The input container bounds from the fresh prepaint.
418    pub fn input_bounds(&self) -> Bounds<Pixels> {
419        self.input_bounds
420    }
421
422    /// The scroll offset that will be in effect after paint, clamped like
423    /// `InputBaseState::update_scroll_offset` clamps it.
424    pub fn scroll_offset(&self) -> Point<Pixels> {
425        self.scroll_offset
426    }
427}
428
429/// The shared text-editing engine behind [`crate::input::InputState`],
430/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
431///
432/// `M` is the mode marker: it carries no data and only decides which methods
433/// exist, so an ordinary input cannot reach the editor's language features.
434///
435/// The three states are type aliases of this one, which is why this name is
436/// public: an alias is only as usable as the type behind it, so hiding this
437/// would leave `InputState` unable to do anything. Prefer naming the aliases
438/// — write `InputState`, not `InputBaseState<InputMode>`.
439pub struct InputBaseState<M: InputModeKind> {
440    /// State only this mode needs. See [`InputModeKind::Extras`].
441    pub(crate) extras: M::Extras,
442    pub(super) focus_handle: FocusHandle,
443    selection_focus: Option<WeakFocusHandle>,
444    pub(super) mode: LayoutMode,
445    pub(super) text: Rope,
446    pub(super) display_map: DisplayMap,
447    pub(super) undo_manager: UndoManager,
448    pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
449    pub(super) pending_token: Option<super::InlineToken>,
450    pub(super) replaying_history: bool,
451    pub(super) validated_token_edit: bool,
452    pub(super) document_revision: u64,
453    pub(super) token_presentation: super::InlineTokenPresentation,
454    pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
455    /// Real per-frame bounds of the placed token elements, keyed by token
456    /// start offset; used for hover payloads and stale-hover reconciliation.
457    pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
458    /// The currently hovered token: its entered span, last measured bounds,
459    /// and UTF-16 range as of entry. Retained so hover exit can still be
460    /// delivered when the token is removed, replaced, scrolled out, or
461    /// disabled.
462    pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
463    pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
464    /// The start offset of a pressed token, with the document revision and
465    /// pointer position at the press.
466    pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
467    pub(super) search_session: super::SearchSession,
468    /// Advances every time search is explicitly invoked. See
469    /// [`InputBaseState::search_activation_revision`].
470    pub(super) search_activation_revision: u64,
471    pub(super) searchable: bool,
472    pub(super) replaceable: bool,
473    pub(super) soft_wrap: bool,
474    pub(super) wrapping_indent: WrappingIndent,
475    pub(super) scroll_beyond_last_line: Option<usize>,
476    pub(super) cursor_surrounding_lines: Option<usize>,
477    pub(super) blink_cursor: Entity<BlinkCursor>,
478    pub(super) loading: bool,
479    /// The cursors and selections.
480    ///
481    /// Always contains at least one selection where index 0 is the active cursor.
482    pub(super) selections: Selections,
483    /// Range for save the selected word, use to keep word range when drag move.
484    pub(super) selected_word_range: Option<CursorSelection>,
485    /// The marked range is the temporary insert text on IME typing.
486    pub(super) ime_marked_range: Option<CursorSelection>,
487    /// Text before an unannounced IME composition, until the next change.
488    ime_original_text: Option<Rope>,
489    pub(super) last_layout: Option<LastLayout>,
490    /// Fresh caret geometry stashed during prepaint for caret-anchored popups.
491    ///
492    /// Popups are positioned in their deferred prepaint, which runs after the
493    /// input's prepaint but before its paint, so they read this instead of
494    /// the previous frame's `last_layout`.
495    pub(crate) prepaint_caret_geometry: Option<PrepaintCaretGeometry>,
496    pub(super) last_cursor: Option<usize>,
497    /// Where the platform was last told the caret is, for its IME panel.
498    pub(super) ime_anchor: Option<(Point<Pixels>, Option<Bounds<Pixels>>)>,
499    /// The input container bounds
500    pub(super) input_bounds: Bounds<Pixels>,
501    /// The text bounds
502    pub(super) last_bounds: Option<Bounds<Pixels>>,
503    /// The fully visible part of the window this input last asked its scroll
504    /// containers to reveal it in, while focused. `None` while unfocused.
505    pub(super) revealed_viewport: Option<Bounds<Pixels>>,
506    pub(super) last_selected_range: Option<CursorSelection>,
507    /// The current edit batch, copied into an event when a change is emitted.
508    pub(super) last_input_edits: Vec<(InputEdit, Rope)>,
509    pub(super) selecting: bool,
510    /// Anchor point of an in-progress columnar (block) selection.
511    pub(super) column_select_start: Option<ColumnarPoint>,
512    /// The selection a long press made, with its handles and edit menu.
513    pub(super) touch_selection: super::touch::TouchSelection,
514    pub(crate) disabled: bool,
515    pub(crate) readonly: bool,
516    pub(crate) text_align: TextAlign,
517    pub(super) masked: bool,
518    pub(super) clean_on_escape: bool,
519    pub(super) submit_on_enter: bool,
520    /// Overrides for [`Self::text_input_configuration`].
521    pub(super) input_action: Option<TextInputAction>,
522    pub(super) autocorrect: Option<bool>,
523    pub(super) autocapitalize: Option<Autocapitalize>,
524    pub(super) show_whitespaces: bool,
525    /// This flag tells the renderer to prefer the end of the current visual line.
526    pub(crate) cursor_line_end_affinity: bool,
527    pub(super) pattern: Option<regex::Regex>,
528    pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
529    /// The minimum value for a numeric input. See [`Self::min`].
530    pub(crate) number_min: Option<f64>,
531    /// The maximum value for a numeric input. See [`Self::max`].
532    pub(crate) number_max: Option<f64>,
533    pub(crate) scroll_handle: ScrollHandle,
534    /// Whether the text stretches past its ends, see [`Self::scroll_bounce`].
535    scroll_bounce: bool,
536    /// The text's stretch past an end, while it lasts.
537    pub(super) overscroll: Overscroll,
538    /// The deferred scroll offset to apply on next layout.
539    pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
540    /// The size of the scrollable content.
541    pub(crate) scroll_size: gpui::Size<Pixels>,
542    pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
543    /// Overview ruler marks in display rows, kept between frames.
544    pub(super) overview_ruler_rows: std::cell::RefCell<OverviewRulerRows>,
545    /// The widest measured unwrapped line width and what it was measured for.
546    pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
547    pub(super) editor_paddings: Edges<Pixels>,
548    /// The style this state paints with: what was projected onto it, with
549    /// every colour left unset resolved from the palette that is current. It
550    /// is rebuilt at the top of every render, which is what keeps it current
551    /// when the palette changes after the state was built.
552    pub(super) editor_style: InputEditorStyle,
553    /// What a consumer projected, kept verbatim so that resolution never
554    /// consumes its own output: resolving in place would fill the unset
555    /// colours once and then never see them as unset again, which is the same
556    /// freeze in a different place.
557    projected_editor_style: InputEditorStyle,
558    pub(super) accessibility: Option<InputAccessibility>,
559    /// What paints in place of Base's editor scrollbar, when a consumer
560    /// supplies its own.
561    pub(super) scrollbar_renderer: Option<crate::input::EditorScrollbarRenderer>,
562
563    /// The mask pattern for formatting the input text
564    pub(crate) mask_pattern: MaskPattern,
565    pub(super) placeholder: SharedString,
566
567    /// Diagnostic currently requested by pointer hover; applications render it.
568    pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
569
570    context_menu_handler: Option<
571        Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
572    >,
573    pending_context_menu: Option<(Point<Pixels>, usize)>,
574    context_menu_offset: Option<usize>,
575
576    /// Whether the context menu that shows on right-click is enabled.
577    ///
578    pub(super) enable_context_menu: bool,
579
580    /// A flag to indicate if we are currently inserting a completion item.
581    pub(super) completion_inserting: bool,
582    pub(super) overlay_action_handler: Option<
583        Rc<
584            dyn Fn(
585                super::InputOverlayKind,
586                Box<dyn Action>,
587                &mut Window,
588                &mut Context<InputBaseState<M>>,
589            ) -> bool,
590        >,
591    >,
592
593    /// A flag to indicate if we have a pending update to the text.
594    ///
595    /// If true, will call some update (for example LSP, Syntax Highlight) before render.
596    _pending_update: bool,
597    /// A flag to indicate if we should ignore the next completion event.
598    pub(super) silent_replace_text: bool,
599    /// A flag to indicate if we should emit InputEvents.
600    pub(super) emit_events: bool,
601
602    _subscriptions: Vec<Subscription>,
603
604    pub(super) auto_scroll: AutoScroll,
605}
606
607/// Accessibility presentation for the editor's existing keyboard-focus boundary.
608///
609/// Frames and their addon controls keep their own identities. This projection
610/// does not create a focus handle or register another text Tab stop. The engine
611/// supplies the live value and guards accessibility actions against its current
612/// disabled, read-only and masked state.
613#[derive(Clone, Debug)]
614pub struct InputAccessibility {
615    role: Option<gpui::Role>,
616    label: Option<SharedString>,
617    description: Option<SharedString>,
618    placeholder: Option<SharedString>,
619    accessibility_id: Option<SharedString>,
620    expanded: Option<bool>,
621    required: bool,
622    invalid: bool,
623    value_exposed: bool,
624}
625
626impl InputAccessibility {
627    pub fn new(role: Option<gpui::Role>) -> Self {
628        Self {
629            role,
630            label: None,
631            description: None,
632            placeholder: None,
633            accessibility_id: None,
634            expanded: None,
635            required: false,
636            invalid: false,
637            value_exposed: true,
638        }
639    }
640
641    pub fn with_role(mut self, role: Option<gpui::Role>) -> Self {
642        self.role = role;
643        self
644    }
645
646    pub fn with_label(mut self, label: Option<SharedString>) -> Self {
647        self.label = label;
648        self
649    }
650
651    /// Supplementary help or validation text, announced after the input's name.
652    pub fn with_description(mut self, description: Option<SharedString>) -> Self {
653        self.description = description;
654        self
655    }
656
657    pub fn with_placeholder(mut self, placeholder: Option<SharedString>) -> Self {
658        self.placeholder = placeholder;
659        self
660    }
661
662    pub fn with_accessibility_id(mut self, id: Option<SharedString>) -> Self {
663        self.accessibility_id = id;
664        self
665    }
666
667    /// Whether an associated suggestion popup is currently expanded.
668    pub fn with_expanded(mut self, expanded: Option<bool>) -> Self {
669        self.expanded = expanded;
670        self
671    }
672
673    /// Reports an application requirement; the application owns validation.
674    pub fn with_required(mut self, required: bool) -> Self {
675        self.required = required;
676        self
677    }
678
679    /// Reports the application's current validation result without changing text.
680    pub fn with_invalid(mut self, invalid: bool) -> Self {
681        self.invalid = invalid;
682        self
683    }
684
685    /// Suppress values for secret content even when the mask is revealed.
686    pub fn with_value_exposed(mut self, exposed: bool) -> Self {
687        self.value_exposed = exposed;
688        self
689    }
690
691    pub fn role(&self) -> Option<gpui::Role> {
692        self.role
693    }
694
695    pub fn label(&self) -> Option<&SharedString> {
696        self.label.as_ref()
697    }
698
699    pub fn description(&self) -> Option<&SharedString> {
700        self.description.as_ref()
701    }
702
703    pub fn placeholder(&self) -> Option<&SharedString> {
704        self.placeholder.as_ref()
705    }
706
707    pub fn accessibility_id(&self) -> Option<&SharedString> {
708        self.accessibility_id.as_ref()
709    }
710
711    pub fn expanded(&self) -> Option<bool> {
712        self.expanded
713    }
714
715    pub fn is_required(&self) -> bool {
716        self.required
717    }
718
719    pub fn is_invalid(&self) -> bool {
720        self.invalid
721    }
722
723    pub fn value_exposed(&self) -> bool {
724        self.value_exposed
725    }
726}
727
728/// Read-only styling data exposed to presentation facades.
729///
730/// The fields are private and read through the methods below, so that a new
731/// one can be added without breaking the facades.
732#[derive(Clone)]
733pub struct InputPresentation {
734    focus_handle: FocusHandle,
735    disabled: bool,
736    readonly: bool,
737    loading: bool,
738    masked: bool,
739    multi_line: bool,
740    code_editor: bool,
741    text_align: TextAlign,
742    placeholder: SharedString,
743    mask_placeholder: Option<String>,
744}
745
746impl InputPresentation {
747    pub fn focus_handle(&self) -> &FocusHandle {
748        &self.focus_handle
749    }
750
751    pub fn is_disabled(&self) -> bool {
752        self.disabled
753    }
754
755    pub fn is_readonly(&self) -> bool {
756        self.readonly
757    }
758
759    /// Returns true if the user is allowed to change the text.
760    ///
761    /// See also: [`InputBaseState::is_editable`].
762    pub fn is_editable(&self) -> bool {
763        !self.disabled && !self.readonly
764    }
765
766    pub fn is_loading(&self) -> bool {
767        self.loading
768    }
769
770    pub fn is_masked(&self) -> bool {
771        self.masked
772    }
773
774    pub fn is_multi_line(&self) -> bool {
775        self.multi_line
776    }
777
778    pub fn is_code_editor(&self) -> bool {
779        self.code_editor
780    }
781
782    pub fn text_align(&self) -> TextAlign {
783        self.text_align
784    }
785
786    pub fn placeholder(&self) -> &SharedString {
787        &self.placeholder
788    }
789
790    /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
791    pub fn mask_placeholder(&self) -> Option<&str> {
792        self.mask_placeholder.as_deref()
793    }
794}
795
796impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
797impl<M: InputModeKind> EventEmitter<InputEditsEvent> for InputBaseState<M> {}
798
799impl<M: InputModeKind> InputBaseState<M> {
800    #[doc(hidden)]
801    pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
802        let layout = self.last_layout.as_ref()?;
803        Some((layout.cursor_bounds?, layout.line_height))
804    }
805
806    /// Caret geometry from the latest prepaint, for caret-anchored popups.
807    ///
808    /// Popups positioned in their deferred prepaint read this to anchor to
809    /// the current frame's caret instead of the previous frame's paint.
810    #[doc(hidden)]
811    pub fn prepaint_caret_geometry(&self) -> Option<PrepaintCaretGeometry> {
812        self.prepaint_caret_geometry
813    }
814
815    pub fn input_bounds(&self) -> Bounds<Pixels> {
816        self.input_bounds
817    }
818
819    pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
820        self.last_bounds
821    }
822
823    /// The cached display map for querying wrapped rows and display positions.
824    ///
825    /// Reading this does not prepare text or force layout. Before the first
826    /// layout, [`DisplayMap::wrap_row_count`] can be zero; prepared empty text
827    /// has one row. The count describes content, independent of minimum rows,
828    /// auto-grow limits and viewport height.
829    ///
830    /// Text edits use the cached wrapping parameters. Layout refreshes the
831    /// cache after width or font changes; consume that count on a subsequent
832    /// render, or use [`Self::prewrap`] to prepare it before the first layout.
833    pub fn display_map(&self) -> &DisplayMap {
834        &self.display_map
835    }
836
837    /// Wrap the text for `font`, `font_size` and `width` before the first
838    /// layout, so that [`DisplayMap::wrap_row_count`] is known on the first frame.
839    ///
840    /// Call it after setting the value and the wrapping indent. `width` is the
841    /// width of the input's text area: its width less its padding, and less
842    /// the line-number gutter for an editor with line numbers. It wraps as
843    /// layout does, a little short of that width and with the state's wrapping
844    /// indent. Once the input has been laid out this does nothing, and layout
845    /// keeps the wrap up to date. The font and font size must match the input's
846    /// actual text style.
847    pub fn prewrap(
848        &mut self,
849        font: gpui::Font,
850        font_size: Pixels,
851        width: Pixels,
852        cx: &mut Context<Self>,
853    ) {
854        if self.last_layout.is_some() {
855            return;
856        }
857        let wrap_width = (width - RIGHT_MARGIN).max(px(1.));
858        self.display_map.set_font(font, font_size, cx);
859        self.display_map
860            .set_tab_size(self.mode.tab_size().tab_size, cx);
861        self.display_map
862            .on_layout_changed(self.soft_wrap.then_some(wrap_width), cx);
863        self.display_map
864            .set_wrapping_indent(self.wrapping_indent, cx);
865        self.display_map.ensure_text_prepared(&self.text, cx);
866    }
867
868    pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
869        self.diagnostic_popover.clone()
870    }
871
872    pub fn presentation(&self) -> InputPresentation {
873        InputPresentation {
874            focus_handle: self.focus_handle.clone(),
875            disabled: self.disabled,
876            readonly: self.readonly,
877            loading: self.loading,
878            masked: self.masked,
879            multi_line: self.is_multi_line(),
880            code_editor: self.is_code_editor(),
881            text_align: self.text_align,
882            placeholder: self.placeholder.clone(),
883            mask_placeholder: self.mask_pattern.placeholder(),
884        }
885    }
886
887    /// Whether this input spans more than one line.
888    ///
889    /// Answered by the mode marker, which is fixed when the state is built.
890    /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
891    #[inline]
892    /// Whether this input paints scrollbars.
893    ///
894    /// Only a multi-line input can scroll: a single-line input keeps its
895    /// caret in view by moving its own offset, and never has a viewport a
896    /// user could drag. Adding the editor scrollbar to every input put a
897    /// thumb inside every text field, which is a control the field does not
898    /// have.
899    pub(crate) fn shows_scrollbar(&self) -> bool {
900        self.is_multi_line()
901    }
902
903    pub fn is_multi_line(&self) -> bool {
904        M::MULTI_LINE
905    }
906
907    /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
908    #[inline]
909    pub fn is_single_line(&self) -> bool {
910        !M::MULTI_LINE
911    }
912
913    /// Whether this input is a source-code editor.
914    #[inline]
915    pub fn is_code_editor(&self) -> bool {
916        M::CODE_EDITOR
917    }
918
919    /// Whether the user is allowed to copy the selection out.
920    ///
921    /// A masked input keeps its value out of the clipboard.
922    pub fn is_copyable(&self) -> bool {
923        self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
924    }
925
926    pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
927        let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
928        InputContextMenuCapabilities::new()
929            .disabled(self.disabled)
930            .readonly(self.readonly)
931            .code_editor(self.is_code_editor())
932            .selection(!self.active_selection().is_empty())
933            .masked(self.masked)
934            .go_to_definition(go_to_definition)
935            .code_actions(code_actions)
936    }
937
938    pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
939        if !self.is_single_line() || self.text_align == text_align {
940            return;
941        }
942
943        self.text_align = text_align;
944        cx.notify();
945    }
946
947    /// Flip the password mask.
948    ///
949    /// Setting the mask is a single-line method, but flipping it stays here:
950    /// the reveal button is rendered from the generic path, and it can only be
951    /// switched on through [`crate::input::InputState`] anyway.
952    pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
953        self.masked = !self.masked;
954        cx.notify();
955    }
956
957    pub fn on_context_menu(
958        &mut self,
959        handler: Rc<
960            dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
961        >,
962    ) {
963        self.context_menu_handler = Some(handler);
964    }
965
966    /// Keeps the selection highlighted while this popup or one of its children has focus.
967    ///
968    /// This does not transfer keyboard focus or keep the caret visible. The
969    /// association holds only a weak focus handle. Pass `None` to clear it.
970    pub fn set_selection_focus(&mut self, focus: Option<FocusHandle>, cx: &mut Context<Self>) {
971        self.selection_focus = focus.as_ref().map(FocusHandle::downgrade);
972        cx.notify();
973    }
974
975    /// Whether the input or its associated selection popup has focus.
976    pub fn has_selection_focus(&self, window: &Window, cx: &App) -> bool {
977        self.focus_handle.is_focused(window)
978            || self
979                .selection_focus
980                .as_ref()
981                .and_then(WeakFocusHandle::upgrade)
982                .is_some_and(|focus| focus.is_focused(window) || focus.contains_focused(window, cx))
983    }
984
985    /// Build the engine. Each mode's own `new` sets its layout on top of this.
986    fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
987        let focus_handle = cx.focus_handle().tab_stop(true);
988        let blink_cursor = cx.new(BlinkCursor::new);
989        let undo_manager = UndoManager::new();
990
991        let _subscriptions = vec![
992            // Key bindings can consume events before on_key_down. Observe input
993            // before action dispatch so every keystroke resets the blink delay.
994            cx.intercept_keystrokes({
995                let focus_handle = focus_handle.clone();
996                let blink_cursor = blink_cursor.downgrade();
997                move |_, window, cx| {
998                    if focus_handle.is_focused(window) {
999                        _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
1000                    }
1001                }
1002            }),
1003            // Observe the blink cursor to repaint the view when it changes.
1004            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
1005            // Blink the cursor when the window is active, pause when it's not.
1006            cx.observe_window_activation(window, |input, window, cx| {
1007                if !window.is_window_active() {
1008                    input.cancel_mouse_gesture(cx);
1009                }
1010                if window.is_window_active() {
1011                    let focus_handle = input.focus_handle.clone();
1012                    if focus_handle.is_focused(window) {
1013                        input.blink_cursor.update(cx, |blink_cursor, cx| {
1014                            blink_cursor.start(cx);
1015                        });
1016                    }
1017                }
1018            }),
1019            cx.observe_window_bounds(window, |input, _, cx| input.cancel_mouse_gesture(cx)),
1020            cx.on_focus(&focus_handle, window, Self::on_focus),
1021            cx.on_blur(&focus_handle, window, Self::on_blur),
1022        ];
1023
1024        let text_style = window.text_style();
1025
1026        Self {
1027            extras: M::Extras::default(),
1028            focus_handle: focus_handle.clone(),
1029            selection_focus: None,
1030            text: "".into(),
1031            display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
1032            search_session: super::SearchSession::default(),
1033            search_activation_revision: 0,
1034            searchable: false,
1035            replaceable: true,
1036            soft_wrap: true,
1037            wrapping_indent: WrappingIndent::default(),
1038            scroll_beyond_last_line: None,
1039            cursor_surrounding_lines: None,
1040            blink_cursor,
1041            undo_manager,
1042            inline_tokens: None,
1043            pending_token: None,
1044            replaying_history: false,
1045            validated_token_edit: false,
1046            document_revision: 0,
1047            token_presentation: Default::default(),
1048            token_bounds: Default::default(),
1049            hovered_token: None,
1050            pending_token_hover_exits: Vec::new(),
1051            token_layout_cache: None,
1052            pressed_token: None,
1053            selections: Selections::default(),
1054            selected_word_range: None,
1055            ime_marked_range: None,
1056            ime_original_text: None,
1057            input_bounds: Bounds::default(),
1058            selecting: false,
1059            touch_selection: Default::default(),
1060            disabled: false,
1061            readonly: false,
1062            text_align: TextAlign::Left,
1063            masked: false,
1064            clean_on_escape: false,
1065            submit_on_enter: false,
1066            input_action: None,
1067            autocorrect: None,
1068            autocapitalize: None,
1069            show_whitespaces: false,
1070            loading: false,
1071            pattern: None,
1072            validate: None,
1073            number_min: None,
1074            number_max: None,
1075            mode: LayoutMode::default(),
1076            last_layout: None,
1077            prepaint_caret_geometry: None,
1078            last_bounds: None,
1079            revealed_viewport: None,
1080            last_selected_range: None,
1081            last_input_edits: Vec::new(),
1082            column_select_start: None,
1083            last_cursor: None,
1084            ime_anchor: None,
1085            scroll_handle: ScrollHandle::new(),
1086            scroll_bounce: crate::ScrollBounce::enabled_by_default(),
1087            overscroll: Overscroll::default(),
1088            scroll_size: gpui::size(px(0.), px(0.)),
1089            editor_scrollbar_snapshot: Cell::new(None),
1090            overview_ruler_rows: Default::default(),
1091            longest_line_width: Cell::new(None),
1092            editor_paddings: Edges::default(),
1093            deferred_scroll_offset: None,
1094            placeholder: SharedString::default(),
1095            mask_pattern: MaskPattern::default(),
1096            editor_style: InputEditorStyle::default(),
1097            projected_editor_style: InputEditorStyle::default(),
1098            accessibility: None,
1099            scrollbar_renderer: None,
1100            diagnostic_popover: None,
1101            context_menu_handler: None,
1102            pending_context_menu: None,
1103            context_menu_offset: None,
1104            enable_context_menu: true,
1105            completion_inserting: false,
1106            overlay_action_handler: None,
1107            silent_replace_text: false,
1108            emit_events: true,
1109            _subscriptions,
1110            _pending_update: false,
1111            cursor_line_end_affinity: false,
1112            auto_scroll: AutoScroll::default(),
1113        }
1114    }
1115
1116    /// Sets whether the context menu that shows on right-click is enabled.
1117    ///
1118    /// The context menu is enabled by default. Disabling it turns off the
1119    /// right-click menu entirely, including a custom menu set on the element.
1120    /// A custom menu already replaces the built-in one, so keep this enabled
1121    /// to show only your own items.
1122    pub fn context_menu(mut self, enable: bool) -> Self {
1123        self.enable_context_menu = enable;
1124        self
1125    }
1126
1127    pub fn set_context_menu_enabled(&mut self, enabled: bool) {
1128        self.enable_context_menu = enabled;
1129    }
1130
1131    /// Set whether search UI allows replacement, default is true.
1132    #[doc(hidden)]
1133    pub fn replaceable(mut self, allow: bool) -> Self {
1134        self.replaceable = allow;
1135        self
1136    }
1137
1138    /// Set placeholder
1139    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1140        self.placeholder = placeholder.into();
1141        self
1142    }
1143
1144    /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode.
1145    pub fn set_highlighter(
1146        &mut self,
1147        new_language: impl Into<SharedString>,
1148        cx: &mut Context<Self>,
1149    ) {
1150        match &mut self.mode {
1151            LayoutMode::CodeEditor {
1152                language,
1153                highlighter,
1154                ..
1155            } => {
1156                language.set_name(new_language.into());
1157                *highlighter.borrow_mut() = None;
1158            }
1159            _ => {}
1160        }
1161        self.refresh(cx);
1162    }
1163
1164    fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
1165        match &mut self.mode {
1166            LayoutMode::CodeEditor { highlighter, .. } => {
1167                *highlighter.borrow_mut() = None;
1168            }
1169            _ => {}
1170        }
1171        cx.notify();
1172    }
1173
1174    /// Install the parser/highlighter adapter used by code-editor mode.
1175    pub fn set_highlighter_factory(
1176        &mut self,
1177        factory: InputHighlighterFactory,
1178        cx: &mut Context<Self>,
1179    ) {
1180        self.mode.set_highlighter_factory(factory);
1181        self._pending_update = true;
1182        self.token_layout_cache = None;
1183        cx.notify();
1184    }
1185
1186    /// Install a default adapter without replacing an application-provided one.
1187    pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
1188        self.mode.ensure_highlighter_factory(factory);
1189    }
1190
1191    pub fn set_editor_style(&mut self, style: InputEditorStyle) {
1192        self.editor_style = style.clone();
1193        self.projected_editor_style = style;
1194    }
1195
1196    /// Project semantics onto the editor, never onto a second focus owner.
1197    pub fn set_accessibility(&mut self, accessibility: InputAccessibility) {
1198        self.accessibility = Some(accessibility);
1199    }
1200
1201    /// Existing native semantics, for compositions that change only their own fields.
1202    pub fn accessibility(&self) -> Option<&InputAccessibility> {
1203        self.accessibility.as_ref()
1204    }
1205
1206    fn handle_accessibility_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1207        if !self.disabled {
1208            self.focus(window, cx);
1209        }
1210    }
1211
1212    fn handle_accessibility_set_value(
1213        &mut self,
1214        data: Option<&gpui::accesskit::ActionData>,
1215        window: &mut Window,
1216        cx: &mut Context<Self>,
1217    ) {
1218        let Some(gpui::accesskit::ActionData::Value(value)) = data else {
1219            return;
1220        };
1221        // The action may have been queued before editability changed.
1222        if self.is_editable() {
1223            self.replace_all(value.to_string(), window, cx);
1224        }
1225    }
1226
1227    /// Set presentation padding for multi-line text and its scrollbar layout.
1228    #[doc(hidden)]
1229    pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
1230        self.editor_paddings = paddings;
1231    }
1232
1233    /// Supply the element painted in place of the editor's scrollbar, or
1234    /// `None` to keep Base's. The renderer is called where the editor paints
1235    /// its scrollbar, with that frame's [`EditorScrollbarContext`]. Like
1236    /// [`Self::set_editor_style`], this does not notify, so it can be called
1237    /// while rendering.
1238    ///
1239    /// [`EditorScrollbarContext`]: crate::input::EditorScrollbarContext
1240    pub fn set_scrollbar_renderer(
1241        &mut self,
1242        renderer: Option<crate::input::EditorScrollbarRenderer>,
1243    ) {
1244        self.scrollbar_renderer = renderer;
1245    }
1246
1247    pub fn apply_highlighter_fold_candidates(
1248        &mut self,
1249        candidates: Vec<crate::input::FoldRange>,
1250        cx: &mut Context<Self>,
1251    ) {
1252        if self.mode.is_folding() {
1253            self.display_map.set_fold_candidates(candidates);
1254        }
1255        cx.notify();
1256    }
1257
1258    #[inline]
1259    pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
1260        self.mode.diagnostics()
1261    }
1262
1263    #[inline]
1264    pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
1265        self.mode.diagnostics_mut()
1266    }
1267
1268    /// Set placeholder
1269    pub fn set_placeholder(
1270        &mut self,
1271        placeholder: impl Into<SharedString>,
1272        _: &mut Window,
1273        cx: &mut Context<Self>,
1274    ) {
1275        self.placeholder = placeholder.into();
1276        cx.notify();
1277    }
1278
1279    /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
1280    ///
1281    /// Returns:
1282    ///
1283    /// - The index of the line (zero-based) containing the offset.
1284    /// - The index of the sub-line (zero-based) within the line containing the offset.
1285    /// - The position of the offset.
1286    pub(super) fn line_and_position_for_offset(
1287        &self,
1288        offset: usize,
1289    ) -> (usize, usize, Option<Point<Pixels>>) {
1290        let Some(last_layout) = &self.last_layout else {
1291            return (0, 0, None);
1292        };
1293        let line_height = last_layout.line_height;
1294        let target_row = self.text.offset_to_point(offset.min(self.text.len())).row;
1295
1296        let mut y_offset = last_layout.visible_top;
1297        for (vi, line) in last_layout.lines.iter().enumerate() {
1298            let buffer_line = last_layout.visible_buffer_lines[vi];
1299            if buffer_line == target_row {
1300                let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
1301                let local_offset = offset.saturating_sub(prev_lines_offset).min(line.len());
1302                let pos = line
1303                    .position_for_index(local_offset, last_layout, false)
1304                    .unwrap_or_else(|| point(px(0.), px(0.)));
1305                let sub_line_index = (pos.y / line_height) as usize;
1306                let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
1307                return (vi, sub_line_index, Some(adjusted_pos));
1308            }
1309
1310            y_offset += line.size(line_height).height;
1311        }
1312        (0, 0, None)
1313    }
1314
1315    /// Set the value of the input field: plain text, or [`InputContent`] to
1316    /// restore text together with its inline tokens. Editing history is
1317    /// cleared and no [`InputEvent::Change`] is emitted.
1318    ///
1319    /// For single-line inputs the caret is placed at the end of the text while
1320    /// the view is scrolled back to the start, so a long value shows its
1321    /// beginning instead of its tail (matching HTML `<input>`). Multi-line
1322    /// inputs reset the selection to `0..0`.
1323    pub fn set_value(
1324        &mut self,
1325        value: impl Into<super::InputContent>,
1326        window: &mut Window,
1327        cx: &mut Context<Self>,
1328    ) {
1329        let content = value.into();
1330        self.inline_tokens = None;
1331        self.undo_manager.set_ignoring(true);
1332        self.emit_events = false;
1333        self.replace_text(content.text().clone(), window, cx);
1334        self.ime_original_text = None;
1335        self.install_tokens(content);
1336        self.undo_manager.set_ignoring(false);
1337        self.emit_events = true;
1338
1339        self.reset_selection();
1340        self.reset_lsp_state();
1341        self.reset_scroll_to_start();
1342
1343        self.undo_manager.clear();
1344        cx.notify();
1345    }
1346
1347    /// Replace the entire text content while preserving undo history.
1348    ///
1349    /// Unlike [`set_value`](Self::set_value), this method records the
1350    /// replacement in the undo stack, allowing the user to undo/redo
1351    /// the change. The selection is placed at the end of the new text
1352    /// for single-line inputs, or cleared (0..0) for multi-line inputs.
1353    ///
1354    /// Use this when programmatically replacing the full text but the
1355    /// user should still be able to undo the operation — e.g. formatting.
1356    pub fn replace_all(
1357        &mut self,
1358        text: impl Into<SharedString>,
1359        window: &mut Window,
1360        cx: &mut Context<Self>,
1361    ) {
1362        self.replace_text(text, window, cx);
1363        self.reset_selection();
1364        self.reset_lsp_state();
1365        self.reset_scroll_to_start();
1366
1367        cx.notify();
1368    }
1369
1370    /// Perform `f` with the user-facing edit restrictions lifted.
1371    ///
1372    /// The `disabled` and `readonly` modes only reject the changes made by the
1373    /// user, the programmatic APIs must always be able to update the text.
1374    pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1375        let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1376        (self.disabled, self.readonly) = (false, false);
1377        f(self);
1378        (self.disabled, self.readonly) = (was_disabled, was_readonly);
1379    }
1380
1381    /// Insert text at the current cursor position.
1382    ///
1383    /// And the cursor will be moved to the end of inserted text.
1384    pub fn insert(
1385        &mut self,
1386        text: impl Into<SharedString>,
1387        window: &mut Window,
1388        cx: &mut Context<Self>,
1389    ) {
1390        let text: SharedString = text.into();
1391        self.with_edits_allowed(|this| {
1392            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1393            let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1394            this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1395            let end = this.active_selection().end;
1396            this.set_cursor_to(end);
1397        });
1398    }
1399
1400    /// Replace text at the current cursor position.
1401    ///
1402    /// And the cursor will be moved to the end of replaced text.
1403    pub fn replace(
1404        &mut self,
1405        text: impl Into<SharedString>,
1406        window: &mut Window,
1407        cx: &mut Context<Self>,
1408    ) {
1409        let text: SharedString = text.into();
1410        self.with_edits_allowed(|this| {
1411            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1412            this.replace_text_in_range_silent(None, &text, window, cx);
1413            let end = this.active_selection().end;
1414            this.set_cursor_to(end);
1415        });
1416    }
1417
1418    fn replace_text(
1419        &mut self,
1420        text: impl Into<SharedString>,
1421        window: &mut Window,
1422        cx: &mut Context<Self>,
1423    ) {
1424        let text: SharedString = text.into();
1425        self.with_edits_allowed(|this| {
1426            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1427            let range = 0..this.text.chars().map(|c| c.len_utf16()).sum();
1428            this.replace_text_in_range_silent(Some(range), &text, window, cx);
1429            this.reset_highlighter(cx);
1430        });
1431    }
1432
1433    fn reset_selection(&mut self) {
1434        self.selections.remove_all_but_active();
1435
1436        // For single-line inputs the caret is placed at the end of the text
1437        // (matching HTML `<input>`); multi-line inputs reset the selection to
1438        // `0..0`.
1439        if self.is_single_line() {
1440            let end = self.text.len();
1441            self.set_cursor_to(end);
1442        } else {
1443            self.active_selection_mut().clear();
1444        }
1445    }
1446
1447    fn reset_lsp_state(&mut self) {
1448        if self.is_code_editor() {
1449            self._pending_update = true;
1450            M::reset_language_features(self);
1451        }
1452    }
1453
1454    fn reset_scroll_to_start(&mut self) {
1455        // Move scroll to the start. For single-line the caret is at the end, so
1456        // override the cursor-follow scroll for the next painted frame to keep
1457        // the start visible; the deferred offset is consumed during that paint.
1458        self.scroll_handle.set_offset(point(px(0.), px(0.)));
1459        if self.is_single_line() {
1460            self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1461        }
1462    }
1463
1464    /// Set with disabled mode.
1465    ///
1466    /// See also: [`Self::set_disabled`].
1467    #[allow(unused)]
1468    pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1469        self.disabled = disabled;
1470        self
1471    }
1472
1473    /// Disables editing and normal Tab entry. An already-focused field retains
1474    /// its focus binding so Tab and Shift-Tab can leave it.
1475    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1476        if self.disabled == disabled {
1477            return;
1478        }
1479
1480        self.disabled = disabled;
1481        if disabled {
1482            M::hide_context_menu(self, cx);
1483            M::clear_inline_completion(self, cx);
1484        }
1485        cx.notify();
1486    }
1487
1488    /// Set with read-only mode.
1489    ///
1490    /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1491    /// focus, cursor, selection and copy behavior, it only rejects any change
1492    /// of the text made by the user.
1493    ///
1494    /// See also: [`Self::set_readonly`].
1495    #[allow(unused)]
1496    pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1497        self.readonly = readonly;
1498        self
1499    }
1500
1501    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1502        if self.readonly == readonly {
1503            return;
1504        }
1505
1506        self.readonly = readonly;
1507        if readonly {
1508            M::hide_context_menu(self, cx);
1509            M::clear_inline_completion(self, cx);
1510            self.search_session.replace_mode = false;
1511        }
1512        cx.notify();
1513    }
1514
1515    /// Returns true if the user is allowed to change the text.
1516    ///
1517    /// This is false when the input is `disabled` or `readonly`, the programmatic
1518    /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1519    pub fn is_editable(&self) -> bool {
1520        !self.disabled && !self.readonly
1521    }
1522
1523    /// Set true to clear the input by pressing Escape key.
1524    ///
1525    /// Not on Android, where Escape is also the back button.
1526    pub fn clean_on_escape(mut self) -> Self {
1527        self.clean_on_escape = true;
1528        self
1529    }
1530
1531    pub fn set_clean_on_escape(&mut self, clean: bool) {
1532        self.clean_on_escape = clean;
1533    }
1534
1535    /// Set true to treat `Enter` as a submit action in multi-line mode,
1536    /// while `Shift+Enter` inserts a newline.
1537    ///
1538    /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1539    #[doc(hidden)]
1540    pub fn submit_on_enter(mut self, submit: bool) -> Self {
1541        self.submit_on_enter = submit;
1542        self
1543    }
1544
1545    pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1546        self.submit_on_enter = submit;
1547        cx.notify();
1548    }
1549
1550    /// Set the action a software keyboard shows on its enter key, like Search
1551    /// or Send. Pressing it still emits [`InputEvent::PressEnter`].
1552    ///
1553    /// Default is [`TextInputAction::Done`] for a single-line input (and a
1554    /// multi-line one that submits on enter), and [`TextInputAction::Enter`]
1555    /// (a line break) for a multi-line input.
1556    pub fn input_action(mut self, action: TextInputAction) -> Self {
1557        self.input_action = Some(action);
1558        self
1559    }
1560
1561    /// Set whether the platform may autocorrect the text and offer word
1562    /// suggestions.
1563    ///
1564    /// Default is `false`. Enable this explicitly for fields that accept prose;
1565    /// masking or revealing text does not change the setting.
1566    pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1567        self.autocorrect = Some(autocorrect);
1568        self
1569    }
1570
1571    /// Set how a software keyboard capitalizes the text.
1572    ///
1573    /// Default is [`Autocapitalize::None`]. Enable capitalization explicitly for
1574    /// fields where it is appropriate, independently of autocorrection.
1575    pub fn autocapitalize(mut self, autocapitalize: Autocapitalize) -> Self {
1576        self.autocapitalize = Some(autocapitalize);
1577        self
1578    }
1579
1580    /// The text assistance a platform IME (a software keyboard) should give
1581    /// this input, from [`Self::input_action`], [`Self::autocorrect`] and
1582    /// [`Self::autocapitalize`] or the defaults they describe.
1583    pub fn text_input_configuration(&self) -> TextInputConfiguration {
1584        // Masking is a presentation choice, not a reliable content type: a
1585        // revealed password must not acquire text assistance. Keep assistance
1586        // opt-in for structured fields such as passwords, email and URLs.
1587        let autocorrect = self.autocorrect.unwrap_or(false);
1588        let input_action =
1589            self.input_action
1590                .unwrap_or(if self.is_multi_line() && !self.submit_on_enter {
1591                    TextInputAction::Enter
1592                } else {
1593                    TextInputAction::Done
1594                });
1595        TextInputConfiguration {
1596            autocorrect,
1597            autocapitalize: self.autocapitalize.unwrap_or(Autocapitalize::None),
1598            suggestions: autocorrect,
1599            input_action,
1600        }
1601    }
1602
1603    /// Set whether to show whitespace characters.
1604    #[doc(hidden)]
1605    pub fn show_whitespaces(mut self, show: bool) -> Self {
1606        self.show_whitespaces = show;
1607        self
1608    }
1609
1610    /// Update whether to show whitespace characters.
1611    pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1612        self.show_whitespaces = show;
1613        cx.notify();
1614    }
1615
1616    /// Empty rows reserved below the last line of content ("scroll
1617    /// beyond last line"), code-editor mode only. Mirrors VSCode's
1618    /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1619    ///
1620    /// - `None` (default): half the viewport, floored at
1621    ///   [`BOTTOM_MARGIN_ROWS`] line-heights.
1622    /// - `Some(0)`: no trailing space; the cursor sits flush with the
1623    ///   last row at scroll-max.
1624    /// - `Some(n)`: exactly `n` rows.
1625    pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1626        self.scroll_beyond_last_line = rows;
1627        self
1628    }
1629
1630    /// Update [`Self::scroll_beyond_last_line`] after construction.
1631    pub fn set_scroll_beyond_last_line(
1632        &mut self,
1633        rows: Option<usize>,
1634        _: &mut Window,
1635        cx: &mut Context<Self>,
1636    ) {
1637        if self.scroll_beyond_last_line == rows {
1638            return;
1639        }
1640        self.scroll_beyond_last_line = rows;
1641        cx.notify();
1642    }
1643
1644    /// Minimum number of lines the cursor is kept clear of the viewport's
1645    /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1646    /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1647    /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1648    /// empty region; this controls the cursor's resting distance from the
1649    /// edge.
1650    ///
1651    /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to
1652    ///   one line on small viewports.
1653    /// - `Some(n)`: requests `n` lines, clamped to half the viewport.
1654    ///
1655    /// In a constrained viewport, edge clearance yields to the cursor's
1656    /// complete visual row so surrounding space cannot clip the text being edited.
1657    pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1658        self.cursor_surrounding_lines = lines;
1659        self
1660    }
1661
1662    /// Update [`Self::cursor_surrounding_lines`] after construction.
1663    pub fn set_cursor_surrounding_lines(
1664        &mut self,
1665        lines: Option<usize>,
1666        _: &mut Window,
1667        cx: &mut Context<Self>,
1668    ) {
1669        if self.cursor_surrounding_lines == lines {
1670            return;
1671        }
1672        self.cursor_surrounding_lines = lines;
1673        cx.notify();
1674    }
1675
1676    /// Set the default value of the input field.
1677    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1678        let text: SharedString = value.into();
1679        self.text = Rope::from(self.normalize_input(&text).as_ref());
1680        if let Some(diagnostics) = self.mode.diagnostics_mut() {
1681            diagnostics.reset(&self.text)
1682        }
1683        // Note: We can't call display_map.set_text here because it needs cx.
1684        // The text will be set during prepare_if_need in element.rs
1685        self._pending_update = true;
1686        self
1687    }
1688
1689    /// Return the value of the input field as an owned string.
1690    ///
1691    /// The string is materialized on each call. See [`Self::text`] for the
1692    /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1693    pub fn value(&self) -> SharedString {
1694        SharedString::new(self.text.to_string())
1695    }
1696
1697    /// Return the portion of the value within the input field that
1698    /// is selected by the user, as an owned string.
1699    ///
1700    /// The string is materialized on each call. See [`Self::selected_text`]
1701    /// for the same selection borrowed out of the [`Rope`] the state owns.
1702    pub fn selected_value(&self) -> SharedString {
1703        SharedString::new(self.selected_text().to_string())
1704    }
1705
1706    /// Return the value without mask.
1707    pub fn unmask_value(&self) -> SharedString {
1708        self.mask_pattern.unmask(&self.text.to_string()).into()
1709    }
1710
1711    /// Kept so existing render paths keep compiling.
1712    ///
1713    /// Configuration used to be collected by a facade and applied here; the
1714    /// state now configures itself, so this does nothing and can be deleted at
1715    /// the call site.
1716    #[doc(hidden)]
1717    pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1718
1719    /// Return the text [`Rope`] of the input field.
1720    ///
1721    /// Borrowed from the state, so reading even a large document copies
1722    /// nothing. See [`Self::value`] when an owned string is wanted.
1723    pub fn text(&self) -> &Rope {
1724        &self.text
1725    }
1726
1727    /// Report the change with its own snapshot before the legacy notification.
1728    fn emit_change(&mut self, cx: &mut Context<Self>) {
1729        if let Some(original) = self.ime_original_text.take() {
1730            self.last_input_edits = vec![(
1731                Self::full_input_edit(&original, &self.text),
1732                self.text.clone(),
1733            )];
1734        }
1735        cx.emit(InputEditsEvent {
1736            edits: self.last_input_edits.clone(),
1737        });
1738        cx.emit(InputEvent::Change);
1739    }
1740
1741    fn full_input_edit(old_text: &Rope, new_text: &Rope) -> InputEdit {
1742        InputEdit {
1743            start_byte: 0,
1744            old_end_byte: old_text.len(),
1745            new_end_byte: new_text.len(),
1746            start_position: old_text.offset_to_point(0),
1747            old_end_position: old_text.offset_to_point(old_text.len()),
1748            new_end_position: new_text.offset_to_point(new_text.len()),
1749        }
1750    }
1751
1752    /// Return the (0-based) [`Position`] of the cursor.
1753    pub fn cursor_position(&self) -> Position {
1754        let offset = self.cursor();
1755        self.text.offset_to_position(offset)
1756    }
1757
1758    /// Set (0-based) [`Position`] of the cursor.
1759    ///
1760    /// This will move the cursor to the specified line and column, and update the selection range.
1761    pub fn set_cursor_position(
1762        &mut self,
1763        position: impl Into<Position>,
1764        window: &mut Window,
1765        cx: &mut Context<Self>,
1766    ) {
1767        let position: Position = position.into();
1768        let offset = self.text.position_to_offset(&position);
1769
1770        self.move_to(offset, None, cx);
1771        self.update_preferred_column();
1772        self.focus(window, cx);
1773    }
1774
1775    /// Focus the input field.
1776    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1777        self.focus_handle.focus(window, cx);
1778        self.blink_cursor.update(cx, |cursor, cx| {
1779            cursor.start(cx);
1780        });
1781    }
1782
1783    /// Refresh the input, so the next render re-runs syntax highlighting and
1784    /// the LSP providers, not just a redraw.
1785    ///
1786    /// Assigning the `lsp` providers (or other render-affecting state) at
1787    /// runtime does not take effect until the text next changes. Call this
1788    /// afterwards to force the refresh on the next render.
1789    ///
1790    /// ```ignore
1791    /// input.update(cx, |state, cx| {
1792    ///     state.extras.lsp.hover_provider = Some(provider);
1793    ///     state.refresh(cx);
1794    /// });
1795    /// ```
1796    pub fn refresh(&mut self, cx: &mut Context<Self>) {
1797        self._pending_update = true;
1798        cx.notify();
1799    }
1800
1801    pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1802        self.undo_manager.break_transaction_coalescing();
1803        self.select_all_cursors_to(|s, sel| s.previous_boundary(sel.cursor_offset()), cx);
1804    }
1805
1806    pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1807        self.select_all_cursors_to(|s, sel| s.next_boundary(sel.cursor_offset()), cx);
1808    }
1809
1810    pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1811        if self.is_single_line() {
1812            return;
1813        }
1814        self.select_all_cursors_to_with_affinity(
1815            |s, sel| {
1816                s.vertical_selection_target(
1817                    sel.cursor_offset(),
1818                    sel.column_anchor,
1819                    s.line_end_affinity_for(sel),
1820                    -1,
1821                )
1822            },
1823            true,
1824            cx,
1825        );
1826    }
1827
1828    pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1829        if self.is_single_line() {
1830            return;
1831        }
1832        self.select_all_cursors_to_with_affinity(
1833            |s, sel| {
1834                s.vertical_selection_target(
1835                    sel.cursor_offset(),
1836                    sel.column_anchor,
1837                    s.line_end_affinity_for(sel),
1838                    1,
1839                )
1840            },
1841            true,
1842            cx,
1843        );
1844    }
1845
1846    pub(super) fn on_action_select_all(
1847        &mut self,
1848        _: &SelectAll,
1849        window: &mut Window,
1850        cx: &mut Context<Self>,
1851    ) {
1852        self.select_all(window, cx);
1853    }
1854
1855    pub(super) fn select_to_start(
1856        &mut self,
1857        _: &SelectToStart,
1858        _: &mut Window,
1859        cx: &mut Context<Self>,
1860    ) {
1861        self.undo_manager.break_transaction_coalescing();
1862        self.select_all_cursors_to(|_, _| 0, cx);
1863    }
1864
1865    pub(super) fn select_to_end(
1866        &mut self,
1867        _: &SelectToEnd,
1868        _: &mut Window,
1869        cx: &mut Context<Self>,
1870    ) {
1871        self.undo_manager.break_transaction_coalescing();
1872        let end = self.text.len();
1873        self.select_all_cursors_to(move |_, _| end, cx);
1874    }
1875
1876    pub(super) fn select_to_start_of_line(
1877        &mut self,
1878        _: &SelectToStartOfLine,
1879        _: &mut Window,
1880        cx: &mut Context<Self>,
1881    ) {
1882        self.undo_manager.break_transaction_coalescing();
1883        self.select_all_cursors_to(
1884            |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1885            cx,
1886        );
1887    }
1888
1889    pub(super) fn select_to_end_of_line(
1890        &mut self,
1891        _: &SelectToEndOfLine,
1892        _: &mut Window,
1893        cx: &mut Context<Self>,
1894    ) {
1895        self.undo_manager.break_transaction_coalescing();
1896        self.select_all_cursors_to_with_affinity(
1897            |s, sel| {
1898                (
1899                    s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1900                    true,
1901                )
1902            },
1903            false,
1904            cx,
1905        );
1906    }
1907
1908    pub(super) fn select_to_previous_word(
1909        &mut self,
1910        _: &SelectToPreviousWordStart,
1911        _: &mut Window,
1912        cx: &mut Context<Self>,
1913    ) {
1914        self.undo_manager.break_transaction_coalescing();
1915        self.select_all_cursors_to(
1916            |s, sel| s.previous_start_of_word_at(sel.cursor_offset()),
1917            cx,
1918        );
1919    }
1920
1921    pub(super) fn select_to_next_word(
1922        &mut self,
1923        _: &SelectToNextWordEnd,
1924        _: &mut Window,
1925        cx: &mut Context<Self>,
1926    ) {
1927        self.undo_manager.break_transaction_coalescing();
1928        self.select_all_cursors_to(|s, sel| s.next_end_of_word_at(sel.cursor_offset()), cx);
1929    }
1930
1931    /// Return the start offset of the previous word.
1932    /// Return the previous start offset of the word before `offset`.
1933    pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1934        if self.masked {
1935            // The mask replaces every character, so the displayed text has no
1936            // word boundaries to move or delete by. Collapse the word to the
1937            // whole text.
1938            return 0;
1939        }
1940
1941        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1942        // FIXME: Avoid to_string
1943        let left_part = self.text.slice(0..offset).to_string();
1944
1945        let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1946            .rfind(|(_, s)| !s.trim_start().is_empty())
1947            .map(|(i, _)| i)
1948            .unwrap_or(0);
1949        self.token_boundary(target, Bias::Left)
1950    }
1951
1952    /// Return the next end offset of the word after `offset`.
1953    pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1954        if self.masked {
1955            // See `previous_start_of_word_at`.
1956            return self.text.len();
1957        }
1958
1959        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1960        let right_part = self.text.slice(offset..self.text.len()).to_string();
1961
1962        let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1963            .find(|(_, s)| !s.trim_start().is_empty())
1964            .map(|(i, s)| offset + i + s.len())
1965            .unwrap_or(self.text.len());
1966        self.token_boundary(target, Bias::Right)
1967    }
1968
1969    /// Get start of line byte offset for the given `offset`.
1970    ///
1971    /// When soft wrap is active, first press goes to visual line start,
1972    /// second press (already at visual start) goes to logical line start.
1973    pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1974        if self.is_single_line() {
1975            return 0;
1976        }
1977
1978        let row = self.text.offset_to_point(offset).row;
1979        let logical_start = self.text.line_start_offset(row);
1980
1981        if self.soft_wrap && self.is_code_editor() {
1982            let wrap_point = self
1983                .display_map
1984                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1985            if let Some(line) = self.display_map.line(row)
1986                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1987            {
1988                let visual_start = logical_start + range.start;
1989                if offset != visual_start {
1990                    return visual_start;
1991                }
1992            }
1993        }
1994
1995        logical_start
1996    }
1997
1998    /// Get end of line byte offset for the given `offset`.
1999    ///
2000    /// When soft wrap is active, first press goes to visual line end,
2001    /// second press (already at visual end) goes to logical line end.
2002    pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2003        if self.is_single_line() {
2004            return self.text.len();
2005        }
2006
2007        let row = self.text.offset_to_point(offset).row;
2008        let logical_start = self.text.line_start_offset(row);
2009        let logical_end = self.text.line_end_offset(row);
2010
2011        if self.soft_wrap && self.is_code_editor() {
2012            // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
2013            // the next row, and a second End press would keep walking down instead of falling
2014            // through to the logical line end.
2015            let wrap_point = self
2016                .display_map
2017                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2018            if let Some(line) = self.display_map.line(row)
2019                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2020            {
2021                let visual_end = logical_start + range.end;
2022                if offset != visual_end {
2023                    return visual_end;
2024                }
2025            }
2026        }
2027
2028        logical_end
2029    }
2030
2031    /// Get indent string of next line.
2032    ///
2033    /// To get current and next line indent, to return more depth one.
2034    pub(super) fn indent_of_next_line(&mut self) -> String {
2035        self.indent_of_next_line_at(self.cursor())
2036    }
2037
2038    /// Get indent string of the next line, relative to the given `offset`.
2039    pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
2040        if self.is_single_line() {
2041            return "".into();
2042        }
2043
2044        let mut current_indent = String::new();
2045        let mut next_indent = String::new();
2046        let line_end_affinity = self.line_end_affinity_at(offset);
2047        let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
2048        let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
2049        for c in self.text.slice(current_line_start_pos..).chars() {
2050            if !c.is_whitespace() {
2051                break;
2052            }
2053            if c == '\n' || c == '\r' {
2054                break;
2055            }
2056            current_indent.push(c);
2057        }
2058
2059        for c in self.text.slice(next_line_start_pos..).chars() {
2060            if !c.is_whitespace() {
2061                break;
2062            }
2063            if c == '\n' || c == '\r' {
2064                break;
2065            }
2066            next_indent.push(c);
2067        }
2068
2069        if next_indent.len() > current_indent.len() {
2070            return next_indent;
2071        }
2072
2073        // Smart indent: one extra level after lines ending with a trigger.
2074        // Skipped inside strings and comments: the trigger is literal text.
2075        if let Some(rules) = self.mode.language_config() {
2076            if self.mode.is_smart_indent()
2077                && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
2078            {
2079                let line_before: String = self
2080                    .text
2081                    .slice(current_line_start_pos..offset)
2082                    .chars()
2083                    .collect();
2084                if rules.opens_indent(line_before.trim_end()) {
2085                    let tab = self.mode.tab_size();
2086                    if tab.hard_tabs {
2087                        current_indent.push('\t');
2088                    } else {
2089                        for _ in 0..tab.tab_size {
2090                            current_indent.push(' ');
2091                        }
2092                    }
2093                } else {
2094                    let line_after = self.text.slice(offset..next_line_start_pos).to_string();
2095                    if rules.closes_indent(&line_after) {
2096                        let tab = self.mode.tab_size();
2097                        if current_indent.ends_with('\t') {
2098                            current_indent.pop();
2099                        } else {
2100                            for _ in 0..tab.tab_size {
2101                                if !current_indent.ends_with(' ') {
2102                                    break;
2103                                }
2104                                current_indent.pop();
2105                            }
2106                        }
2107                    }
2108                }
2109            }
2110        }
2111
2112        current_indent
2113    }
2114
2115    /// Delete every selection as one batch. Collapsed cursors are first
2116    /// expanded to a deletion range by `collapsed_target` and non-empty
2117    /// selections delete their own range.
2118    ///
2119    /// `collapsed_intent` is the intent to record when every cursor is
2120    /// collapsed, which is what makes a run of single-character deletes undo
2121    /// as one gesture. Deleting a real selection is always atomic.
2122    fn delete_selections(
2123        &mut self,
2124        silent: bool,
2125        collapsed_intent: EditIntent,
2126        mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
2127        window: &mut Window,
2128        cx: &mut Context<Self>,
2129    ) {
2130        if !self.is_editable() {
2131            return;
2132        }
2133        let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
2134        let intent = if cursors.iter().all(|sel| sel.is_empty()) {
2135            collapsed_intent
2136        } else {
2137            EditIntent::Atomic
2138        };
2139        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
2140        for sel in &cursors {
2141            let range = if sel.is_empty() {
2142                collapsed_target(self, sel.cursor_offset())
2143            } else {
2144                sel.start..sel.end
2145            };
2146            let (start, end) = (range.start.min(range.end), range.start.max(range.end));
2147            let mut selection = *sel;
2148            selection.start = start;
2149            selection.end = end;
2150            new_selections.push(selection);
2151        }
2152        // Capture the user's selections before expanding or merging deletion
2153        // ranges. The edit ranges cannot reconstruct their original carets.
2154        self.undo_manager.begin_transaction_with(intent);
2155        self.undo_manager
2156            .record_selections(cursors.clone(), cursors.clone());
2157        self.selections.replace_all(new_selections);
2158        self.undo_manager.set_pending_intent(intent);
2159
2160        let was_silent = self.silent_replace_text;
2161        self.silent_replace_text = silent;
2162        self.replace_text_in_range(None, "", window, cx);
2163        self.silent_replace_text = was_silent;
2164        self.undo_manager
2165            .record_selections(cursors, self.selections.iter().copied().collect());
2166        self.undo_manager.commit_transaction();
2167        self.pause_blink_cursor(cx);
2168    }
2169
2170    /// Decide pairing against the pre-edit text, before an opening quote can
2171    /// change its own syntax context. Ordinary characters never query syntax.
2172    fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
2173        if self.silent_replace_text
2174            || self.ime_marked_range.is_some()
2175            || !self.selections.is_single()
2176            || !self.active_selection().is_empty()
2177            || !range.is_empty()
2178            || range.start != self.cursor()
2179            || text.chars().count() != 1
2180            || !self.mode.is_auto_close()
2181        {
2182            return None;
2183        }
2184        let rules = self.mode.language_config()?;
2185        if self
2186            .text
2187            .chars_at(range.start)
2188            .next()
2189            .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
2190        {
2191            return None;
2192        }
2193        for (open, close, not_in) in rules.closing_pairs() {
2194            let Some(prefix) = open.strip_suffix(text) else {
2195                continue;
2196            };
2197            if !self.text_before_matches(range.start, prefix) {
2198                continue;
2199            }
2200            let start = range.start - prefix.len();
2201            if open == close
2202                && (self.is_escaped_at(start)
2203                    || self
2204                        .text
2205                        .chars_at(start)
2206                        .reversed()
2207                        .next()
2208                        .is_some_and(|c| c.is_alphanumeric() || c == '_'))
2209            {
2210                continue;
2211            }
2212            if not_in.contains(&M::editing_syntax_context(self, start)) {
2213                continue;
2214            }
2215            return Some((open.len(), close.into()));
2216        }
2217        None
2218    }
2219
2220    fn text_before_matches(&self, offset: usize, text: &str) -> bool {
2221        offset >= text.len()
2222            && self.text.is_char_boundary(offset - text.len())
2223            && self.text.slice(offset - text.len()..offset) == text
2224    }
2225
2226    fn text_after_matches(&self, offset: usize, text: &str) -> bool {
2227        offset + text.len() <= self.text.len()
2228            && self.text.is_char_boundary(offset + text.len())
2229            && self.text.slice(offset..offset + text.len()) == text
2230    }
2231
2232    fn is_escaped_at(&self, offset: usize) -> bool {
2233        self.text
2234            .chars_at(offset)
2235            .reversed()
2236            .take_while(|c| *c == '\\')
2237            .count()
2238            % 2
2239            == 1
2240    }
2241
2242    /// Cursor target when a typed closer should skip over an existing one.
2243    ///
2244    /// Returns `Some(offset)` when `new_text` is a single closer from the
2245    /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
2246    /// not escaped. The caller then moves the cursor without editing text or
2247    /// history. `None` means insert normally.
2248    fn skip_over_target(&self, new_text: &str) -> Option<usize> {
2249        if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
2250            return None;
2251        }
2252        let rules = self.mode.language_config()?;
2253        let cursor = self.cursor();
2254        for (open, close, not_in) in rules.closing_pairs() {
2255            for (index, _) in close.char_indices() {
2256                if !close[index..].starts_with(new_text)
2257                    || !self.text_before_matches(cursor, &close[..index])
2258                    || !self.text_after_matches(cursor, &close[index..])
2259                {
2260                    continue;
2261                }
2262                let context = M::editing_syntax_context(self, cursor);
2263                let generated =
2264                    self.mode
2265                        .auto_closed_pairs()
2266                        .contains_closer(cursor, index, close.len());
2267                if !generated
2268                    && not_in.contains(&context)
2269                    && !(context == crate::input::SyntaxContext::String && open == close)
2270                {
2271                    continue;
2272                }
2273                if self.is_escaped_at(cursor - index) {
2274                    continue;
2275                }
2276                return Some(cursor + new_text.len());
2277            }
2278        }
2279        None
2280    }
2281
2282    pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
2283        // Nothing to delete at the start of the text. Propagate so an ancestor
2284        // (e.g. a command palette navigating back a level) can act on it.
2285        // This is harmless when nothing upstream is bound to backspace. With multiple
2286        // cursors the others can still delete, so only the lone-cursor case
2287        // propagates.
2288        if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
2289            cx.propagate();
2290            return;
2291        }
2292
2293        // Pair deletion follows automatic closing rules, independently of
2294        // structural brackets used by Enter.
2295        if self.mode.is_auto_close()
2296            && self.selections.is_single()
2297            && self.active_selection().is_empty()
2298        {
2299            let off = self.cursor();
2300            let deletion = self.mode.language_config().and_then(|rules| {
2301                rules.closing_pairs().find_map(|(open, close, not_in)| {
2302                    if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
2303                    {
2304                        return None;
2305                    }
2306                    let start = off - open.len();
2307                    let generated = self
2308                        .mode
2309                        .auto_closed_pairs()
2310                        .contains(start..off, off..off + close.len());
2311                    if self.is_escaped_at(start)
2312                        || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
2313                    {
2314                        return None;
2315                    }
2316                    Some(start..off + close.len())
2317                })
2318            });
2319            if let Some(range) = deletion {
2320                let utf16 = self.range_to_utf16(&range);
2321                self.replace_text_in_range_silent(Some(utf16), "", window, cx);
2322                return;
2323            }
2324        }
2325
2326        self.delete_selections(
2327            false,
2328            EditIntent::Backspace,
2329            |s, offset| s.previous_boundary(offset)..offset,
2330            window,
2331            cx,
2332        );
2333    }
2334
2335    pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2336        self.delete_selections(
2337            false,
2338            EditIntent::DeleteForward,
2339            |s, offset| offset..s.next_boundary(offset),
2340            window,
2341            cx,
2342        );
2343    }
2344
2345    pub(super) fn delete_to_beginning_of_line(
2346        &mut self,
2347        _: &DeleteToBeginningOfLine,
2348        window: &mut Window,
2349        cx: &mut Context<Self>,
2350    ) {
2351        self.delete_selections(
2352            true,
2353            EditIntent::Atomic,
2354            |s, offset| {
2355                let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
2356                if start == offset {
2357                    start = start.saturating_sub(1);
2358                }
2359                start..offset
2360            },
2361            window,
2362            cx,
2363        );
2364    }
2365
2366    pub(super) fn delete_to_end_of_line(
2367        &mut self,
2368        _: &DeleteToEndOfLine,
2369        window: &mut Window,
2370        cx: &mut Context<Self>,
2371    ) {
2372        self.delete_selections(
2373            true,
2374            EditIntent::Atomic,
2375            |s, offset| {
2376                let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
2377                if end == offset {
2378                    end = (end + 1).clamp(0, s.text.len());
2379                }
2380                offset..end
2381            },
2382            window,
2383            cx,
2384        );
2385    }
2386
2387    pub(super) fn delete_previous_word(
2388        &mut self,
2389        _: &DeleteToPreviousWordStart,
2390        window: &mut Window,
2391        cx: &mut Context<Self>,
2392    ) {
2393        self.delete_selections(
2394            true,
2395            EditIntent::Atomic,
2396            |s, offset| s.previous_start_of_word_at(offset)..offset,
2397            window,
2398            cx,
2399        );
2400    }
2401
2402    pub(super) fn delete_next_word(
2403        &mut self,
2404        _: &DeleteToNextWordEnd,
2405        window: &mut Window,
2406        cx: &mut Context<Self>,
2407    ) {
2408        self.delete_selections(
2409            true,
2410            EditIntent::Atomic,
2411            |s, offset| offset..s.next_word_delete_end_at(offset, !cfg!(target_os = "macos")),
2412            window,
2413            cx,
2414        );
2415    }
2416
2417    /// Return where a forward word delete starting at `offset` stops.
2418    ///
2419    /// With `stop_at_whitespace` (Windows and Linux `Ctrl+Delete`, as in
2420    /// Notepad and VS Code), a line break or a run of blanks is deleted on its
2421    /// own instead of together with the word after it. macOS `Option+Delete`
2422    /// deletes through to the end of the next word.
2423    pub(super) fn next_word_delete_end_at(&self, offset: usize, stop_at_whitespace: bool) -> usize {
2424        if stop_at_whitespace && !self.masked {
2425            let mut chars = self.text.slice(offset..self.text.len()).chars();
2426            match chars.next() {
2427                Some('\r') => {
2428                    let next = if chars.next() == Some('\n') { 2 } else { 1 };
2429                    return offset + next;
2430                }
2431                Some('\n') => return offset + 1,
2432                Some(c) if c.is_whitespace() => {
2433                    let mut end = offset + c.len_utf8();
2434                    for c in chars {
2435                        if c == '\n' || c == '\r' || !c.is_whitespace() {
2436                            break;
2437                        }
2438                        end += c.len_utf8();
2439                    }
2440                    return end;
2441                }
2442                _ => {}
2443            }
2444        }
2445        self.next_end_of_word_at(offset)
2446    }
2447
2448    pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
2449        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2450            return;
2451        }
2452
2453        // Clear inline completion on enter (user chose not to accept it)
2454        if M::has_inline_completion(self) {
2455            M::clear_inline_completion(self, cx);
2456        }
2457
2458        // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
2459        // (without Shift) is treated as submit: propagate the action and emit
2460        // PressEnter without inserting a newline. `Shift+Enter` still inserts
2461        // a newline. A secondary `Enter` (Cmd/Ctrl+Enter) is always a submit
2462        // gesture and never inserts a newline.
2463        let insert_newline =
2464            self.is_multi_line() && !action.secondary && (!self.submit_on_enter || action.shift);
2465
2466        if insert_newline {
2467            if !self.selections.is_single() {
2468                // Insert a newline (with per-line indent) at every cursor.
2469                self.selections.merge_overlapping();
2470                let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2471                let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
2472                for sel in &selections {
2473                    let indent = if self.is_code_editor() {
2474                        self.indent_of_next_line_at(sel.cursor_offset())
2475                    } else {
2476                        String::new()
2477                    };
2478                    edits.push((sel.start..sel.end, format!("\n{}", indent)));
2479                }
2480                edits.sort_by_key(|(range, _)| range.start);
2481                self.replace_text_in_ranges(&edits, window, cx);
2482                self.pause_blink_cursor(cx);
2483            } else {
2484                // Bracket split: Enter between `{|}` produces `{\n  \n}`
2485                // with the cursor on the middle line. Controlled by smart_indent,
2486                // independently of automatic closing.
2487                // Skipped inside strings and comments: splitting there would
2488                // restructure literal text.
2489                let mut split = false;
2490                if self.is_code_editor() && self.active_selection().is_empty() {
2491                    if let Some(rules) = self.mode.language_config() {
2492                        if self.mode.is_smart_indent()
2493                            && M::editing_syntax_context(self, self.cursor())
2494                                == crate::input::SyntaxContext::Code
2495                        {
2496                            let off = self.cursor();
2497                            let is_pair = rules.brackets.iter().any(|p| {
2498                                !p.open.is_empty()
2499                                    && !p.close.is_empty()
2500                                    && p.open != p.close
2501                                    && self.text_before_matches(off, p.open.as_ref())
2502                                    && self.text_after_matches(off, p.close.as_ref())
2503                            });
2504                            if is_pair {
2505                                // Base indent: leading whitespace only.
2506                                let line_end_affinity = self.line_end_affinity_at(off);
2507                                let line_start = self.start_of_line_at(off, line_end_affinity);
2508                                let mut indent = String::new();
2509                                for c in self.text.slice(line_start..).chars() {
2510                                    if !c.is_whitespace() || c == '\n' || c == '\r' {
2511                                        break;
2512                                    }
2513                                    indent.push(c);
2514                                }
2515                                // Extra level only with smart indent enabled.
2516                                let mut inner = indent.clone();
2517                                if self.mode.is_smart_indent() {
2518                                    let tab = self.mode.tab_size();
2519                                    if tab.hard_tabs {
2520                                        inner.push('\t');
2521                                    } else {
2522                                        for _ in 0..tab.tab_size {
2523                                            inner.push(' ');
2524                                        }
2525                                    }
2526                                }
2527                                let new_line_text = format!("\n{inner}\n{indent}");
2528                                self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2529                                self.set_cursor_to(off + 1 + inner.len());
2530                                self.update_preferred_column();
2531                                let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2532                                self.undo_manager
2533                                    .record_selections(cursors.clone(), cursors);
2534                                self.pause_blink_cursor(cx);
2535                                split = true;
2536                            }
2537                        }
2538                    }
2539                }
2540                if !split {
2541                    // Get current line indent
2542                    let indent = if self.is_code_editor() {
2543                        self.indent_of_next_line()
2544                    } else {
2545                        "".to_string()
2546                    };
2547
2548                    // Add newline and indent
2549                    let new_line_text = format!("\n{}", indent);
2550                    self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2551                    self.pause_blink_cursor(cx);
2552                }
2553            }
2554        } else {
2555            // Single line input or submit-on-enter: just emit the event
2556            // (e.g.: in a dialog to confirm, or a chat textarea to send).
2557            self.undo_manager.break_transaction_coalescing();
2558            cx.propagate();
2559        }
2560
2561        cx.emit(InputEvent::PressEnter {
2562            secondary: action.secondary,
2563            shift: action.shift,
2564        });
2565    }
2566
2567    pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2568        self.replace_text("", window, cx);
2569        self.set_selection(0, 0);
2570        self.scroll_to(0, None, cx);
2571    }
2572
2573    pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2574        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2575            return;
2576        }
2577
2578        // Escape also dismisses a request whose popup has not arrived yet.
2579        M::hide_context_menu(self, cx);
2580
2581        // Collapse extra cursors back to the active one first.
2582        if !self.selections.is_single() {
2583            self.undo_manager.break_transaction_coalescing();
2584            self.selections.remove_all_but_active();
2585            cx.notify();
2586            return;
2587        }
2588
2589        // Clear inline completion on escape
2590        if M::has_inline_completion(self) {
2591            M::clear_inline_completion(self, cx);
2592            return; // Consume the escape, don't propagate
2593        }
2594        M::clear_inline_completion(self, cx);
2595
2596        // The handles and the edit menu are the topmost surface to dismiss.
2597        if self.touch_selection().is_some() {
2598            self.dismiss_touch_selection(cx);
2599            return;
2600        }
2601
2602        if self.ime_marked_range.is_some() {
2603            self.unmark_text(window, cx);
2604        }
2605
2606        // Android delivers its back button as escape, and back leaves a field's
2607        // text alone: it closes what is open or navigates.
2608        if self.clean_on_escape && !cfg!(target_os = "android") {
2609            return self.clean(window, cx);
2610        }
2611
2612        cx.propagate();
2613    }
2614
2615    /// Show the right-click context menu as a native OS menu.
2616    pub(crate) fn handle_right_click_menu(
2617        &mut self,
2618        position: Point<Pixels>,
2619        offset: usize,
2620        window: &mut Window,
2621        cx: &mut Context<Self>,
2622    ) {
2623        if self.disabled {
2624            return;
2625        }
2626        if crate::GlobalState::is_in_deferred_context(cx) {
2627            return;
2628        }
2629
2630        self.context_menu_offset = Some(offset);
2631        if !self.active_selection().contains(offset) {
2632            self.move_to(offset, None, cx);
2633        }
2634
2635        if self.is_code_editor() {
2636            M::on_hover_definition(self, offset, window, cx);
2637        }
2638
2639        if let Some(handler) = self.context_menu_handler.clone() {
2640            let capabilities = self.context_menu_capabilities();
2641            let input = cx.weak_entity();
2642            // The handler runs with the input released, so a custom builder can
2643            // read it (cursor, selection, text) to build its items.
2644            window.defer(cx, move |window, cx| {
2645                if input.upgrade().is_none() {
2646                    return;
2647                }
2648                let previous_focus = window.focused(cx);
2649                handler(NativeMenu::new(), capabilities, position, window, cx);
2650                // A drawn menu takes focus synchronously; native menus leave it
2651                // on the input. Capture it here rather than in the handler.
2652                input
2653                    .update(cx, |this, cx| {
2654                        if window.focused(cx) == previous_focus
2655                            && !this.focus_handle.is_focused(window)
2656                            && this.has_selection_focus(window, cx)
2657                        {
2658                            // A custom handler can reuse an already-focused popup.
2659                            return;
2660                        }
2661                        let menu_focus = window.focused(cx).filter(|focus| {
2662                            Some(focus) != previous_focus.as_ref() && *focus != this.focus_handle
2663                        });
2664                        this.set_selection_focus(menu_focus, cx);
2665                    })
2666                    .ok();
2667            });
2668        }
2669    }
2670
2671    pub(super) fn add_cursor_above(
2672        &mut self,
2673        _: &AddCursorAbove,
2674        _: &mut Window,
2675        cx: &mut Context<Self>,
2676    ) {
2677        self.add_cursor_vertical(-1, cx);
2678    }
2679
2680    pub(super) fn add_cursor_below(
2681        &mut self,
2682        _: &AddCursorBelow,
2683        _: &mut Window,
2684        cx: &mut Context<Self>,
2685    ) {
2686        self.add_cursor_vertical(1, cx);
2687    }
2688
2689    /// Add a new cursor one display line above (`move_lines < 0`) or below each
2690    /// existing cursor, preserving the column. Cursors that would not move (at
2691    /// the first/last display row) or that would duplicate an existing cursor
2692    /// are skipped.
2693    fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2694        if !self.is_multi_line() {
2695            return;
2696        }
2697
2698        self.pause_blink_cursor(cx);
2699        // Changing the cursor set ends the editing gesture that came before it.
2700        self.undo_manager.break_transaction_coalescing();
2701
2702        let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2703            .selections
2704            .iter()
2705            .map(|sel| {
2706                (
2707                    sel.cursor_offset(),
2708                    sel.column_anchor,
2709                    self.line_end_affinity_for(sel),
2710                )
2711            })
2712            .collect();
2713        let mut offsets: std::collections::HashSet<usize> =
2714            sources.iter().map(|(offset, _, _)| *offset).collect();
2715
2716        let mut newest: Option<usize> = None;
2717        for (offset, anchor, line_end_affinity) in sources {
2718            let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2719            let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2720            if target == offset || offsets.contains(&target) {
2721                continue;
2722            }
2723            offsets.insert(target);
2724            let id = self.selections.generate_id();
2725            let mut cursor = CursorSelection::new(id, target, target);
2726            cursor.column_anchor = anchor;
2727            self.selections.add(cursor);
2728            newest = Some(target);
2729        }
2730
2731        if let Some(newest) = newest {
2732            self.scroll_to(newest, None, cx);
2733        }
2734        cx.notify();
2735    }
2736
2737    /// Add an additional collapsed cursor at `offset`.
2738    ///
2739    /// Rejected when `offset` lands inside an existing selection or exactly on
2740    /// an existing cursor.
2741    pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2742        if !self.is_multi_line() {
2743            return;
2744        }
2745
2746        for sel in self.selections.iter() {
2747            if sel.contains(offset) {
2748                return;
2749            }
2750            if sel.is_collapsed() && sel.cursor_offset() == offset {
2751                return;
2752            }
2753        }
2754
2755        self.undo_manager.break_transaction_coalescing();
2756        let id = self.selections.generate_id();
2757        let mut selection = CursorSelection::new(id, offset, offset);
2758        selection.column_anchor = self.preferred_column_for(offset);
2759        self.selections.add(selection);
2760        cx.notify();
2761    }
2762
2763    /// Build a columnar (block) selection spanning the rows between the two
2764    /// points, one selection per display row at the same column span.
2765    ///
2766    /// The span keeps the columns the pointer sat past the end of a short row, so a row
2767    /// that runs out of text does not narrow the block for the rows that do reach that
2768    /// far. Each row is then clipped to its own end, selecting as much of the span as it
2769    /// actually has.
2770    pub(super) fn build_columnar_selection(
2771        &mut self,
2772        start: ColumnarPoint,
2773        end: ColumnarPoint,
2774        cx: &mut Context<Self>,
2775    ) {
2776        if !self.is_multi_line() {
2777            return;
2778        }
2779
2780        self.undo_manager.break_transaction_coalescing();
2781
2782        let (start_row, start_col) = self.columnar_row_column(start);
2783        let (end_row, end_col) = self.columnar_row_column(end);
2784        let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2785        let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2786
2787        let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2788        for row in start_row..=end_row {
2789            let sel_start = self
2790                .display_map
2791                .display_row_column_to_offset(row, start_col);
2792            let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2793            let id = self.selections.generate_id();
2794            let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2795            let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2796            new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2797        }
2798
2799        self.selections.replace_all(new_selections);
2800        cx.notify();
2801    }
2802
2803    /// Resolve a columnar point to the display row it is on and the column it reaches,
2804    /// counting the columns beyond the row's end so a short row keeps the full span.
2805    fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2806        let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2807        let row = self
2808            .display_map
2809            .wrap_row_to_display_row(display_point.row)
2810            .unwrap_or_else(|| {
2811                self.display_map
2812                    .nearest_visible_display_row(display_point.row)
2813            });
2814
2815        (row, display_point.column + point.columns_past_line_end)
2816    }
2817
2818    pub(super) fn on_mouse_down(
2819        &mut self,
2820        event: &MouseDownEvent,
2821        window: &mut Window,
2822        cx: &mut Context<Self>,
2823    ) {
2824        // A token that consumed the press (a double click selecting it) must
2825        // not also place the caret.
2826        if window.default_prevented() {
2827            return;
2828        }
2829        // A tap asks for the virtual keyboard. Focus alone does not when it
2830        // moves from another input, or stays here, after the user hid it.
2831        if event.button == MouseButton::Left
2832            && crate::GlobalState::is_touch_press(cx)
2833            && !self.disabled
2834            && !self.readonly
2835        {
2836            window.request_virtual_keyboard();
2837        }
2838        self.undo_manager.break_transaction_coalescing();
2839        // Treat every press like a cursor move: take focus now rather than
2840        // after GPUI's focus observer runs, show the caret at once and restart
2841        // the idle delay, whatever phase the blink was in.
2842        if !self.disabled {
2843            self.focus(window, cx);
2844            self.pause_blink_cursor(cx);
2845        }
2846        // Clear inline completion on any mouse interaction
2847        M::clear_inline_completion(self, cx);
2848        // A tap on the touch selection asks for its menu back. Any other press
2849        // places the caret or starts a new drag, and the handles and the menu
2850        // no longer belong to what is selected.
2851        if event.button == MouseButton::Left
2852            && event.click_count == 1
2853            && self.reopen_edit_menu_at(event.position, cx)
2854        {
2855            return;
2856        }
2857        self.dismiss_touch_selection(cx);
2858
2859        // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2860        // Clear the marked range.
2861        if let Some(ime_marked_range) = &self.ime_marked_range {
2862            if ime_marked_range.len() == 0 {
2863                self.ime_marked_range = None;
2864            }
2865        }
2866
2867        self.selecting = true;
2868        let (offset, line_end_affinity, columns_past_line_end) =
2869            self.resolve_mouse_position(event.position);
2870
2871        if M::on_click(self, event, offset, window, cx) {
2872            return;
2873        }
2874
2875        // Triple click to select line
2876        if event.button == MouseButton::Left && event.click_count >= 3 {
2877            self.select_line(offset, window, cx);
2878            return;
2879        }
2880
2881        // Double click to select word
2882        if event.button == MouseButton::Left && event.click_count == 2 {
2883            self.select_word(offset, window, cx);
2884            // A double tap is touch's other way to select a word, and it
2885            // gets the handles and the menu like a long press does.
2886            if crate::GlobalState::is_touch_press(cx) {
2887                self.keep_touch_selection(cx);
2888            }
2889            return;
2890        }
2891
2892        // Show Mouse context menu
2893        if event.button == MouseButton::Right {
2894            if self.enable_context_menu {
2895                if !self.active_selection().contains(offset) {
2896                    self.move_to(offset, None, cx);
2897                }
2898                self.pending_context_menu = Some((event.position, offset));
2899            }
2900            return;
2901        }
2902
2903        // Multi-cursor placement, multi-line only.
2904        if self.is_multi_line() && event.button == MouseButton::Left {
2905            if event.modifiers.alt
2906                && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2907            {
2908                // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2909                // Mark selecting so the drag handler extends the block.
2910                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2911                self.selecting = true;
2912                self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2913                return;
2914            } else if event.modifiers.alt {
2915                self.add_cursor_at(offset, cx);
2916                // Keep click-to-add behavior, but use this press as the block
2917                // anchor if the user continues dragging with the left button.
2918                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2919                return;
2920            }
2921        }
2922
2923        if event.modifiers.shift {
2924            self.select_to_with_affinity(offset, line_end_affinity, cx);
2925        } else {
2926            self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2927        }
2928    }
2929
2930    pub(super) fn on_mouse_up(
2931        &mut self,
2932        event: &MouseUpEvent,
2933        window: &mut Window,
2934        cx: &mut Context<Self>,
2935    ) {
2936        if event.button == MouseButton::Right {
2937            if let Some((position, offset)) = self.pending_context_menu.take() {
2938                self.handle_right_click_menu(position, offset, window, cx);
2939            }
2940        }
2941        if self.active_selection().is_empty() {
2942            self.active_selection_mut().reversed = false;
2943        }
2944        self.selecting = false;
2945        self.selected_word_range = None;
2946        self.column_select_start = None;
2947        self.auto_scroll.stop();
2948    }
2949
2950    pub(super) fn on_mouse_move(
2951        &mut self,
2952        event: &MouseMoveEvent,
2953        window: &mut Window,
2954        cx: &mut Context<Self>,
2955    ) {
2956        // `last_bounds` is moved by the scroll offset; `input_bounds` is the visible area.
2957        let within_bounds = self.input_bounds.contains(&event.position);
2958
2959        if !within_bounds {
2960            // Clear hover when mouse leaves the input
2961            M::clear_hover_state(self, cx);
2962            return;
2963        }
2964
2965        // Show diagnostic popover on mouse move
2966        let (offset, _) = self.index_for_mouse_position(event.position);
2967        M::on_mouse_move(self, offset, event, window, cx);
2968
2969        if self.is_code_editor() {
2970            // Keep the current popover while the pointer stays on the same
2971            // diagnostic, so moving over a squiggle neither repaints nor
2972            // rebuilds the popover.
2973            match self
2974                .mode
2975                .diagnostics()
2976                .and_then(|set| set.for_offset(offset))
2977            {
2978                Some(diagnostic) => {
2979                    if self.diagnostic_popover.as_deref() != Some(diagnostic) {
2980                        self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
2981                        cx.notify();
2982                    }
2983                }
2984                None => {
2985                    if self.diagnostic_popover.take().is_some() {
2986                        cx.notify();
2987                    }
2988                }
2989            }
2990        }
2991    }
2992
2993    pub(super) fn on_scroll_wheel(
2994        &mut self,
2995        event: &ScrollEvent,
2996        window: &mut Window,
2997        cx: &mut Context<Self>,
2998    ) {
2999        let line_height = self
3000            .last_layout
3001            .as_ref()
3002            .map(|layout| layout.line_height)
3003            .unwrap_or(window.line_height());
3004        let delta = event.delta.pixel_delta(line_height);
3005
3006        let old_offset = self.scroll_handle.offset();
3007        let precise = matches!(event.delta, gpui::ScrollDelta::Pixels(_));
3008        if !precise || !self.scroll_bounce || cx.reduce_motion() || !self.overflows_vertically() {
3009            let displaced = self.overscroll.offset() != 0.;
3010            self.overscroll.reset();
3011            if displaced {
3012                cx.notify();
3013            }
3014        }
3015        let bounces = self.scroll_bounce
3016            && precise
3017            && !cx.reduce_motion()
3018            && delta.y.abs() >= delta.x.abs()
3019            && self.overflows_vertically();
3020        if bounces {
3021            let mut overscroll = std::mem::take(&mut self.overscroll);
3022            let stretched = overscroll.packet(
3023                delta.y.as_f32(),
3024                event.touch_phase,
3025                self.input_bounds.size.height.as_f32(),
3026                cx.background_executor().now(),
3027                |dy| {
3028                    let before = self.scroll_handle.offset();
3029                    self.update_scroll_offset(
3030                        Some(point(before.x + delta.x, before.y + px(dy))),
3031                        cx,
3032                    );
3033                    (self.scroll_handle.offset().y - before.y).as_f32()
3034                },
3035            );
3036            self.overscroll = overscroll;
3037            if stretched {
3038                cx.notify();
3039            }
3040        } else {
3041            self.overscroll
3042                .touch_phase(event.touch_phase, cx.background_executor().now());
3043            // Axis drift must not drop the end of a vertical drag.
3044            if matches!(
3045                event.touch_phase,
3046                gpui::TouchPhase::Ended | gpui::TouchPhase::Cancelled
3047            ) && self.overscroll.offset() != 0.
3048            {
3049                self.overscroll.packet(
3050                    0.,
3051                    event.touch_phase,
3052                    self.input_bounds.size.height.as_f32(),
3053                    cx.background_executor().now(),
3054                    |_| 0.,
3055                );
3056                cx.notify();
3057            }
3058            self.update_scroll_offset(Some(old_offset + delta), cx);
3059        }
3060
3061        // Text that has room to scroll keeps a scroll over it even where the
3062        // text ends, so reaching the end does not scroll the region around the
3063        // input; text that fits leaves the scroll to that region.
3064        if self.scroll_handle.offset() != old_offset || self.overflows_along(delta) {
3065            cx.stop_propagation();
3066        }
3067
3068        if self.diagnostic_popover.take().is_some() {
3069            cx.notify();
3070        }
3071        // The handles follow the text; the menu would sit over whatever
3072        // scrolls underneath it, so it steps aside until the finger lifts.
3073        self.edit_menu_on_scroll(event.touch_phase, cx);
3074    }
3075
3076    /// Whether the text takes a wheel event moving by `delta` from the
3077    /// scroll areas around it: it has room to scroll along the axis the
3078    /// event mostly moves on. Unlike [`Self::overflows_along`], an event that
3079    /// moves on neither axis, such as a gesture's start or end, goes to text
3080    /// that can scroll vertically.
3081    pub(super) fn takes_scroll(&self, delta: Point<Pixels>) -> bool {
3082        if delta.y.abs() >= delta.x.abs() {
3083            self.overflows_vertically()
3084        } else {
3085            self.scroll_size.width > self.input_bounds.size.width
3086        }
3087    }
3088
3089    /// Whether the text has room to scroll along the axis `delta` mostly
3090    /// moves on. A trackpad swipe drifts a little off its axis, so the drift
3091    /// alone does not claim the scroll.
3092    fn overflows_along(&self, delta: Point<Pixels>) -> bool {
3093        if delta.y.abs() >= delta.x.abs() {
3094            delta.y != px(0.) && self.overflows_vertically()
3095        } else {
3096            self.scroll_size.width > self.input_bounds.size.width
3097        }
3098    }
3099
3100    /// Whether multi-line text is taller than the input.
3101    fn overflows_vertically(&self) -> bool {
3102        self.is_multi_line() && self.scroll_size.height > self.input_bounds.size.height
3103    }
3104
3105    pub(super) fn update_scroll_offset(
3106        &mut self,
3107        offset: Option<Point<Pixels>>,
3108        cx: &mut Context<Self>,
3109    ) {
3110        let mut offset = offset.unwrap_or(self.scroll_handle.offset());
3111        let safe_y_range =
3112            (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.);
3113
3114        offset.y = if self.is_single_line() {
3115            px(0.)
3116        } else {
3117            offset.y.clamp(safe_y_range.start, safe_y_range.end)
3118        };
3119        offset.x = clamp_horizontal_scroll_offset(
3120            offset.x,
3121            self.scroll_size.width,
3122            self.input_bounds.size.width,
3123            self.text_align,
3124        );
3125        if self.scroll_handle.offset() != offset {
3126            self.scroll_handle.set_offset(offset);
3127            cx.notify();
3128        }
3129    }
3130
3131    /// Scroll to make the given offset visible.
3132    ///
3133    /// If `direction` is Some, will keep edges at the same side.
3134    pub(crate) fn scroll_to(
3135        &mut self,
3136        offset: usize,
3137        direction: Option<MoveDirection>,
3138        cx: &mut Context<Self>,
3139    ) {
3140        let padding = if direction.is_some() {
3141            ScrollPadding::SurroundingLines
3142        } else {
3143            ScrollPadding::Minimal
3144        };
3145        self.scroll_to_with_padding(offset, direction, padding, cx);
3146    }
3147
3148    /// Reveal an offset with independently chosen direction restriction and padding.
3149    /// Search uses surrounding lines without restricting movement to match order.
3150    pub(crate) fn scroll_to_with_padding(
3151        &mut self,
3152        offset: usize,
3153        direction: Option<MoveDirection>,
3154        padding: ScrollPadding,
3155        cx: &mut Context<Self>,
3156    ) {
3157        let Some(last_layout) = self.last_layout.as_ref() else {
3158            return;
3159        };
3160        let Some(bounds) = self.last_bounds.as_ref() else {
3161            return;
3162        };
3163
3164        let mut scroll_offset = self.scroll_handle.offset();
3165        let was_offset = scroll_offset;
3166        let line_height = last_layout.line_height;
3167
3168        let point = self.text.offset_to_point(offset);
3169
3170        let row = point.row;
3171
3172        // Resolve the wrapped row even when the target is outside the last layout.
3173        let display_row = self
3174            .display_map
3175            .offset_to_display_row(offset, self.line_end_affinity_at(offset));
3176        let row_offset_y = line_height * display_row;
3177
3178        // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
3179        // in layout_cursors, so shifting the text here would cause a first-click visual jump.
3180        let safety_margin = match last_layout.text_align {
3181            TextAlign::Left => RIGHT_MARGIN,
3182            TextAlign::Right => px(0.),
3183            TextAlign::Center => CURSOR_WIDTH,
3184        };
3185        if let Some(vi) = last_layout
3186            .visible_buffer_lines
3187            .iter()
3188            .position(|&line| line == row)
3189        {
3190            let line = &last_layout.lines[vi];
3191            let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
3192            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
3193                let bounds_width = bounds.size.width - last_layout.line_number_width;
3194                let col_offset_x = pos.x;
3195                if col_offset_x - safety_margin < -scroll_offset.x {
3196                    // If the position is out of the visible area, scroll to make it visible
3197                    scroll_offset.x = -col_offset_x + safety_margin;
3198                } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
3199                    scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
3200                }
3201            }
3202        }
3203
3204        // Scroll the row into view. Use the same edge clearance helper as
3205        // `TextElement::layout_cursors` so both scroll-into-view paths agree
3206        // (a mismatch flickered on `Down` at end-of-buffer with a small
3207        // `cursor_surrounding_lines` override).
3208        let edge_height =
3209            if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
3210                super::element::cursor_surrounding_padding(
3211                    self.mode.is_auto_grow(),
3212                    self.cursor_surrounding_lines,
3213                    super::element::viewport_visible_lines(bounds.size.height, line_height),
3214                    line_height,
3215                )
3216            } else {
3217                px(0.)
3218            };
3219        scroll_offset.y = super::element::reveal_row(
3220            scroll_offset.y,
3221            row_offset_y,
3222            line_height,
3223            bounds.size.height,
3224            edge_height,
3225        );
3226
3227        // Avoid necessary scroll, when it was already in the correct position.
3228        if direction == Some(MoveDirection::Up) {
3229            scroll_offset.y = scroll_offset.y.max(was_offset.y);
3230        } else if direction == Some(MoveDirection::Down) {
3231            scroll_offset.y = scroll_offset.y.min(was_offset.y);
3232        }
3233
3234        // Clamp the deferred target into the same safe range that
3235        // `update_scroll_offset` enforces on persist, so paint never shows an
3236        // over-scrolled frame before the post-paint clamp pulls it back.
3237        let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.));
3238        scroll_offset.x = scroll_offset.x.min(px(0.));
3239        scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.));
3240        self.deferred_scroll_offset = Some(scroll_offset);
3241        cx.notify();
3242    }
3243
3244    pub(super) fn show_character_palette(
3245        &mut self,
3246        _: &ShowCharacterPalette,
3247        window: &mut Window,
3248        _: &mut Context<Self>,
3249    ) {
3250        window.show_character_palette();
3251    }
3252
3253    /// The text of every non-empty selection, in document order.
3254    fn selected_texts(&self) -> Vec<String> {
3255        let mut selections: Vec<CursorSelection> = self
3256            .selections
3257            .iter()
3258            .copied()
3259            .filter(|sel| !sel.is_empty())
3260            .collect();
3261        selections.sort_by_key(|sel| sel.start);
3262        selections
3263            .iter()
3264            .map(|sel| self.text.slice(*sel).to_string())
3265            .collect()
3266    }
3267
3268    pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
3269        if !self.is_copyable() {
3270            return;
3271        }
3272
3273        let texts = self.selected_texts();
3274
3275        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3276    }
3277
3278    pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
3279        if !self.is_copyable() {
3280            return;
3281        }
3282
3283        let texts = self.selected_texts();
3284
3285        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3286
3287        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3288        self.replace_text_in_range_silent(None, "", window, cx);
3289    }
3290
3291    pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
3292        if !self.is_editable() {
3293            return;
3294        }
3295        if let Some(clipboard) = cx.read_from_clipboard() {
3296            self.insert_clipboard(clipboard, window, cx);
3297            return;
3298        }
3299        // The synchronous read is empty on platforms whose clipboard is
3300        // asynchronous and permission-gated (the web), so fall back to the
3301        // real read. It has to start here, still inside the user activation
3302        // that dispatched `Paste`, or the browser refuses the read.
3303        let read = cx.read_from_clipboard_async();
3304        let target = self.paste_target();
3305        cx.spawn_in(window, async move |this, cx| match read.await {
3306            Ok(Some(clipboard)) => {
3307                this.update_in(cx, |this, window, cx| {
3308                    // The read can sit behind a permission prompt for as
3309                    // long as the user likes. If they edited, moved the
3310                    // caret or left the input meanwhile, the paste would
3311                    // land where they no longer mean it to; drop it, as the
3312                    // browser's own paste event only reaches the focused
3313                    // input too.
3314                    if this.is_editable()
3315                        && this.focus_handle.is_focused(window)
3316                        && this.paste_target() == target
3317                    {
3318                        this.insert_clipboard(clipboard, window, cx);
3319                    }
3320                })
3321                .ok();
3322            }
3323            Ok(None) => {}
3324            Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
3325        })
3326        .detach();
3327    }
3328
3329    /// Where a paste would go right now: the document as edited so far and
3330    /// the selections it would replace. Two equal targets mean an edit made
3331    /// for one still applies to the other.
3332    fn paste_target(&self) -> PasteTarget {
3333        PasteTarget {
3334            document_revision: self.document_revision,
3335            selections: self.selections.iter().copied().collect(),
3336        }
3337    }
3338
3339    /// Inserts the clipboard text the way `Paste` does: one atomic edit,
3340    /// newlines dropped on a single-line input, one line per selection when
3341    /// the counts match on a multi-line one. A clipboard without text (an
3342    /// image, say) is left alone rather than replacing the selection with
3343    /// nothing.
3344    fn insert_clipboard(
3345        &mut self,
3346        clipboard: ClipboardItem,
3347        window: &mut Window,
3348        cx: &mut Context<Self>,
3349    ) {
3350        let Some(new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
3351            return;
3352        };
3353        // A paste is one atomic edit, never part of a typing run.
3354        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3355
3356        if !self.is_multi_line() {
3357            self.replace_text_in_range_silent(None, &new_text, window, cx);
3358            return;
3359        }
3360
3361        // Distribute one clipboard line per selection when the counts match.
3362        // Otherwise insert the whole clipboard text at each cursor.
3363        if !self.selections.is_single() {
3364            self.selections.merge_overlapping();
3365        }
3366        // Split LF and CRLF separators without leaving carriage returns at
3367        // individual cursors. Keep a trailing empty line as a paste target.
3368        let lines: Vec<_> = new_text
3369            .lines()
3370            .chain(new_text.ends_with('\n').then_some(""))
3371            .collect();
3372        let count = self.selections.len();
3373        if count > 1 && lines.len() == count {
3374            let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3375            selections.sort_by_key(|sel| sel.start);
3376            let edits: Vec<(Range<usize>, String)> = selections
3377                .iter()
3378                .zip(lines)
3379                .map(|(sel, line)| (sel.start..sel.end, line.to_owned()))
3380                .collect();
3381            self.replace_text_in_ranges(&edits, window, cx);
3382        } else {
3383            self.replace_text_in_range_silent(None, &new_text, window, cx);
3384        }
3385        self.scroll_to(self.cursor(), None, cx);
3386    }
3387
3388    /// The intent of a batch the caller did not label: inserting text at
3389    /// collapsed cursors is typing, anything else stands on its own.
3390    fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
3391        if !new_text.is_empty()
3392            && !new_text.contains(['\n', '\r'])
3393            && edits.iter().all(|(range, _)| range.is_empty())
3394        {
3395            EditIntent::Typing
3396        } else {
3397            EditIntent::Atomic
3398        }
3399    }
3400
3401    /// Where a cursor stood before an edit made with this intent.
3402    ///
3403    /// Backspace and forward delete expand a collapsed cursor over the text
3404    /// they are about to remove, so the recorded cursor has to collapse back to
3405    /// the side it came from for undo to restore it where the user left it.
3406    fn collapse_for_intent(
3407        intent: EditIntent,
3408        mut selection: CursorSelection,
3409        range: &Range<usize>,
3410    ) -> CursorSelection {
3411        match intent {
3412            EditIntent::Backspace => selection.place_at(range.end, None),
3413            EditIntent::DeleteForward => selection.place_at(range.start, None),
3414            EditIntent::Typing | EditIntent::Atomic => {}
3415        }
3416        selection
3417    }
3418
3419    /// Whether an edit rewrites the character before a collapsed cursor, as the
3420    /// macOS Korean IME does on each keystroke instead of marking text.
3421    fn rewrites_typed_char(
3422        &self,
3423        selection: CursorSelection,
3424        range: &Range<usize>,
3425        old_text: &str,
3426        new_text: &str,
3427    ) -> bool {
3428        !self.silent_replace_text
3429            && selection.is_collapsed()
3430            && selection.cursor_offset() == range.end
3431            && old_text.chars().count() == 1
3432            && !old_text.contains(['\n', '\r'])
3433            && !new_text.contains(['\n', '\r'])
3434    }
3435
3436    fn push_history(
3437        &mut self,
3438        text: &Rope,
3439        range: &Range<usize>,
3440        new_text: &str,
3441        requested_intent: Option<EditIntent>,
3442        selection_before: CursorSelection,
3443        selection_after: Option<CursorSelection>,
3444    ) -> bool {
3445        self.document_revision = self.document_revision.wrapping_add(1);
3446        let token_delta = self.edit_tokens(range, new_text.len());
3447        if self.undo_manager.is_ignoring() {
3448            return false;
3449        }
3450
3451        let range =
3452            text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
3453        let old_text = text.slice(range.clone()).to_string();
3454        let new_range = range.start..range.start + new_text.len();
3455
3456        let intent = requested_intent.unwrap_or_else(|| {
3457            if range.is_empty()
3458                && old_text.is_empty()
3459                && !new_text.is_empty()
3460                && !new_text.contains(['\n', '\r'])
3461                || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
3462            {
3463                EditIntent::Typing
3464            } else {
3465                EditIntent::Atomic
3466            }
3467        });
3468
3469        let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
3470        let selection_after =
3471            selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
3472
3473        let open_transaction = self.undo_manager.has_open_transaction();
3474        let mut change = Change::new(range, &old_text, new_range, new_text);
3475        change.token_delta = token_delta;
3476        let recorded = self.undo_manager.record_transaction(change, intent);
3477        // A batch records its own cursor sets. This covers a change that is a
3478        // transaction on its own.
3479        if recorded && !open_transaction {
3480            self.undo_manager
3481                .record_selections(vec![selection_before], vec![selection_after]);
3482        }
3483        recorded
3484    }
3485
3486    pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
3487        self.replay_history(true, window, cx);
3488    }
3489
3490    pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
3491        self.replay_history(false, window, cx);
3492    }
3493
3494    fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
3495        if !self.is_editable() {
3496            return;
3497        }
3498        let replay = if undo {
3499            self.undo_manager.undo()
3500        } else {
3501            self.undo_manager.redo()
3502        };
3503        let Some(replay) = replay else {
3504            return;
3505        };
3506        let token_aware = self.inline_tokens.is_some()
3507            || replay
3508                .changes
3509                .iter()
3510                .any(|change| change.token_delta.is_some());
3511        let emit_events = self.emit_events;
3512        if token_aware {
3513            self.emit_events = false;
3514            self.last_input_edits.clear();
3515        }
3516        self.replaying_history = token_aware;
3517        self.undo_manager.set_ignoring(true);
3518        for change in &replay.changes {
3519            let (range, text) = if undo {
3520                (change.new_range.into(), &change.old_text)
3521            } else {
3522                (change.old_range.into(), &change.new_text)
3523            };
3524            let range_utf16 = self.range_to_utf16(&range);
3525            self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
3526            self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
3527        }
3528        self.restore_selections(replay.selections);
3529        self.mode
3530            .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
3531        if token_aware {
3532            // Token replay bypasses IME normalization; a stale marked range
3533            // would otherwise describe text that no longer exists.
3534            self.ime_marked_range = None;
3535        }
3536        self.undo_manager.set_ignoring(false);
3537        self.replaying_history = false;
3538        self.emit_events = emit_events;
3539        if token_aware {
3540            if emit_events {
3541                self.emit_change(cx);
3542            } else {
3543                self.last_input_edits.clear();
3544            }
3545        }
3546        cx.notify();
3547    }
3548
3549    /// Restore a set of selections captured in a transaction, clamping offsets
3550    /// to the current text length. `None` leaves the current selections as the
3551    /// replay left them.
3552    fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
3553        let Some(selections) = selections else {
3554            return;
3555        };
3556
3557        let len = self.text.len();
3558        let restored: Vec<CursorSelection> = selections
3559            .into_iter()
3560            .map(|mut sel| {
3561                sel.start = sel.start.min(len);
3562                sel.end = sel.end.min(len);
3563                sel
3564            })
3565            .collect();
3566        self.selections.replace_all(restored);
3567        self.selections.merge_overlapping();
3568    }
3569
3570    /// Get byte offset of the text under the pointer at the right-click that last opened
3571    /// the context menu.
3572    ///
3573    /// A right-click inside the selection keeps the selection and the cursor, so a custom
3574    /// context menu reads this to find the word under the pointer. The offset is the
3575    /// UTF-8 offset.
3576    pub fn context_menu_offset(&self) -> Option<usize> {
3577        self.context_menu_offset
3578    }
3579
3580    /// Get byte offset of the cursor.
3581    ///
3582    /// The offset is the UTF-8 offset.
3583    pub fn cursor(&self) -> usize {
3584        if let Some(ime_marked_range) = &self.ime_marked_range {
3585            return ime_marked_range.end;
3586        }
3587
3588        self.selections.active().cursor_offset()
3589    }
3590
3591    /// Returns the active selection.
3592    pub(super) fn active_selection(&self) -> &CursorSelection {
3593        self.selections.active()
3594    }
3595
3596    /// Returns a mutable reference to the active selection.
3597    pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
3598        self.selections.active_mut()
3599    }
3600
3601    /// Sets the active selection to the given range, keeping its `reversed`
3602    /// and `column_anchor` state untouched.
3603    pub(super) fn set_selection(&mut self, start: usize, end: usize) {
3604        let range = self.normalize_token_range(start..end);
3605        let (start, end) = (range.start, range.end);
3606        let active = self.active_selection_mut();
3607        active.start = start;
3608        active.end = end;
3609    }
3610
3611    /// Collapses the active selection to a cursor at the given offset,
3612    /// clearing `reversed`.
3613    pub(super) fn set_cursor_to(&mut self, offset: usize) {
3614        let offset = self.token_boundary(offset, Bias::Right);
3615        let active = self.active_selection_mut();
3616        active.start = offset;
3617        active.end = offset;
3618        active.reversed = false;
3619    }
3620
3621    /// Visible row range in the last laid-out viewport, `None` before first layout.
3622    pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3623        self.last_layout.as_ref().map(|l| l.visible_range.clone())
3624    }
3625
3626    /// Current scroll offset of the editor viewport.
3627    pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
3628        self.scroll_handle.offset()
3629    }
3630
3631    /// Set scroll offset of the editor viewport.
3632    ///
3633    /// The offset will be clamped to the valid range, and applied after the next layout.
3634    pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
3635        self.deferred_scroll_offset = Some(offset);
3636        cx.notify();
3637    }
3638
3639    /// Laid-out line height; `None` before first layout.
3640    pub fn line_height(&self) -> Option<gpui::Pixels> {
3641        self.last_layout.as_ref().map(|l| l.line_height)
3642    }
3643
3644    /// Returns the active selection as a byte range into the text.
3645    ///
3646    /// With multiple cursors, this reads only the active selection.
3647    ///
3648    /// The range is empty (`start == end`) when no text is selected; in
3649    /// that case the offset equals `cursor()`. Byte offsets are measured
3650    /// in the underlying rope's byte units.
3651    pub fn selected_range(&self) -> std::ops::Range<usize> {
3652        (*self.selections.active()).into()
3653    }
3654
3655    /// Whether the active selection's caret is at the start of its range.
3656    ///
3657    /// Collapsed selections are not reversed. Use this with [`Self::selected_range`]
3658    /// and [`Self::set_selected_range_with_direction`] to restore a selection.
3659    pub fn is_selection_reversed(&self) -> bool {
3660        let selection = self.selections.active();
3661        !selection.is_empty() && selection.reversed
3662    }
3663
3664    pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3665        self.undo_manager.break_transaction_coalescing();
3666        self.selections.remove_all_but_active();
3667        self.set_selection(0, self.text.len());
3668        cx.notify();
3669    }
3670
3671    /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
3672    ///
3673    /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
3674    /// clipped to the preceding character boundary.
3675    pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3676        self.set_selected_range_with_direction(range, false, cx);
3677    }
3678
3679    /// Set the selected UTF-8 byte range and the active caret direction.
3680    ///
3681    /// With `reversed`, the caret is at the start and the anchor is at the end.
3682    /// Empty ranges collapse to a caret regardless of direction. Range clipping,
3683    /// token boundaries and removal of additional cursors follow
3684    /// [`Self::set_selected_range`].
3685    pub fn set_selected_range_with_direction(
3686        &mut self,
3687        range: Range<usize>,
3688        reversed: bool,
3689        cx: &mut Context<Self>,
3690    ) {
3691        let range = self.normalize_token_range(range);
3692        let end_bias = if range.start == range.end {
3693            Bias::Left
3694        } else {
3695            Bias::Right
3696        };
3697        let start = self.text.clip_offset(range.start, Bias::Left);
3698        let end = self.text.clip_offset(range.end, end_bias);
3699
3700        let (anchor, head) = if reversed { (end, start) } else { (start, end) };
3701        self.move_to(anchor, None, cx);
3702        self.active_selection_mut().reversed = false;
3703        self.selected_word_range = None;
3704        self.select_to(head, cx);
3705    }
3706
3707    /// Add `range` as an additional selection, keeping the existing ones —
3708    /// the programmatic equivalent of Alt-clicking another cursor into the
3709    /// text.
3710    ///
3711    /// The range is clipped to the text and expanded to character
3712    /// boundaries, like [`Self::set_selected_range`]. A range already
3713    /// covered by a selection adds nothing. Overlapping selections are merged.
3714    /// On a single-line input there is no second cursor to add, so the call
3715    /// replaces the selection instead.
3716    /// The view scrolls to the new selection.
3717    pub fn add_selection(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3718        if !self.is_multi_line() {
3719            self.set_selected_range(range, cx);
3720            return;
3721        }
3722
3723        let range = self.normalize_token_range(range);
3724        let end_bias = if range.start == range.end {
3725            Bias::Left
3726        } else {
3727            Bias::Right
3728        };
3729        let start = self.cursor_boundary(range.start, Bias::Left);
3730        // Match set_selected_range: expand UTF-8 boundaries first, then place
3731        // the selection endpoint without splitting a CRLF newline.
3732        let end = self.cursor_boundary(self.text.clip_offset(range.end, end_bias), Bias::Left);
3733
3734        for sel in self.selections.iter() {
3735            if sel.start <= start && end <= sel.end {
3736                return;
3737            }
3738        }
3739
3740        self.undo_manager.break_transaction_coalescing();
3741        self.selected_word_range = None;
3742        self.pause_blink_cursor(cx);
3743        M::hide_context_menu(self, cx);
3744        M::clear_inline_completion(self, cx);
3745        let id = self.selections.generate_id();
3746        let mut selection = CursorSelection::new(id, start, end);
3747        selection.column_anchor = self.preferred_column_for(end);
3748        self.selections.add(selection);
3749        self.selections.merge_overlapping();
3750        self.scroll_to(end, None, cx);
3751        cx.notify();
3752    }
3753
3754    /// Resolve a mouse position to a byte offset in the text.
3755    ///
3756    /// Also reports the caret's line-end affinity for that offset: `true` when the position
3757    /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
3758    /// end of that row rather than at the start of the next one. Callers that place or extend a
3759    /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
3760    /// caret one row below the pointer.
3761    pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3762        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3763        (offset, line_end_affinity)
3764    }
3765
3766    /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
3767    /// how many columns the pointer sits past the end of that row.
3768    ///
3769    /// Only a columnar selection needs the third value; everywhere else a position past
3770    /// the end of a row means the end of that row, and
3771    /// [`Self::index_for_mouse_position`] is the call to make.
3772    pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3773        // If the text is empty, always return 0
3774        if self.text.len() == 0 {
3775            return (0, false, 0);
3776        }
3777
3778        let (Some(bounds), Some(last_layout)) =
3779            (self.last_bounds.as_ref(), self.last_layout.as_ref())
3780        else {
3781            return (0, false, 0);
3782        };
3783
3784        let line_height = last_layout.line_height;
3785        let line_number_width = last_layout.line_number_width;
3786
3787        // TIP: About the IBeam cursor
3788        //
3789        // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3790
3791        // The position is relative to the bounds of the text input
3792        //
3793        // bounds.origin:
3794        //
3795        // - included the input padding.
3796        // - included the scroll offset.
3797        let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3798
3799        let mut y_offset = last_layout.visible_top;
3800        // Position relative to the last line walked, kept for a pointer that ends up
3801        // below every line.
3802        let mut last_line_pos = None;
3803
3804        // Traverse visible buffer lines (compact, no hidden entries)
3805        for (vi, (line_layout, _buffer_line)) in last_layout
3806            .lines
3807            .iter()
3808            .zip(last_layout.visible_buffer_lines.iter())
3809            .enumerate()
3810        {
3811            let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3812
3813            // Calculate line origin for this display row
3814            let line_origin = point(px(0.), y_offset);
3815            let pos = inner_position - line_origin;
3816
3817            // Return offset by use closest_index_for_x if is single line mode.
3818            if self.is_single_line() {
3819                let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3820                // A single line never wraps, so there is no boundary to disambiguate.
3821                return (
3822                    self.resolve_index(line_start_offset + local_index),
3823                    false,
3824                    0,
3825                );
3826            }
3827
3828            // Check if mouse is in this line's bounds
3829            if let Some((local_index, line_end_affinity)) =
3830                line_layout.closest_index_for_position(pos, last_layout)
3831            {
3832                return (
3833                    self.resolve_index(line_start_offset + local_index),
3834                    line_end_affinity,
3835                    line_layout.columns_past_line_end(pos, last_layout),
3836                );
3837            } else if pos.y < px(0.) {
3838                // Mouse is above this line, return start of this line
3839                return (self.resolve_index(line_start_offset), false, 0);
3840            }
3841
3842            y_offset += line_layout.size(line_height).height;
3843            last_line_pos = Some(pos);
3844        }
3845
3846        // Clamp to the last laid-out row. Returning the end of the whole document
3847        // would select unseen text before drag autoscroll has reached it.
3848        let last_position = last_layout
3849            .lines
3850            .last()
3851            .zip(last_line_pos)
3852            .zip(last_layout.visible_line_byte_offsets.last())
3853            .map(|((line_layout, pos), line_start)| {
3854                let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3855                let pos = point(pos.x, last_row_top);
3856                (
3857                    self.resolve_index(line_start + line_layout.len()),
3858                    false,
3859                    line_layout.columns_past_line_end(pos, last_layout),
3860                )
3861            });
3862
3863        last_position.unwrap_or((self.text.len(), false, 0))
3864    }
3865
3866    /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3867    /// is masked.
3868    fn resolve_index(&self, index: usize) -> usize {
3869        if self.masked {
3870            self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3871        } else {
3872            index.min(self.text.len())
3873        }
3874    }
3875
3876    /// Returns a y offsetted point for the line origin.
3877    /// Select the text from the current cursor position to the given offset.
3878    ///
3879    /// The offset is the UTF-8 offset.
3880    ///
3881    /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
3882    /// Extend a single selection so its moving end lands at `offset`, flipping
3883    /// `reversed` when the ends cross. When a sticky `word_range` is given the
3884    /// selection is kept covering it.
3885    fn extend_selection(
3886        sel: &mut CursorSelection,
3887        offset: usize,
3888        word_range: Option<CursorSelection>,
3889    ) {
3890        if sel.reversed {
3891            sel.start = offset;
3892        } else {
3893            sel.end = offset;
3894        }
3895
3896        if sel.end < sel.start {
3897            sel.reversed = !sel.reversed;
3898            std::mem::swap(&mut sel.start, &mut sel.end);
3899        }
3900
3901        if let Some(word_range) = word_range {
3902            if sel.start > word_range.start {
3903                sel.start = word_range.start;
3904            }
3905            if sel.end < word_range.end {
3906                sel.end = word_range.end;
3907            }
3908        }
3909    }
3910
3911    /// Extend only the active selection to `offset`. Used by mouse drag.
3912    pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
3913        self.select_to_with_affinity(offset, false, cx);
3914    }
3915
3916    /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
3917    ///
3918    /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
3919    /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
3920    /// the text rather than from a visual position, so the caret has no reason to keep sticking
3921    /// to the end of a wrapped row.
3922    pub(crate) fn select_to_with_affinity(
3923        &mut self,
3924        offset: usize,
3925        line_end_affinity: bool,
3926        cx: &mut Context<Self>,
3927    ) {
3928        M::clear_inline_completion(self, cx);
3929
3930        self.cursor_line_end_affinity = line_end_affinity;
3931        let offset = self.cursor_boundary(offset, Bias::Left);
3932        let word_range = self.selected_word_range;
3933        Self::extend_selection(self.active_selection_mut(), offset, word_range);
3934        let range = self.normalize_token_range(self.selected_range());
3935        self.set_selection(range.start, range.end);
3936
3937        if self.active_selection().is_empty() {
3938            self.update_preferred_column();
3939        }
3940        cx.notify()
3941    }
3942
3943    /// Extend every selection to the offset produced by `f`, then merge any
3944    /// selections that now overlap. Used by keyboard selection commands.
3945    fn select_all_cursors_to(
3946        &mut self,
3947        f: impl Fn(&Self, &CursorSelection) -> usize,
3948        cx: &mut Context<Self>,
3949    ) {
3950        self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
3951    }
3952
3953    /// Extend selections with caret affinity, preserving their column anchors even
3954    /// when vertical movement collapses a selection to a cursor.
3955    fn select_all_cursors_to_with_affinity(
3956        &mut self,
3957        f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
3958        preserve_column: bool,
3959        cx: &mut Context<Self>,
3960    ) {
3961        self.pause_blink_cursor(cx);
3962        self.undo_manager.break_transaction_coalescing();
3963        M::clear_inline_completion(self, cx);
3964
3965        let mut active_affinity = false;
3966        let new_selections: Vec<CursorSelection> = self
3967            .selections
3968            .iter()
3969            .map(|sel| {
3970                let (offset, affinity) = f(self, sel);
3971                if sel.id == self.active_selection().id {
3972                    active_affinity = affinity;
3973                }
3974                let offset = self.cursor_boundary(offset, Bias::Left);
3975                let mut new_sel = *sel;
3976                Self::extend_selection(&mut new_sel, offset, None);
3977                let range = self.normalize_token_range(new_sel.start..new_sel.end);
3978                new_sel.start = range.start;
3979                new_sel.end = range.end;
3980                if !preserve_column {
3981                    new_sel.column_anchor =
3982                        self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
3983                } else if new_sel.column_anchor.is_none() {
3984                    new_sel.column_anchor = self.preferred_column_for_with_affinity(
3985                        sel.cursor_offset(),
3986                        self.line_end_affinity_for(sel),
3987                    );
3988                }
3989                new_sel
3990            })
3991            .collect();
3992        self.cursor_line_end_affinity = active_affinity;
3993        self.selections.replace_all(new_selections);
3994        self.selections.merge_overlapping();
3995
3996        self.scroll_to(self.cursor(), None, cx);
3997        cx.notify()
3998    }
3999
4000    /// Unselects the currently selected text.
4001    pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4002        self.undo_manager.break_transaction_coalescing();
4003        let offset = self.cursor();
4004        self.set_cursor_to(offset);
4005        cx.notify()
4006    }
4007
4008    #[inline]
4009    pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
4010        self.text.offset_utf16_to_offset(offset)
4011    }
4012
4013    #[inline]
4014    pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
4015        self.text.offset_to_offset_utf16(offset)
4016    }
4017
4018    #[inline]
4019    pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
4020        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
4021    }
4022
4023    #[inline]
4024    pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
4025        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
4026    }
4027
4028    /// If offset falls on a hidden (folded) line, clamp backward to the end of
4029    /// the fold header line (last visible position before the fold).
4030    fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
4031        let line = self.text.offset_to_point(offset).row;
4032        if self.display_map.is_buffer_line_hidden(line) {
4033            for fold in self.display_map.folded_ranges() {
4034                if line > fold.start_line && line <= fold.end_line {
4035                    return self.text.line_end_offset(fold.start_line);
4036                }
4037            }
4038        }
4039        offset
4040    }
4041
4042    /// If offset falls on a hidden (folded) line, clamp forward to the start of
4043    /// the fold end line (first visible position after the fold).
4044    fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
4045        let line = self.text.offset_to_point(offset).row;
4046        if self.display_map.is_buffer_line_hidden(line) {
4047            for fold in self.display_map.folded_ranges() {
4048                if line > fold.start_line && line <= fold.end_line {
4049                    return self.text.line_start_offset(fold.end_line);
4050                }
4051            }
4052        }
4053        offset
4054    }
4055
4056    /// Clip a cursor/selection offset without splitting a CRLF newline. This does
4057    /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
4058    pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
4059        let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
4060        if offset > 0
4061            && self.text.char_at(offset - 1) == Some('\r')
4062            && self.text.char_at(offset) == Some('\n')
4063        {
4064            if bias == Bias::Left {
4065                offset - 1
4066            } else {
4067                offset + 1
4068            }
4069        } else {
4070            offset
4071        }
4072    }
4073
4074    pub(super) fn previous_boundary(&self, offset: usize) -> usize {
4075        let offset =
4076            self.cursor_boundary(previous_grapheme_boundary(&self.text, offset), Bias::Left);
4077        self.clamp_offset_to_visible_backward(offset)
4078    }
4079
4080    pub(super) fn next_boundary(&self, offset: usize) -> usize {
4081        let offset = self.cursor_boundary(next_grapheme_boundary(&self.text, offset), Bias::Right);
4082        self.clamp_offset_to_visible_forward(offset)
4083    }
4084
4085    /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
4086    pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
4087        (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
4088            && !self.disabled
4089            && self.blink_cursor.read(cx).visible()
4090            && window.is_window_active()
4091    }
4092
4093    fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4094        self.blink_cursor.update(cx, |cursor, cx| {
4095            cursor.start(cx);
4096        });
4097        cx.emit(InputEvent::Focus);
4098    }
4099
4100    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4101        self.cancel_mouse_gesture(cx);
4102        self.revealed_viewport = None;
4103        if M::is_context_menu_open(self, cx) {
4104            return;
4105        }
4106
4107        M::hide_context_menu(self, cx);
4108        self.undo_manager.break_transaction_coalescing();
4109
4110        // NOTE: Do not cancel select, when blur.
4111        // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
4112
4113        M::clear_hover_state(self, cx);
4114        self.diagnostic_popover = None;
4115        M::clear_inline_completion(self, cx);
4116        self.dismiss_touch_selection(cx);
4117        self.blink_cursor.update(cx, |cursor, cx| {
4118            cursor.stop(cx);
4119        });
4120        self.clamp_number_value(window, cx);
4121        cx.emit(InputEvent::Blur);
4122        cx.notify();
4123    }
4124
4125    /// Clamp the number value to the `min`/`max` range, used on blur.
4126    ///
4127    /// Out-of-range values are allowed while typing (e.g. `1` is an
4128    /// intermediate state of `15` when min is 10), and clamped on blur.
4129    fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4130        if !self.is_single_line() {
4131            return;
4132        }
4133        if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4134            return;
4135        }
4136        if self.number_min.is_none() && self.number_max.is_none() {
4137            return;
4138        }
4139
4140        let Ok(value) = self.unmask_value().parse::<f64>() else {
4141            return;
4142        };
4143
4144        let clamped = match (self.number_min, self.number_max) {
4145            (Some(min), _) if value < min => min,
4146            (_, Some(max)) if value > max => max,
4147            _ => return,
4148        };
4149
4150        // The clamped value must pass the `pattern`/`validate` check,
4151        // otherwise keep the value as is.
4152        let new_text = clamped.to_string();
4153        if !self.is_valid_input(&new_text, cx) {
4154            return;
4155        }
4156
4157        let range = self.range_to_utf16(&(0..self.text.len()));
4158        self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
4159    }
4160
4161    pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
4162        self.blink_cursor.update(cx, |cursor, cx| {
4163            cursor.pause(cx);
4164        });
4165    }
4166
4167    pub(super) fn cancel_mouse_gesture(&mut self, cx: &mut Context<Self>) {
4168        let was_dragging = self.selecting || self.column_select_start.is_some();
4169        self.selecting = false;
4170        self.column_select_start = None;
4171        self.auto_scroll.stop();
4172        if was_dragging {
4173            cx.notify();
4174        }
4175    }
4176
4177    pub(super) fn on_drag_move(
4178        &mut self,
4179        event: &MouseMoveEvent,
4180        window: &mut Window,
4181        cx: &mut Context<Self>,
4182    ) {
4183        if event.pressed_button != Some(MouseButton::Left) {
4184            self.cancel_mouse_gesture(cx);
4185            return;
4186        }
4187        if self.text.len() == 0 {
4188            return;
4189        }
4190
4191        if self.last_layout.is_none() {
4192            return;
4193        }
4194
4195        if !self.focus_handle.is_focused(window) {
4196            return;
4197        }
4198
4199        if !self.selecting {
4200            return;
4201        }
4202
4203        self.auto_scroll.last_drag_position = Some(event.position);
4204        let (offset, line_end_affinity, columns_past_line_end) =
4205            self.resolve_mouse_position(event.position);
4206        if let Some(start) = self.column_select_start {
4207            let end = ColumnarPoint::new(offset, columns_past_line_end);
4208            self.build_columnar_selection(start, end, cx);
4209        } else {
4210            self.select_to_with_affinity(offset, line_end_affinity, cx);
4211        }
4212
4213        if !self.is_single_line() {
4214            let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
4215            // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
4216            let scroll_delta = delta.map(|d| -d);
4217            self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
4218                let current = state.scroll_handle.offset();
4219                state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
4220                if let Some(pos) = state.auto_scroll.last_drag_position {
4221                    let (offset, line_end_affinity, columns_past_line_end) =
4222                        state.resolve_mouse_position(pos);
4223                    if let Some(start) = state.column_select_start {
4224                        let end = ColumnarPoint::new(offset, columns_past_line_end);
4225                        state.build_columnar_selection(start, end, cx);
4226                    } else {
4227                        state.select_to_with_affinity(offset, line_end_affinity, cx);
4228                    }
4229                }
4230            });
4231        }
4232    }
4233
4234    /// Normalize the inserted text before applying it to the input.
4235    ///
4236    /// For number inputs (with [`MaskPattern::Number`]), this converts
4237    /// full-width number characters into their ASCII equivalents,
4238    /// e.g. `12。5` -> `12.5`.
4239    pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
4240        let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4241            normalize_number_input(new_text)
4242        } else {
4243            Cow::Borrowed(new_text)
4244        };
4245
4246        if self.is_single_line() && normalized.contains(['\n', '\r']) {
4247            Cow::Owned(normalized.replace(['\n', '\r'], ""))
4248        } else {
4249            normalized
4250        }
4251    }
4252
4253    pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
4254        if new_text.is_empty() {
4255            return true;
4256        }
4257
4258        if let Some(validate) = &self.validate {
4259            if !validate(new_text, cx) {
4260                return false;
4261            }
4262        }
4263
4264        if !self.mask_pattern.is_valid(new_text) {
4265            return false;
4266        }
4267
4268        let Some(pattern) = &self.pattern else {
4269            return true;
4270        };
4271
4272        pattern.is_match(new_text)
4273    }
4274
4275    /// Set the mask pattern for formatting the input text.
4276    ///
4277    /// The pattern can contain:
4278    /// - 9: Any digit or dot
4279    /// - A: Any letter
4280    /// - *: Any character
4281    /// - Other characters will be treated as literal mask characters
4282    ///
4283    /// Example: "(999)999-999" for phone numbers
4284    pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
4285        self.mask_pattern = pattern.into();
4286        if let Some(placeholder) = self.mask_pattern.placeholder() {
4287            self.placeholder = placeholder.into();
4288        }
4289        self
4290    }
4291
4292    pub fn set_mask_pattern(
4293        &mut self,
4294        pattern: impl Into<MaskPattern>,
4295        _: &mut Window,
4296        cx: &mut Context<Self>,
4297    ) {
4298        self.mask_pattern = pattern.into();
4299        if let Some(placeholder) = self.mask_pattern.placeholder() {
4300            self.placeholder = placeholder.into();
4301        }
4302        cx.notify();
4303    }
4304
4305    pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
4306        let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
4307        self.input_bounds = new_bounds;
4308
4309        // Update display_map wrap_width if changed.
4310        if let Some(last_layout) = self.last_layout.as_ref() {
4311            if wrap_width_changed {
4312                let wrap_width = if !self.soft_wrap {
4313                    // None to disable wrapping (will use Pixels::MAX)
4314                    None
4315                } else {
4316                    last_layout.wrap_width
4317                };
4318
4319                self.display_map.on_layout_changed(wrap_width, cx);
4320                if self.is_multi_line() {
4321                    self.mode.update_auto_grow(&self.display_map);
4322                }
4323                cx.notify();
4324            }
4325        }
4326    }
4327
4328    /// Return the active selection's text, borrowed out of the [`Rope`]
4329    /// the state owns.
4330    ///
4331    /// See [`Self::selected_value`] when an owned string is wanted.
4332    pub fn selected_text(&self) -> RopeSlice<'_> {
4333        let range_utf16 = self.range_to_utf16(&self.selected_range());
4334        let range = self.range_from_utf16(&range_utf16);
4335        self.text.slice(range)
4336    }
4337
4338    /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
4339    ///
4340    /// Returns `None` when the requested range is not currently laid out or visible.
4341    pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
4342        let Some(last_layout) = self.last_layout.as_ref() else {
4343            return None;
4344        };
4345
4346        let Some(last_bounds) = self.last_bounds else {
4347            return None;
4348        };
4349
4350        let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
4351        let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
4352
4353        let Some(start_pos) = start_pos else {
4354            return None;
4355        };
4356        let Some(end_pos) = end_pos else {
4357            return None;
4358        };
4359
4360        Some(Bounds::from_corners(
4361            last_bounds.origin + start_pos,
4362            last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
4363        ))
4364    }
4365
4366    /// Replace text in range in silent.
4367    ///
4368    /// This will not trigger any UI interaction, such as auto-completion.
4369    pub(crate) fn replace_text_in_range_silent(
4370        &mut self,
4371        range_utf16: Option<Range<usize>>,
4372        new_text: &str,
4373        window: &mut Window,
4374        cx: &mut Context<Self>,
4375    ) {
4376        self.silent_replace_text = true;
4377        self.replace_text_in_range(range_utf16, new_text, window, cx);
4378        self.silent_replace_text = false;
4379    }
4380
4381    /// Apply a batch of edits as one atomic history transaction.
4382    ///
4383    /// `edits` are `(byte range in the current pre-edit document, replacement)`
4384    /// pairs.
4385    pub(crate) fn replace_text_in_ranges(
4386        &mut self,
4387        edits: &[(Range<usize>, String)],
4388        window: &mut Window,
4389        cx: &mut Context<Self>,
4390    ) {
4391        if !self.is_editable() || edits.is_empty() {
4392            return;
4393        }
4394
4395        // Every edit invalidates provider responses for the previous document,
4396        // including deletion and indentation which do not trigger completion.
4397        M::hide_context_menu(self, cx);
4398        M::clear_inline_completion(self, cx);
4399
4400        // Sort descending by start so applying front-of-vec first edits the
4401        // highest offsets first, leaving lower offsets unchanged.
4402        let mut sorted: Vec<(Range<usize>, &str)> = edits
4403            .iter()
4404            .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
4405            .collect();
4406        sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
4407        if !self.token_spans().is_empty() {
4408            let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
4409            for (range, text) in sorted {
4410                if let Some(last) = merged
4411                    .last_mut()
4412                    .filter(|last| range.end > last.0.start || range == last.0)
4413                {
4414                    last.0.start = range.start.min(last.0.start);
4415                    last.0.end = range.end.max(last.0.end);
4416                } else {
4417                    merged.push((range, text));
4418                }
4419            }
4420            sorted = merged;
4421        }
4422
4423        #[cfg(debug_assertions)]
4424        for pair in sorted.windows(2) {
4425            debug_assert!(
4426                pair[1].0.end <= pair[0].0.start,
4427                "replace_text_in_ranges requires disjoint ranges"
4428            );
4429        }
4430
4431        // Wrap multiple edits in one explicit transaction so they undo as a
4432        // unit. A single edit records directly, which keeps it eligible for
4433        // the undo manager's typing coalescing.
4434        let requested_intent = self.undo_manager.take_pending_intent();
4435        let selection_before = *self.active_selection();
4436        let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
4437        // Snapshot the cursors before applying, so undo can restore them. A
4438        // delete has already expanded them over the text it removes, so they
4439        // collapse back to where the user left them.
4440        let selections_before: Vec<CursorSelection> = self
4441            .selections
4442            .iter()
4443            .map(|selection| {
4444                Self::collapse_for_intent(
4445                    requested_intent.unwrap_or(EditIntent::Atomic),
4446                    *selection,
4447                    &(selection.start..selection.end),
4448                )
4449            })
4450            .collect();
4451        let group = sorted.len() > 1;
4452        if group {
4453            self.undo_manager.begin_transaction();
4454        }
4455
4456        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4457        let mut recorded = false;
4458        // Several edits reach the highlighter as one batch, so it reparses
4459        // once for the change instead of once per edit.
4460        let mut highlighter_edits = Vec::new();
4461        // Token-aware history replay applies several replacements but emits one
4462        // `Change` at the end, so its edits accumulate instead of being
4463        // discarded with each silent replacement.
4464        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4465        if !accumulate_replay_edits {
4466            self.last_input_edits.clear();
4467        }
4468        for (range, new_text) in &sorted {
4469            let old_text = self.text.clone();
4470            self.mode.adjust_auto_closed_pair(range, new_text.len());
4471            self.text.replace(range.clone(), new_text);
4472
4473            M::adjust_annotations(self, range, new_text.len());
4474            recorded |= self.push_history(
4475                &old_text,
4476                range,
4477                new_text,
4478                requested_intent,
4479                selection_before,
4480                None,
4481            );
4482
4483            // Incremental, single-range updates must run per edit.
4484            self.display_map
4485                .adjust_folds_for_edit(&old_text, range, new_text);
4486            self.display_map
4487                .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
4488
4489            let edit = super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
4490            if self.emit_events || self.replaying_history {
4491                self.last_input_edits.push((edit, self.text.clone()));
4492            }
4493
4494            if group {
4495                if self.is_code_editor() {
4496                    highlighter_edits.push((edit, self.text.clone()));
4497                }
4498            } else {
4499                self.mode.update_highlighter(
4500                    super::mode::HighlighterUpdate {
4501                        selected_range: range,
4502                        old_text: &old_text,
4503                        new_text: &self.text,
4504                        change_text: new_text,
4505                        force: true,
4506                        input_edit: Some(edit),
4507                    },
4508                    window,
4509                    cx,
4510                );
4511
4512                self.update_fold_candidates_incremental(range, new_text);
4513            }
4514        }
4515
4516        if group {
4517            self.mode
4518                .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
4519
4520            // Fold candidates are read from the reparsed document, so each
4521            // edit is located where it ended up once every edit was applied.
4522            // `sorted` runs from the highest offset down.
4523            let mut shift = 0isize;
4524            for (range, new_text) in sorted.iter().rev() {
4525                let start = (range.start as isize + shift) as usize;
4526                self.update_fold_candidates_incremental(&(start..start), new_text);
4527                shift += new_text.len() as isize - range.len() as isize;
4528            }
4529
4530            self.undo_manager.commit_transaction();
4531        }
4532
4533        // One observable update per batch instead of one per edit.
4534        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4535            diagnostics.reset(&self.text)
4536        }
4537        M::refresh_language_features(self, window, cx);
4538        self.update_search(cx);
4539
4540        // Compute the resulting cursors.
4541        // One collapsed cursor per edit, at the end of its inserted text.
4542        let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
4543        ascending.sort_by_key(|edit| edit.0.start);
4544        let text_len = self.text.len();
4545        let mut delta: isize = 0;
4546        let mut edit_results = Vec::with_capacity(ascending.len());
4547        for (range, new_text) in &ascending {
4548            let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
4549            edit_results.push((range.clone(), offset));
4550            delta += new_text.len() as isize - (range.end as isize - range.start as isize);
4551        }
4552
4553        let mut used = vec![false; edit_results.len()];
4554        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
4555        for selection in original_selections {
4556            if let Ok(index) = edit_results
4557                .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
4558                    (range.start, range.end)
4559                })
4560                && !used[index]
4561            {
4562                let offset = edit_results[index].1;
4563                used[index] = true;
4564                let mut selection = selection;
4565                selection.place_at(offset, None);
4566                new_selections.push(selection);
4567            }
4568        }
4569        for (index, (_, offset)) in edit_results.into_iter().enumerate() {
4570            if !used[index] {
4571                new_selections.push(CursorSelection::new(
4572                    self.selections.generate_id(),
4573                    offset,
4574                    offset,
4575                ));
4576            }
4577        }
4578        self.selections.replace_all(new_selections);
4579        self.selections.merge_overlapping();
4580
4581        // Record the cursor snapshots for undo/redo restore.
4582        let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
4583        if recorded {
4584            self.undo_manager.record_auto_closed_pairs(
4585                auto_closed_pairs_before,
4586                self.mode.auto_closed_pairs().clone(),
4587            );
4588            self.undo_manager
4589                .record_selections(selections_before, selections_after);
4590        }
4591
4592        self.ime_marked_range.take();
4593        self.update_preferred_column();
4594        self.dismiss_touch_selection(cx);
4595        if self.is_multi_line() {
4596            self.mode.update_auto_grow(&self.display_map);
4597        }
4598        if self.emit_events {
4599            self.emit_change(cx);
4600        }
4601        cx.notify();
4602    }
4603
4604    /// Update fold candidates from tree-sitter syntax tree (full extraction).
4605    /// Used only on initial load or language changes.
4606    fn update_fold_candidates(&mut self) {
4607        if !self.mode.is_folding() {
4608            return;
4609        }
4610
4611        let Some(highlighter_rc) = self.mode.highlighter() else {
4612            return;
4613        };
4614
4615        let highlighter = highlighter_rc.borrow();
4616        let Some(highlighter) = highlighter.as_ref() else {
4617            return;
4618        };
4619
4620        let fold_ranges = highlighter.fold_ranges(&self.text);
4621        self.display_map.set_fold_candidates(fold_ranges);
4622    }
4623
4624    /// Incrementally update fold candidates after a text edit.
4625    /// Only traverses the edited region of the syntax tree instead of the full tree.
4626    fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
4627        if !self.mode.is_folding() {
4628            return;
4629        }
4630
4631        let Some(highlighter_rc) = self.mode.highlighter() else {
4632            return;
4633        };
4634
4635        let highlighter = highlighter_rc.borrow();
4636        let Some(highlighter) = highlighter.as_ref() else {
4637            return;
4638        };
4639
4640        // The new byte range in the updated text after the edit
4641        let new_end = edit_range.start + new_text.len();
4642        self.display_map.update_fold_candidates_for_edit(
4643            |range, text| highlighter.fold_ranges_for_edit(range, text),
4644            edit_range.start..new_end,
4645            &self.text,
4646        );
4647    }
4648}
4649
4650impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4651    fn accepts_text_input(&self, window: &mut Window, _cx: &mut Context<Self>) -> bool {
4652        self.focus_handle.is_focused(window)
4653    }
4654
4655    fn text_for_range(
4656        &mut self,
4657        range_utf16: Range<usize>,
4658        adjusted_range: &mut Option<Range<usize>>,
4659        _window: &mut Window,
4660        _cx: &mut Context<Self>,
4661    ) -> Option<String> {
4662        let range = self.range_from_utf16(&range_utf16);
4663        let range_utf16 = self.range_to_utf16(&range);
4664        let utf16_len = range_utf16.len();
4665        adjusted_range.replace(range_utf16);
4666        if self.masked {
4667            // Keep the redacted text aligned with the platform's UTF-16 range.
4668            return Some(MASK_CHAR.to_string().repeat(utf16_len));
4669        }
4670        Some(self.text.slice(range).to_string())
4671    }
4672
4673    fn selected_text_range(
4674        &mut self,
4675        _ignore_disabled_input: bool,
4676        _window: &mut Window,
4677        _cx: &mut Context<Self>,
4678    ) -> Option<UTF16Selection> {
4679        Some(UTF16Selection {
4680            range: self.range_to_utf16(&self.selected_range()),
4681            reversed: self.active_selection().reversed,
4682        })
4683    }
4684
4685    /// Select the given range, as the platform's own text UI asks when it
4686    /// drives the selection: a native selection handle, or the macOS IME.
4687    ///
4688    /// The end that moved becomes the cursor, so dragging the start handle
4689    /// leaves a reversed selection and keeps the moving end in view. Text and
4690    /// undo history are left alone.
4691    fn set_selected_text_range(
4692        &mut self,
4693        range_utf16: Range<usize>,
4694        _window: &mut Window,
4695        cx: &mut Context<Self>,
4696    ) {
4697        let previous = self.selected_range();
4698        let was_reversed = self.active_selection().reversed;
4699        let range = self.range_from_utf16(&range_utf16);
4700        let range = range.start.min(range.end)..range.start.max(range.end);
4701        self.set_selected_range(range, cx);
4702
4703        let range = self.selected_range();
4704        let reversed = if range == previous {
4705            was_reversed
4706        } else if !range.is_empty() && range.end == previous.start {
4707            true
4708        } else if !range.is_empty() && range.start == previous.end {
4709            false
4710        } else {
4711            !range.is_empty() && range.start != previous.start && range.end == previous.end
4712        };
4713        self.active_selection_mut().reversed = reversed;
4714        self.scroll_to(self.cursor(), None, cx);
4715        cx.notify();
4716    }
4717
4718    fn marked_text_range(
4719        &self,
4720        _window: &mut Window,
4721        _cx: &mut Context<Self>,
4722    ) -> Option<Range<usize>> {
4723        self.ime_marked_range
4724            .map(|range| self.range_to_utf16(&range.into()))
4725    }
4726
4727    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4728        self.ime_marked_range = None;
4729        self.undo_manager.commit_transaction();
4730        // Unmarking keeps the preedit as committed text, which marked edits
4731        // never reported. Android keyboards compose every word and often end
4732        // with only this call (hiding the keyboard, moving the caret).
4733        if self.ime_original_text.as_ref() == Some(&self.text) {
4734            self.ime_original_text = None;
4735        } else if self.ime_original_text.is_some() && self.emit_events {
4736            self.emit_change(cx);
4737        }
4738    }
4739
4740    /// Replace text in range.
4741    ///
4742    /// - If the new text is invalid, it will not be replaced.
4743    /// - If `range_utf16` is not provided, the current selected range will be used.
4744    fn replace_text_in_range(
4745        &mut self,
4746        range_utf16: Option<Range<usize>>,
4747        new_text: &str,
4748        window: &mut Window,
4749        cx: &mut Context<Self>,
4750    ) {
4751        let requested_intent = self.undo_manager.take_pending_intent();
4752        if !self.is_editable() {
4753            return;
4754        }
4755        let selection_before = *self.active_selection();
4756        // Committing a composition ends the transaction it opened, whether or
4757        // not the platform follows up with `unmark_text`.
4758        let ends_composition = self.ime_marked_range.is_some();
4759
4760        self.pause_blink_cursor(cx);
4761
4762        // NOTE: The normalization keeps the UTF-16 length, but may change the
4763        // UTF-8 byte length, so all the byte-offset calculations below must
4764        // use the normalized text.
4765        let new_text = if self.replaying_history {
4766            Cow::Borrowed(new_text)
4767        } else {
4768            self.normalize_input(new_text)
4769        };
4770        let new_text: &str = &new_text;
4771
4772        let range = range_utf16
4773            .as_ref()
4774            .map(|range_utf16| self.range_from_utf16(range_utf16))
4775            .or(self.ime_marked_range.map(|range| {
4776                let range = self.range_to_utf16(&(range.start..range.end));
4777                self.range_from_utf16(&range)
4778            }))
4779            .unwrap_or(self.selected_range());
4780        let range = self.normalize_token_range(range);
4781
4782        // Skip-over as a pure cursor move: a typed closer that already follows
4783        // the cursor moves past it without touching text or history, so Undo
4784        // never exposes a transient duplicate. Only for interactive single
4785        // keystrokes (current selection, no IME mark, not silent replays).
4786        // `take_pending_intent` above already consumed any request.
4787        if range.is_empty()
4788            && range.start == self.cursor()
4789            && self.ime_marked_range.is_none()
4790            && !self.silent_replace_text
4791            && self.is_code_editor()
4792            && self.selections.is_single()
4793            && self.active_selection().is_empty()
4794        {
4795            if let Some(target) = self.skip_over_target(new_text) {
4796                self.set_cursor_to(target);
4797                self.update_preferred_column();
4798                cx.notify();
4799                return;
4800            }
4801        }
4802
4803        if self.is_multi_line() {
4804            let multi_cursor = range_utf16.is_none()
4805                && self.ime_marked_range.is_none()
4806                && !self.selections.is_single();
4807            if multi_cursor {
4808                self.selections.merge_overlapping();
4809                let mut edits: Vec<(Range<usize>, String)> = self
4810                    .selections
4811                    .iter()
4812                    .map(|sel| (sel.start..sel.end, new_text.to_string()))
4813                    .collect();
4814                edits.sort_by_key(|(range, _)| range.start);
4815                // One keystroke across several cursors is one batch, committed
4816                // with the intent of the keystroke so a run of them coalesces
4817                // into one undo just like single-cursor typing.
4818                let intent =
4819                    requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
4820                self.undo_manager.begin_transaction_with(intent);
4821                self.undo_manager.set_pending_intent(intent);
4822                self.replace_text_in_ranges(&edits, window, cx);
4823                self.undo_manager.commit_transaction();
4824            } else {
4825                if range_utf16.is_some() {
4826                    self.selections.remove_all_but_active();
4827                }
4828                if let Some(intent) = requested_intent {
4829                    self.undo_manager.set_pending_intent(intent);
4830                }
4831                if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
4832                    // One edit keeps the pair atomic even at undo coalescing limits.
4833                    let replacement = format!("{new_text}{closer}");
4834                    self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
4835                    let cursor = range.start + new_text.len();
4836                    self.mode.track_auto_closed_pair(
4837                        cursor - open_len..cursor,
4838                        cursor..cursor + closer.len(),
4839                    );
4840                    self.undo_manager
4841                        .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
4842                    self.set_cursor_to(cursor);
4843                    self.update_preferred_column();
4844                    self.undo_manager.record_selections(
4845                        vec![selection_before],
4846                        self.selections.iter().copied().collect(),
4847                    );
4848                } else {
4849                    self.replace_text_in_ranges(
4850                        &[(range.clone(), new_text.to_string())],
4851                        window,
4852                        cx,
4853                    );
4854                }
4855            }
4856            if ends_composition {
4857                self.undo_manager.commit_transaction();
4858            }
4859
4860            if !self.silent_replace_text {
4861                M::on_text_typed(self, &range, new_text, window, cx);
4862            }
4863            return;
4864        }
4865
4866        // Single-line path
4867        let old_text = self.text.clone();
4868        // Token-aware history replay applies several replacements but emits one
4869        // `Change` at the end, so its edits accumulate instead of being
4870        // discarded with each silent replacement.
4871        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4872        if !accumulate_replay_edits {
4873            self.last_input_edits.clear();
4874        }
4875        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4876        self.text.replace(range.clone(), new_text);
4877
4878        let mut new_offset = (range.start + new_text.len()).min(self.text.len());
4879
4880        // True if the mask has changed the text, e.g. regrouping the
4881        // separators or completing a leading dot.
4882        let mut mask_changed = false;
4883
4884        if self.is_single_line() {
4885            let pending_text = self.text.to_string();
4886            // Check if the new text is valid.
4887            //
4888            // Only reject the edit if the old text was valid, to avoid
4889            // trapping a pre-existing invalid text (e.g. a `default_value`
4890            // that does not conform), the user can still edit to fix it.
4891            if !self.replaying_history
4892                && !self.validated_token_edit
4893                && !self.is_valid_input(&pending_text, cx)
4894                && self.is_valid_input(&old_text.to_string(), cx)
4895            {
4896                self.text = old_text;
4897                return;
4898            }
4899
4900            if !self.replaying_history && !self.mask_pattern.is_none() {
4901                let mask_text = self.mask_pattern.mask(&pending_text);
4902                mask_changed = mask_text.as_str() != pending_text;
4903                self.text = Rope::from(mask_text.as_str());
4904                let new_text_len =
4905                    (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
4906                new_offset = (range.start + new_text_len).min(mask_text.len());
4907            }
4908        }
4909
4910        if mask_changed {
4911            // Masking rewrites the whole document, so ranges recorded against
4912            // the old text no longer point at anything.
4913            M::reset_annotations(self);
4914        } else {
4915            M::adjust_annotations(self, &range, new_text.len());
4916        }
4917        if mask_changed {
4918            // A segment-based history entry no longer matches the masked
4919            // document, record a whole-document change instead, so that
4920            // undo/redo can restore the text exactly.
4921            self.push_history(
4922                &old_text,
4923                &(0..old_text.len()),
4924                &self.text.to_string(),
4925                Some(EditIntent::Atomic),
4926                selection_before,
4927                Some((new_offset..new_offset).into()),
4928            );
4929        } else {
4930            self.push_history(
4931                &old_text,
4932                &range,
4933                &new_text,
4934                requested_intent,
4935                selection_before,
4936                None,
4937            );
4938        }
4939        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4940            diagnostics.reset(&self.text)
4941        }
4942        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4943        self.display_map
4944            .adjust_folds_for_edit(&old_text, &range, new_text);
4945        self.display_map
4946            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4947
4948        let edit = if mask_changed {
4949            Self::full_input_edit(&old_text, &self.text)
4950        } else {
4951            super::mode::replacement_input_edit(&old_text, &self.text, &range, new_text)
4952        };
4953        if self.emit_events || self.replaying_history {
4954            self.last_input_edits.push((edit, self.text.clone()));
4955        }
4956
4957        self.mode.update_highlighter::<M>(
4958            super::mode::HighlighterUpdate {
4959                selected_range: &range,
4960                old_text: &old_text,
4961                new_text: &self.text,
4962                change_text: &new_text,
4963                force: true,
4964                input_edit: Some(edit),
4965            },
4966            window,
4967            cx,
4968        );
4969
4970        self.update_fold_candidates_incremental(&range, new_text);
4971        M::refresh_language_features(self, window, cx);
4972        self.set_cursor_to(new_offset);
4973        self.ime_marked_range.take();
4974        // A commit ends the IME composition: macOS delivers `insertText:` for
4975        // the confirmed candidate without a following `unmarkText`, so close
4976        // the transaction here. Leaving it open would keep merging every later
4977        // edit into the same change, which then carries the text and selection
4978        // of the first composition.
4979        if ends_composition {
4980            self.undo_manager
4981                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4982            self.undo_manager.commit_transaction();
4983        }
4984        self.update_preferred_column();
4985        self.update_search(cx);
4986        self.dismiss_touch_selection(cx);
4987        if self.is_multi_line() {
4988            self.mode.update_auto_grow(&self.display_map);
4989        }
4990        if !self.silent_replace_text {
4991            M::on_text_typed(self, &range, &new_text, window, cx);
4992        }
4993        if self.emit_events {
4994            self.emit_change(cx);
4995        }
4996        cx.notify();
4997    }
4998
4999    /// Mark text is the IME temporary insert on typing.
5000    fn replace_and_mark_text_in_range(
5001        &mut self,
5002        range_utf16: Option<Range<usize>>,
5003        new_text: &str,
5004        new_selected_range_utf16: Option<Range<usize>>,
5005        window: &mut Window,
5006        cx: &mut Context<Self>,
5007    ) {
5008        let requested_intent = self.undo_manager.take_pending_intent();
5009        if !self.is_editable() {
5010            return;
5011        }
5012        let selection_before = *self.active_selection();
5013
5014        let starts_composition = self.ime_marked_range.is_none();
5015        if starts_composition {
5016            // Even a canceled preedit separates the typing gestures on either
5017            // side; its no-op transaction must not reconnect those gestures.
5018            self.undo_manager.break_transaction_coalescing();
5019            self.undo_manager.begin_transaction();
5020        }
5021
5022        // Collapse any extra cursors so we never leave stale secondary cursors behind.
5023        self.selections.remove_all_but_active();
5024
5025        M::reset_language_features(self);
5026
5027        // See the same NOTE in `replace_text_in_range`.
5028        let new_text = if self.replaying_history {
5029            Cow::Borrowed(new_text)
5030        } else {
5031            self.normalize_input(new_text)
5032        };
5033        let new_text: &str = &new_text;
5034
5035        let range = range_utf16
5036            .as_ref()
5037            .map(|range_utf16| self.range_from_utf16(range_utf16))
5038            .or(self.ime_marked_range.map(|range| {
5039                let range = self.range_to_utf16(&(range.start..range.end));
5040                self.range_from_utf16(&range)
5041            }))
5042            .unwrap_or(self.selected_range());
5043        let range = self.normalize_token_range(range);
5044
5045        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
5046        let old_text = self.text.clone();
5047        // Marked text does not emit `InputEvent::Change`, so no edit belongs to
5048        // the most recent change after it.
5049        self.last_input_edits.clear();
5050        self.mode.adjust_auto_closed_pair(&range, new_text.len());
5051        self.text.replace(range.clone(), new_text);
5052
5053        if self.is_single_line() {
5054            let pending_text = self.text.to_string();
5055            // See the same NOTE in `replace_text_in_range`.
5056            if !self.replaying_history
5057                && !self.validated_token_edit
5058                && !self.is_valid_input(&pending_text, cx)
5059                && self.is_valid_input(&old_text.to_string(), cx)
5060            {
5061                self.text = old_text;
5062                if starts_composition {
5063                    self.undo_manager.commit_transaction();
5064                }
5065                return;
5066            }
5067        }
5068
5069        if self.ime_original_text.is_none() {
5070            self.ime_original_text = Some(old_text.clone());
5071        }
5072        M::adjust_annotations(self, &range, new_text.len());
5073        if let Some(diagnostics) = self.mode.diagnostics_mut() {
5074            diagnostics.reset(&self.text)
5075        }
5076        // Adjust folds before updating wrap map: remove overlapping folds and shift others
5077        self.display_map
5078            .adjust_folds_for_edit(&old_text, &range, new_text);
5079        self.display_map
5080            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5081
5082        self.mode.update_highlighter::<M>(
5083            super::mode::HighlighterUpdate {
5084                selected_range: &range,
5085                old_text: &old_text,
5086                new_text: &self.text,
5087                change_text: &new_text,
5088                force: true,
5089                input_edit: None,
5090            },
5091            window,
5092            cx,
5093        );
5094
5095        self.update_fold_candidates_incremental(&range, new_text);
5096        M::refresh_language_features(self, window, cx);
5097        if new_text.is_empty() {
5098            // Cancel selection, when cancel IME input.
5099            self.set_cursor_to(range.start);
5100            self.ime_marked_range = None;
5101        } else {
5102            self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
5103            let new_range = new_selected_range_utf16
5104                .as_ref()
5105                .map(|range_utf16| {
5106                    let new_text = Rope::from(new_text);
5107                    range.start + new_text.offset_utf16_to_offset(range_utf16.start)
5108                        ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
5109                })
5110                .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
5111            self.set_selection(new_range.start, new_range.end);
5112        }
5113        if self.is_multi_line() {
5114            self.mode.update_auto_grow(&self.display_map);
5115        }
5116        if self.push_history(
5117            &old_text,
5118            &range,
5119            new_text,
5120            requested_intent,
5121            selection_before,
5122            Some(*self.active_selection()),
5123        ) {
5124            self.undo_manager
5125                .record_selections(vec![selection_before], vec![*self.active_selection()]);
5126            self.undo_manager.record_auto_closed_pairs(
5127                auto_closed_pairs_before,
5128                self.mode.auto_closed_pairs().clone(),
5129            );
5130        }
5131        if new_text.is_empty() {
5132            self.undo_manager.commit_transaction();
5133        }
5134        cx.notify();
5135    }
5136
5137    /// Used to position IME candidates.
5138    fn bounds_for_range(
5139        &mut self,
5140        range_utf16: Range<usize>,
5141        bounds: Bounds<Pixels>,
5142        _window: &mut Window,
5143        _cx: &mut Context<Self>,
5144    ) -> Option<Bounds<Pixels>> {
5145        let last_layout = self.last_layout.as_ref()?;
5146        let line_height = last_layout.line_height;
5147        let line_number_width = last_layout.line_number_width;
5148        let range = self.range_from_utf16(&range_utf16);
5149
5150        let mut start_origin = None;
5151        let mut end_origin = None;
5152        let line_number_origin = point(line_number_width, px(0.));
5153        let mut y_offset = last_layout.visible_top;
5154
5155        let start_row = self
5156            .text
5157            .offset_to_point(range.start.min(self.text.len()))
5158            .row;
5159        let end_row = self
5160            .text
5161            .offset_to_point(range.end.min(self.text.len()))
5162            .row;
5163
5164        for (vi, line) in last_layout.lines.iter().enumerate() {
5165            if start_origin.is_some() && end_origin.is_some() {
5166                break;
5167            }
5168
5169            let buffer_line = last_layout.visible_buffer_lines[vi];
5170            let index_offset = last_layout.visible_line_byte_offsets[vi];
5171
5172            if start_origin.is_none() && buffer_line == start_row {
5173                let local_offset = range.start.saturating_sub(index_offset).min(line.len());
5174                let p = line
5175                    .position_for_index(local_offset, last_layout, false)
5176                    .unwrap_or_else(|| point(px(0.), px(0.)));
5177                start_origin = Some(p + point(px(0.), y_offset));
5178            }
5179
5180            if end_origin.is_none() && buffer_line == end_row {
5181                let local_offset = range.end.saturating_sub(index_offset).min(line.len());
5182                let p = line
5183                    .position_for_index(local_offset, last_layout, false)
5184                    .unwrap_or_else(|| point(px(0.), px(0.)));
5185                end_origin = Some(p + point(px(0.), y_offset));
5186            }
5187
5188            y_offset += line.size(line_height).height;
5189        }
5190
5191        let start_origin = start_origin.or_else(|| {
5192            let offset = self.last_cursor.or(Some(self.cursor()))?;
5193            let (_, _, origin) = self.line_and_position_for_offset(offset);
5194            origin.map(|origin| origin - line_number_origin)
5195        })?;
5196        let mut end_origin = end_origin.unwrap_or(start_origin);
5197        // Ensure at same line.
5198        end_origin.y = start_origin.y;
5199        if end_origin.x <= start_origin.x {
5200            end_origin.x = start_origin.x + px(1.);
5201        }
5202
5203        Some(Bounds::from_corners(
5204            bounds.origin + line_number_origin + start_origin,
5205            // + line_height for show IME panel under the cursor line.
5206            bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
5207        ))
5208    }
5209
5210    fn character_index_for_point(
5211        &mut self,
5212        point: gpui::Point<Pixels>,
5213        _window: &mut Window,
5214        _cx: &mut Context<Self>,
5215    ) -> Option<usize> {
5216        let last_layout = self.last_layout.as_ref()?;
5217        self.input_bounds.localize(&point)?;
5218        let inner_position = point - self.last_bounds?.origin;
5219        let mut y_offset = last_layout.visible_top;
5220
5221        for (vi, line) in last_layout.lines.iter().enumerate() {
5222            let offset = last_layout.visible_line_byte_offsets[vi];
5223            let line_point = inner_position - gpui::point(last_layout.line_number_width, y_offset);
5224            if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
5225                return Some(self.offset_to_utf16(self.resolve_index(offset + utf8_index)));
5226            }
5227            y_offset += line.size(last_layout.line_height).height;
5228        }
5229
5230        None
5231    }
5232
5233    fn text_input_configuration(
5234        &mut self,
5235        _window: &mut Window,
5236        _cx: &mut Context<Self>,
5237    ) -> TextInputConfiguration {
5238        InputBaseState::text_input_configuration(self)
5239    }
5240}
5241
5242impl<M: InputModeKind> Focusable for InputBaseState<M> {
5243    fn focus_handle(&self, _cx: &App) -> FocusHandle {
5244        self.focus_handle.clone()
5245    }
5246}
5247
5248impl<M: InputModeKind> Render for InputBaseState<M> {
5249    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5250        // Before anything reads it: the element resolves this style during
5251        // layout and paint, and both happen after this call in the same frame.
5252        self.editor_style = self
5253            .projected_editor_style
5254            .resolved(&crate::Theme::global(cx).input_colors);
5255        let entity = cx.entity();
5256        let text_runs = self.accessibility_text_runs(window);
5257        if self._pending_update {
5258            self.mode.update_highlighter::<M>(
5259                super::mode::HighlighterUpdate {
5260                    selected_range: &(0..0),
5261                    old_text: &self.text,
5262                    new_text: &self.text,
5263                    change_text: "",
5264                    force: false,
5265                    input_edit: None,
5266                },
5267                window,
5268                cx,
5269            );
5270
5271            self.update_fold_candidates();
5272            M::refresh_language_features(self, window, cx);
5273            self._pending_update = false;
5274        }
5275
5276        let element = div()
5277            .id(EDITOR_ELEMENT_ID)
5278            .key_context(CONTEXT)
5279            .when_some(self.accessibility.as_ref(), |this, accessibility| {
5280                this.when_some(accessibility.role, |this, role| this.role(role))
5281                    .when_some(accessibility.label.clone(), |this, label| {
5282                        this.aria_label(label)
5283                    })
5284                    .when_some(accessibility.description.clone(), |this, description| {
5285                        this.aria_description(description)
5286                    })
5287                    .when_some(accessibility.placeholder.clone(), |this, placeholder| {
5288                        this.aria_placeholder(placeholder)
5289                    })
5290                    .when_some(accessibility.accessibility_id.clone(), |this, id| {
5291                        this.accessibility_id(id)
5292                    })
5293                    .when_some(accessibility.expanded, |this, expanded| {
5294                        this.aria_expanded(expanded)
5295                    })
5296                    .when(
5297                        accessibility.value_exposed
5298                            && !self.masked
5299                            && (window.is_a11y_active() || cfg!(feature = "test-support")),
5300                        |this| this.aria_value(self.text.to_string()),
5301                    )
5302                    .when_some(text_runs, |this, runs| {
5303                        this.a11y_synthetic_children(move |builder| runs.push(builder))
5304                    })
5305                    .on_a11y_action(gpui::AccessibleAction::Focus, {
5306                        let entity = entity.clone();
5307                        move |_, window, cx| {
5308                            entity.update(cx, |state, cx| {
5309                                state.handle_accessibility_focus(window, cx)
5310                            });
5311                        }
5312                    })
5313                    .when(self.is_editable(), |this| {
5314                        this.on_a11y_action(gpui::AccessibleAction::SetValue, {
5315                            let entity = entity.clone();
5316                            move |data, window, cx| {
5317                                entity.update(cx, |state, cx| {
5318                                    state.handle_accessibility_set_value(data, window, cx)
5319                                });
5320                            }
5321                        })
5322                    })
5323            })
5324            .when(self.is_editable(), |this| {
5325                this.on_action(window.listener_for(&entity, InputBaseState::backspace))
5326                    .on_action(window.listener_for(&entity, InputBaseState::delete))
5327                    .on_action(
5328                        window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
5329                    )
5330                    .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
5331                    .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
5332                    .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
5333                    .on_action(window.listener_for(&entity, InputBaseState::enter))
5334                    .on_action(window.listener_for(&entity, InputBaseState::escape))
5335                    .on_action(window.listener_for(&entity, InputBaseState::paste))
5336                    .on_action(window.listener_for(&entity, InputBaseState::cut))
5337                    .on_action(window.listener_for(&entity, InputBaseState::undo))
5338                    .on_action(window.listener_for(&entity, InputBaseState::redo))
5339                    .when(self.is_multi_line(), |this| {
5340                        this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
5341                            .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
5342                            .on_action(window.listener_for(&entity, InputBaseState::indent_block))
5343                            .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
5344                    })
5345            })
5346            .on_action(window.listener_for(&entity, InputBaseState::left))
5347            .on_action(window.listener_for(&entity, InputBaseState::right))
5348            .on_action(window.listener_for(&entity, InputBaseState::select_left))
5349            .on_action(window.listener_for(&entity, InputBaseState::select_right))
5350            .when(self.is_multi_line(), |this| {
5351                this.on_action(window.listener_for(&entity, InputBaseState::up))
5352                    .on_action(window.listener_for(&entity, InputBaseState::down))
5353                    .on_action(window.listener_for(&entity, InputBaseState::select_up))
5354                    .on_action(window.listener_for(&entity, InputBaseState::select_down))
5355                    .on_action(window.listener_for(&entity, InputBaseState::page_up))
5356                    .on_action(window.listener_for(&entity, InputBaseState::page_down))
5357                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
5358                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
5359            })
5360            .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
5361            .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
5362            .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
5363            .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
5364            .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
5365            .on_action(window.listener_for(&entity, InputBaseState::home))
5366            .on_action(window.listener_for(&entity, InputBaseState::end))
5367            .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
5368            .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
5369            .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
5370            .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
5371            .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
5372            .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
5373            .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
5374            .on_action({
5375                let entity = entity.clone();
5376                move |_: &ActivateToken, window, cx| {
5377                    let state = entity.read(cx);
5378                    let activation = state
5379                        .token_spans()
5380                        .iter()
5381                        .find(|span| span.range() == state.selected_range())
5382                        .and_then(|span| {
5383                            state.range_to_bounds(&span.range()).and_then(|bounds| {
5384                                state.token_activation(
5385                                    span.range().start,
5386                                    bounds,
5387                                    gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
5388                                        bounds,
5389                                        ..Default::default()
5390                                    }),
5391                                )
5392                            })
5393                        });
5394                    if let Some((listener, event)) = activation {
5395                        listener(&event, window, cx);
5396                    }
5397                }
5398            })
5399            .on_action(window.listener_for(&entity, InputBaseState::copy))
5400            .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
5401            .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
5402            .on_mouse_down(
5403                MouseButton::Left,
5404                window.listener_for(&entity, InputBaseState::on_mouse_down),
5405            )
5406            .on_mouse_down(
5407                MouseButton::Right,
5408                window.listener_for(&entity, InputBaseState::on_mouse_down),
5409            )
5410            .on_mouse_up(
5411                MouseButton::Left,
5412                window.listener_for(&entity, InputBaseState::on_mouse_up),
5413            )
5414            .on_mouse_up(
5415                MouseButton::Right,
5416                window.listener_for(&entity, InputBaseState::on_mouse_up),
5417            )
5418            .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
5419            .on_scroll(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
5420            .when(self.is_multi_line() && !self.disabled, |this| {
5421                this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
5422            })
5423            .when(!self.disabled, |this| {
5424                if self.is_multi_line() && window.modifiers().alt {
5425                    this.cursor_crosshair()
5426                } else {
5427                    this.cursor_text()
5428                }
5429            })
5430            .flex_1()
5431            // A single line fills the frame and sits at its vertical center,
5432            // so the frame needs no layout of its own to hold it. It is never
5433            // shorter than its line, though: this root clips (overflow-x
5434            // hidden clips both axes), and a frame whose padding leaves less
5435            // than a line, like Component's Input, would cut off descenders.
5436            .map(|this| {
5437                if self.is_multi_line() {
5438                    this.h_full()
5439                } else {
5440                    this.min_h_full().flex().items_center()
5441                }
5442            })
5443            .flex_grow_1()
5444            .overflow_x_hidden()
5445            .when(self.is_multi_line(), |this| {
5446                this.pt(self.editor_paddings.top)
5447                    .pr(self.editor_paddings.right)
5448                    .pb(self.editor_paddings.bottom)
5449                    .pl(self.editor_paddings.left)
5450            })
5451            .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
5452            .when(self.shows_scrollbar(), |this| {
5453                this.child(EditorScrollbar::new(entity.clone()))
5454            });
5455
5456        // Actions only one mode handles are registered by that mode, where
5457        // `Self` is concrete enough to name its own entity type.
5458        // Keep the dispatch binding when disabling a focused field so Tab can
5459        // leave, while excluding disabled fields from normal Tab entry.
5460        crate::a11y_disabled::A11yDisabled::new(
5461            M::register_actions(element, &entity, window),
5462            self.disabled,
5463        )
5464        .with_readonly(self.readonly)
5465        .with_validation(
5466            self.accessibility
5467                .as_ref()
5468                .is_some_and(|value| value.required),
5469            self.accessibility
5470                .as_ref()
5471                .is_some_and(|value| value.invalid),
5472        )
5473        .test_support()
5474        .track_focus(&self.focus_handle.clone().tab_stop(!self.disabled))
5475    }
5476}
5477
5478#[cfg(test)]
5479mod tests {
5480    use super::*;
5481
5482    #[gpui::test]
5483    fn native_input_node_tracks_readonly_state(cx: &mut TestAppContext) {
5484        use gpui::Element as _;
5485
5486        fn check<M: InputModeKind>(
5487            state: &mut InputBaseState<M>,
5488            window: &mut Window,
5489            cx: &mut Context<InputBaseState<M>>,
5490        ) {
5491            for readonly in [false, true, false] {
5492                state.set_readonly(readonly, cx);
5493                let element = state.render(window, cx).into_element();
5494                let mut node = gpui::accesskit::Node::new(element.a11y_role().unwrap());
5495                element.write_a11y_info(&mut node);
5496                assert_eq!(node.is_read_only(), readonly);
5497                assert!(!node.is_disabled());
5498                assert_eq!(
5499                    node.supports_action(gpui::AccessibleAction::SetValue),
5500                    !readonly
5501                );
5502            }
5503        }
5504
5505        cx.update(crate::init);
5506        let window = cx.add_empty_window();
5507        window.update(|window, cx| {
5508            let input = cx.new(|cx| {
5509                let mut state = crate::input::InputState::new(window, cx);
5510                state.set_accessibility(InputAccessibility::new(Some(gpui::Role::TextInput)));
5511                state
5512            });
5513            input.update(cx, |state, cx| check(state, window, cx));
5514
5515            let textarea = cx.new(|cx| {
5516                let mut state = crate::input::TextareaState::new(window, cx);
5517                state.set_accessibility(InputAccessibility::new(Some(
5518                    gpui::Role::MultilineTextInput,
5519                )));
5520                state
5521            });
5522            textarea.update(cx, |state, cx| check(state, window, cx));
5523        });
5524    }
5525
5526    #[gpui::test]
5527    fn test_set_value_waits_for_the_first_layout(cx: &mut TestAppContext) {
5528        cx.update(crate::init);
5529        let (state, cx) = cx.add_window_view(|window, cx| {
5530            let mut state = crate::input::InputState::new(window, cx);
5531            state.set_value("hello", window, cx);
5532            // Made outside drawing, the state only has a placeholder font to shape with.
5533            assert_eq!(state.display_map().wrap_row_count(), 0);
5534            state
5535        });
5536        cx.update(|window, cx| window.draw(cx).clear(cx));
5537        state.read_with(cx, |state, _| {
5538            assert_eq!(state.value(), "hello");
5539            assert_eq!(state.display_map().wrap_row_count(), 1);
5540        });
5541    }
5542
5543    #[gpui::test]
5544    fn accessibility_actions_recheck_live_editability(cx: &mut TestAppContext) {
5545        cx.update(crate::init);
5546        let (state, cx) = cx.add_window_view(|window, cx| {
5547            crate::input::InputState::new(window, cx).default_value("initial")
5548        });
5549        let changes = Rc::new(Cell::new(0));
5550        let observed = changes.clone();
5551        let _subscription = cx.update(|_, cx| {
5552            cx.subscribe(&state, move |_, event: &InputEvent, _| {
5553                if matches!(event, InputEvent::Change) {
5554                    observed.set(observed.get() + 1);
5555                }
5556            })
5557        });
5558        cx.update(|window, cx| {
5559            state.update(cx, |state, cx| {
5560                state.handle_accessibility_set_value(None, window, cx);
5561                state.handle_accessibility_focus(window, cx);
5562                assert!(state.focus_handle.is_focused(window));
5563            });
5564            window.draw(cx).clear(cx);
5565        });
5566        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5567        assert_eq!(changes.get(), 0);
5568
5569        let action = gpui::accesskit::ActionData::Value("updated🦀".into());
5570        cx.update(|window, cx| {
5571            state.update(cx, |state, cx| {
5572                state.handle_accessibility_set_value(Some(&action), window, cx)
5573            });
5574        });
5575        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5576        assert_eq!(changes.get(), 1);
5577        for disabled in [false, true] {
5578            cx.update(|window, cx| {
5579                window.blur(cx);
5580                state.update(cx, |state, cx| {
5581                    state.set_disabled(disabled, cx);
5582                    state.set_readonly(!disabled, cx);
5583                    state.handle_accessibility_focus(window, cx);
5584                    assert_eq!(state.focus_handle.is_focused(window), !disabled);
5585                    let rejected = gpui::accesskit::ActionData::Value("rejected".into());
5586                    state.handle_accessibility_set_value(Some(&rejected), window, cx);
5587                });
5588            });
5589            assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5590            assert_eq!(changes.get(), 1);
5591        }
5592        cx.update(|window, cx| {
5593            state.update(cx, |state, cx| {
5594                state.set_disabled(false, cx);
5595                state.set_readonly(false, cx);
5596                state.handle_accessibility_focus(window, cx);
5597            });
5598            window.draw(cx).clear(cx);
5599            window.dispatch_action(Box::new(Undo), cx);
5600        });
5601        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5602        cx.update(|window, cx| {
5603            state.update(cx, |state, cx| {
5604                state.set_masked(true, window, cx);
5605                state.handle_accessibility_set_value(Some(&action), window, cx);
5606            });
5607        });
5608        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5609    }
5610
5611    #[gpui::test]
5612    fn accessibility_set_value_preserves_exact_editor_text(cx: &mut TestAppContext) {
5613        cx.update(crate::init);
5614        let (editor, cx) = cx.add_window_view(|window, cx| {
5615            crate::input::EditorState::new(window, cx).language("rust")
5616        });
5617        let action = gpui::accesskit::ActionData::Value("(".into());
5618        cx.update(|window, cx| {
5619            editor.update(cx, |editor, cx| {
5620                editor.handle_accessibility_set_value(Some(&action), window, cx)
5621            });
5622        });
5623        assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "(");
5624    }
5625
5626    #[gpui::test]
5627    fn revealing_a_password_keeps_text_assistance_disabled(cx: &mut TestAppContext) {
5628        cx.update(crate::init);
5629        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5630            let state = cx.new(|cx| crate::input::InputState::new(window, cx).masked(true));
5631            let hidden = state.read(cx).text_input_configuration();
5632            assert!(!hidden.autocorrect && !hidden.suggestions);
5633            assert_eq!(hidden.autocapitalize, Autocapitalize::None);
5634
5635            // The component's reveal button uses this same state transition.
5636            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5637            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5638            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5639            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5640            gpui::EmptyView
5641        });
5642    }
5643
5644    #[gpui::test]
5645    fn text_input_configuration_follows_the_input(cx: &mut TestAppContext) {
5646        use crate::input::{InputState, TextareaState};
5647
5648        cx.update(crate::init);
5649        let mut states = None;
5650        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5651            states = Some((
5652                cx.new(|cx| InputState::new(window, cx)),
5653                cx.new(|cx| InputState::new(window, cx).masked(true)),
5654                cx.new(|cx| TextareaState::new(window, cx)),
5655                cx.new(|cx| {
5656                    InputState::new(window, cx)
5657                        .input_action(TextInputAction::Search)
5658                        .autocorrect(true)
5659                        .autocapitalize(Autocapitalize::Words)
5660                }),
5661            ));
5662            gpui::EmptyView
5663        });
5664        let (plain, masked, textarea, search) = states.unwrap();
5665
5666        cx.read(|cx| {
5667            assert_eq!(
5668                plain.read(cx).text_input_configuration(),
5669                TextInputConfiguration {
5670                    input_action: TextInputAction::Done,
5671                    ..Default::default()
5672                }
5673            );
5674            assert_eq!(
5675                masked.read(cx).text_input_configuration(),
5676                TextInputConfiguration {
5677                    input_action: TextInputAction::Done,
5678                    ..Default::default()
5679                }
5680            );
5681            assert_eq!(
5682                textarea.read(cx).text_input_configuration(),
5683                TextInputConfiguration {
5684                    input_action: TextInputAction::Enter,
5685                    ..Default::default()
5686                }
5687            );
5688            let search = search.read(cx).text_input_configuration();
5689            assert_eq!(search.input_action, TextInputAction::Search);
5690            assert_eq!(search.autocapitalize, Autocapitalize::Words);
5691            assert!(search.autocorrect);
5692            assert!(search.suggestions);
5693        });
5694    }
5695
5696    #[gpui::test]
5697    fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) {
5698        use crate::input::{CompletionProvider, EditorState};
5699        use gpui::Task;
5700        use lsp_types::{CompletionContext, CompletionResponse};
5701        use std::cell::RefCell;
5702
5703        #[derive(Default)]
5704        struct Provider {
5705            starts: RefCell<Vec<usize>>,
5706            queries: RefCell<Vec<(usize, String)>>,
5707        }
5708
5709        impl CompletionProvider for Provider {
5710            fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
5711                self.starts.borrow_mut().push(offset);
5712                true
5713            }
5714
5715            fn completions(
5716                &self,
5717                _: &Rope,
5718                offset: usize,
5719                trigger: CompletionContext,
5720                _: &mut Window,
5721                _: &mut App,
5722            ) -> Task<anyhow::Result<CompletionResponse>> {
5723                self.queries
5724                    .borrow_mut()
5725                    .push((offset, trigger.trigger_character.unwrap()));
5726                Task::ready(Ok(CompletionResponse::Array(vec![])))
5727            }
5728        }
5729
5730        cx.update(crate::init);
5731        let mut editor = None;
5732        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5733            editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
5734            gpui::EmptyView
5735        });
5736        let editor = editor.unwrap();
5737        let provider = Rc::new(Provider::default());
5738        window
5739            .update(cx, |_, window, cx| {
5740                editor.update(cx, |state, cx| {
5741                    state.extras.lsp.completion_provider = Some(provider.clone());
5742                    state
5743                        .extras
5744                        .context_menu_content
5745                        .completion
5746                        .trigger_start_offset = Some(0);
5747                    state.extras.context_menu_content.completion.query = "aa".into();
5748                    state.set_cursor_to(1);
5749                    state.add_cursor_at(0, cx);
5750
5751                    state.replace_text_in_range(None, "中", window, cx);
5752
5753                    assert_eq!(state.value(), "中a中a");
5754                    assert_eq!(provider.starts.borrow().as_slice(), &[4]);
5755                    assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
5756                });
5757            })
5758            .unwrap();
5759    }
5760
5761    #[gpui::test]
5762    fn selected_range_restores_unicode_direction_without_splitting_characters(
5763        cx: &mut TestAppContext,
5764    ) {
5765        use crate::input::EditorState;
5766        cx.update(crate::init);
5767        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5768            let _state = cx.new(|cx| {
5769                let mut state = EditorState::new(window, cx).default_value("中😀a");
5770                state.set_selected_range_with_direction(3..8, true, cx);
5771                let selected = state.selected_text_range(false, window, cx).unwrap();
5772                assert_eq!(selected.range, 1..4);
5773                assert!(selected.reversed);
5774                assert_eq!(state.selected_range(), 3..8);
5775                assert!(state.is_selection_reversed());
5776                let range = state.selected_range();
5777                let reversed = state.is_selection_reversed();
5778                state.set_selected_range_with_direction(range, reversed, cx);
5779                assert!(state.is_selection_reversed());
5780                state.set_selected_range(3..8, cx);
5781                let selected = state.selected_text_range(false, window, cx).unwrap();
5782                assert_eq!(selected.range, 1..4);
5783                assert!(!selected.reversed);
5784                assert!(!state.is_selection_reversed());
5785                // A reversed Rust Range remains empty for existing callers.
5786                state.set_selected_range(Range { start: 8, end: 3 }, cx);
5787                assert_eq!(state.selected_range(), 8..8);
5788                assert!(!state.is_selection_reversed());
5789                state.set_selected_range_with_direction(4..4, true, cx);
5790                assert!(!state.is_selection_reversed());
5791                assert_eq!(
5792                    state.selected_text_range(false, window, cx).unwrap().range,
5793                    1..1
5794                );
5795                state
5796            });
5797            gpui::EmptyView
5798        });
5799    }
5800
5801    #[gpui::test]
5802    fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
5803        use crate::input::{InlineToken, InlineTokenPresentation};
5804        let width = Rc::new(Cell::new(4000.));
5805        let render_width = width.clone();
5806        let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
5807        view.window_handle
5808            .update(cx, |_, window, cx| {
5809                view.input.update(cx, |state, cx| {
5810                    state
5811                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
5812                        .unwrap();
5813                    state
5814                        .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
5815                        .unwrap();
5816                    state.set_token_presentation(
5817                        InlineTokenPresentation::default()
5818                            .token(move |_, _, _| div().w(px(render_width.get()))),
5819                    );
5820                });
5821            })
5822            .unwrap();
5823        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5824        visual.update(|window, cx| window.draw(cx).clear(cx));
5825        view.input.read_with(&visual, |state, _| {
5826            assert_eq!(state.display_map.wrap_row_count(), 2);
5827            let first = state.range_to_bounds(&(0..2)).unwrap();
5828            let second = state.range_to_bounds(&(2..4)).unwrap();
5829            assert!(second.origin.y > first.origin.y);
5830            assert_eq!(
5831                state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
5832                2
5833            );
5834        });
5835        width.set(100.);
5836        view.input.update(&mut visual, |_, cx| cx.notify());
5837        visual.update(|window, cx| window.draw(cx).clear(cx));
5838        view.input.read_with(&visual, |state, _| {
5839            assert_eq!(state.display_map.wrap_row_count(), 1)
5840        });
5841    }
5842
5843    #[gpui::test]
5844    fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
5845        use crate::input::{InlineToken, InlineTokenPresentation};
5846        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5847        let target = view.input.clone();
5848        view.window_handle
5849            .update(cx, |_, window, cx| {
5850                view.input.update(cx, |state, cx| {
5851                    state
5852                        .replace_range_with_token(
5853                            7..13,
5854                            InlineToken::new("a", "@alice"),
5855                            window,
5856                            cx,
5857                        )
5858                        .unwrap();
5859                    state.set_token_presentation(
5860                        InlineTokenPresentation::default()
5861                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5862                            .on_token_click(move |_, window, cx| {
5863                                target.update(cx, |state, cx| {
5864                                    state.set_value("activated", window, cx)
5865                                })
5866                            }),
5867                    );
5868                    state.focus(window, cx);
5869                    state.set_selected_range(7..13, cx);
5870                });
5871            })
5872            .unwrap();
5873        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5874        visual.update(|window, cx| window.draw(cx).clear(cx));
5875        visual.update(|window, cx| {
5876            let state = view.input.read(cx);
5877            let bounds = state.range_to_bounds(&(7..13)).unwrap();
5878            assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
5879            let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
5880            let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
5881            assert_eq!((left, right), (7, 13));
5882            window.dispatch_action(Box::new(ActivateToken), cx);
5883        });
5884        visual.run_until_parked();
5885        view.input.read_with(&visual, |state, _| {
5886            assert_eq!(state.value().as_ref(), "activated")
5887        });
5888    }
5889
5890    #[gpui::test]
5891    fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
5892        use crate::input::InlineToken;
5893        cx.update(crate::init);
5894        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5895        view.window_handle
5896            .update(cx, |_, window, cx| {
5897                view.input.update(cx, |state, cx| {
5898                    state
5899                        .replace_range_with_token(
5900                            7..13,
5901                            InlineToken::new("a", "@alice"),
5902                            window,
5903                            cx,
5904                        )
5905                        .unwrap();
5906                    state.set_selected_range(0..0, cx);
5907                });
5908            })
5909            .unwrap();
5910        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5911        visual.update(|window, cx| window.draw(cx).clear(cx));
5912        let bounds = view
5913            .input
5914            .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
5915        visual.simulate_click(bounds.center(), gpui::Modifiers::default());
5916        visual.run_until_parked();
5917        view.input.read_with(&visual, |state, _| {
5918            assert_eq!(state.selected_range(), 7..13, "a click selects the token");
5919        });
5920    }
5921
5922    #[gpui::test]
5923    fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) {
5924        use crate::input::{InlineToken, InlineTokenPresentation};
5925        use gpui::{Bounds, point, px, size};
5926        cx.update(crate::init);
5927        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5928        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
5929        view.window_handle
5930            .update(cx, |_, window, cx| {
5931                view.input.update(cx, |state, cx| {
5932                    state
5933                        .replace_range_with_token(
5934                            7..13,
5935                            InlineToken::new("a", "@alice"),
5936                            window,
5937                            cx,
5938                        )
5939                        .unwrap();
5940                    state.set_token_presentation(
5941                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
5942                    );
5943                    state.set_selected_range(0..0, cx);
5944                });
5945            })
5946            .unwrap();
5947        view.window_handle
5948            .update(cx, |_, _, cx| {
5949                view.input.update(cx, |state, _| {
5950                    let (_, entered) = state
5951                        .token_hover(7, bounds, true, None)
5952                        .expect("hover enters an enabled token");
5953                    assert!(entered.is_hovered());
5954                    assert_eq!(entered.token().id().as_ref(), "a");
5955                    assert_eq!(entered.range(), 7..13);
5956                    assert_eq!(entered.bounds(), bounds);
5957                    let (_, left) = state
5958                        .token_hover(7, bounds, false, None)
5959                        .expect("hover leaves the same token");
5960                    assert!(!left.is_hovered());
5961                    assert_eq!(state.selected_range(), 0..0, "hover never selects");
5962                    assert!(state.token_hover(99, bounds, true, None).is_none());
5963                });
5964            })
5965            .unwrap();
5966
5967        // Disabled tokens suppress hover, matching click; readonly allows it.
5968        view.window_handle
5969            .update(cx, |_, _, cx| {
5970                view.input.update(cx, |state, cx| {
5971                    state.set_disabled(true, cx);
5972                });
5973            })
5974            .unwrap();
5975        view.window_handle
5976            .update(cx, |_, _, cx| {
5977                view.input.update(cx, |state, _| {
5978                    assert!(state.token_hover(7, bounds, true, None).is_none())
5979                })
5980            })
5981            .unwrap();
5982        view.window_handle
5983            .update(cx, |_, _, cx| {
5984                view.input.update(cx, |state, cx| {
5985                    state.set_disabled(false, cx);
5986                    state.set_readonly(true, cx);
5987                });
5988            })
5989            .unwrap();
5990        view.window_handle
5991            .update(cx, |_, _, cx| {
5992                view.input.update(cx, |state, _| {
5993                    assert!(state.token_hover(7, bounds, true, None).is_some())
5994                })
5995            })
5996            .unwrap();
5997
5998        // Without a hover listener there is no hover activation.
5999        view.window_handle
6000            .update(cx, |_, _, cx| {
6001                view.input.update(cx, |state, _| {
6002                    state.set_token_presentation(InlineTokenPresentation::default());
6003                });
6004            })
6005            .unwrap();
6006        view.window_handle
6007            .update(cx, |_, _, cx| {
6008                view.input.update(cx, |state, _| {
6009                    assert!(state.token_hover(7, bounds, true, None).is_none())
6010                })
6011            })
6012            .unwrap();
6013    }
6014
6015    #[gpui::test]
6016    fn test_inline_token_hover_exit_delivered_when_token_removed(cx: &mut TestAppContext) {
6017        use crate::input::{InlineToken, InlineTokenPresentation};
6018        use std::cell::RefCell;
6019        use std::rc::Rc;
6020        cx.update(crate::init);
6021        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6022        let events: Rc<RefCell<Vec<(SharedString, bool)>>> = Rc::new(RefCell::new(Vec::new()));
6023        let sink = events.clone();
6024        view.window_handle
6025            .update(cx, |_, window, cx| {
6026                view.input.update(cx, |state, cx| {
6027                    state
6028                        .replace_range_with_token(
6029                            7..13,
6030                            InlineToken::new("a", "@alice"),
6031                            window,
6032                            cx,
6033                        )
6034                        .unwrap();
6035                    state.set_token_presentation(
6036                        InlineTokenPresentation::default()
6037                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6038                            .on_token_hover(move |event, _, _| {
6039                                sink.borrow_mut()
6040                                    .push((event.token().id().clone(), event.is_hovered()));
6041                            }),
6042                    );
6043                });
6044            })
6045            .unwrap();
6046        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6047        visual.update(|window, cx| window.draw(cx).clear(cx));
6048        let known_bounds = view.input.read_with(&visual, |state, _| {
6049            state
6050                .token_bounds
6051                .get(&7)
6052                .copied()
6053                .expect("placed token bounds")
6054        });
6055        visual.simulate_mouse_move(known_bounds.center(), None, gpui::Modifiers::default());
6056        visual.run_until_parked();
6057        visual.update(|window, cx| window.draw(cx).clear(cx));
6058        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6059
6060        // Remove the token while the pointer is still over its stale row: the
6061        // exit must fire even though the token element that owns the hover
6062        // mask is gone.
6063        view.window_handle
6064            .update(cx, |_, window, cx| {
6065                view.input
6066                    .update(cx, |state, cx| state.set_value("no tokens", window, cx));
6067            })
6068            .unwrap();
6069        visual.run_until_parked();
6070        visual.update(|window, cx| window.draw(cx).clear(cx));
6071        assert_eq!(
6072            events.borrow().as_slice(),
6073            &[("a".into(), true), ("a".into(), false)]
6074        );
6075    }
6076
6077    #[gpui::test]
6078    fn test_inline_token_hover_bounds_stay_single_row_at_wrap_boundary(cx: &mut TestAppContext) {
6079        use crate::input::{InlineToken, InlineTokenPresentation};
6080        cx.update(crate::init);
6081        let view = InputView::build_textarea(cx, |state| {
6082            state
6083                .rows(4)
6084                .default_value("aaaa bbbb cccc dddd @alice eeee ffff")
6085        });
6086        view.window_handle
6087            .update(cx, |_, window, cx| {
6088                view.input.update(cx, |state, cx| {
6089                    state
6090                        .replace_range_with_token(
6091                            20..26,
6092                            InlineToken::new("a", "@alice"),
6093                            window,
6094                            cx,
6095                        )
6096                        .unwrap();
6097                    state.set_token_presentation(
6098                        InlineTokenPresentation::default()
6099                            .token(|_, _, _| div().w(px(60.)).h(px(20.))),
6100                    );
6101                });
6102            })
6103            .unwrap();
6104        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6105        visual.update(|window, cx| window.draw(cx).clear(cx));
6106        let (placed, ranged, line_height) = view.input.read_with(&visual, |state, _| {
6107            (
6108                state
6109                    .token_bounds
6110                    .get(&20)
6111                    .copied()
6112                    .expect("placed token bounds"),
6113                state.range_to_bounds(&(20..26)),
6114                state.last_layout.as_ref().unwrap().line_height,
6115            )
6116        });
6117        // The laid-out element always occupies exactly one row of height, even
6118        // when the range-extent path resolves the same end boundary onto the
6119        // next visual row at a soft-wrap edge.
6120        assert!(placed.size.height <= line_height + px(1.), "{placed:?}");
6121        assert!(
6122            placed.size.width <= px(61.) && placed.size.width > px(0.),
6123            "{placed:?}"
6124        );
6125        if let Some(ranged) = ranged {
6126            assert!(
6127                ranged.size.height >= placed.size.height - px(1.),
6128                "{ranged:?} vs {placed:?}"
6129            );
6130        }
6131    }
6132
6133    #[gpui::test]
6134    fn test_inline_token_hover_same_offset_replacement_exits_predecessor(cx: &mut TestAppContext) {
6135        use crate::input::{InlineToken, InlineTokenPresentation};
6136        use std::{cell::RefCell, rc::Rc};
6137        cx.update(crate::init);
6138        let view = InputView::build(cx, |state| state.default_value("@alice!"));
6139        let events = Rc::new(RefCell::new(Vec::new()));
6140        let sink = events.clone();
6141        view.window_handle
6142            .update(cx, |_, window, cx| {
6143                view.input.update(cx, |state, cx| {
6144                    state
6145                        .replace_range_with_token(0..6, InlineToken::new("a", "@alice"), window, cx)
6146                        .unwrap();
6147                    state.set_token_presentation(
6148                        InlineTokenPresentation::default()
6149                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6150                            .on_token_hover(move |event, _, _| {
6151                                sink.borrow_mut()
6152                                    .push((event.token().id().clone(), event.is_hovered()));
6153                            }),
6154                    );
6155                });
6156            })
6157            .unwrap();
6158        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6159        visual.update(|window, cx| window.draw(cx).clear(cx));
6160        let bounds = view
6161            .input
6162            .read_with(&visual, |state, _| state.token_bounds[&0]);
6163        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6164        visual.run_until_parked();
6165        visual.update(|window, cx| window.draw(cx).clear(cx));
6166        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6167
6168        view.window_handle
6169            .update(cx, |_, window, cx| {
6170                view.input.update(cx, |state, cx| {
6171                    state
6172                        .replace_range_with_token(0..6, InlineToken::new("b", "@alice"), window, cx)
6173                        .unwrap();
6174                });
6175            })
6176            .unwrap();
6177        visual.run_until_parked();
6178        visual.update(|window, cx| window.draw(cx).clear(cx));
6179        visual.simulate_mouse_move(
6180            bounds.center() + gpui::point(px(1.), px(0.)),
6181            None,
6182            gpui::Modifiers::default(),
6183        );
6184        visual.run_until_parked();
6185        visual.update(|window, cx| window.draw(cx).clear(cx));
6186        assert_eq!(
6187            events.borrow().as_slice(),
6188            &[("a".into(), true), ("a".into(), false), ("b".into(), true)]
6189        );
6190        // Disabling keeps the token mounted; re-enabling must reset GPUI's
6191        // retained hover state even with a stationary pointer.
6192        view.input
6193            .update(&mut visual, |state, cx| state.set_disabled(true, cx));
6194        visual.update(|window, cx| window.draw(cx).clear(cx));
6195        visual.run_until_parked();
6196        assert_eq!(events.borrow().last(), Some(&("b".into(), false)));
6197        view.input
6198            .update(&mut visual, |state, cx| state.set_disabled(false, cx));
6199        visual.update(|window, cx| window.draw(cx).clear(cx));
6200        visual.run_until_parked();
6201        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6202        visual.run_until_parked();
6203        assert_eq!(
6204            events.borrow().as_slice(),
6205            &[
6206                ("a".into(), true),
6207                ("a".into(), false),
6208                ("b".into(), true),
6209                ("b".into(), false),
6210                ("b".into(), true)
6211            ]
6212        );
6213        visual.simulate_mouse_move(
6214            bounds.bottom_right() + gpui::point(px(10.), px(10.)),
6215            None,
6216            gpui::Modifiers::default(),
6217        );
6218        visual.run_until_parked();
6219        assert_eq!(
6220            events.borrow().as_slice(),
6221            &[
6222                ("a".into(), true),
6223                ("a".into(), false),
6224                ("b".into(), true),
6225                ("b".into(), false),
6226                ("b".into(), true),
6227                ("b".into(), false)
6228            ]
6229        );
6230    }
6231
6232    #[gpui::test]
6233    fn test_inline_token_hover_older_exit_keeps_newer_snapshot(cx: &mut TestAppContext) {
6234        use crate::input::{InlineToken, InlineTokenPresentation};
6235        use gpui::{Bounds, point, px, size};
6236        cx.update(crate::init);
6237        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6238        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6239        view.window_handle
6240            .update(cx, |_, window, cx| {
6241                view.input.update(cx, |state, cx| {
6242                    state
6243                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6244                        .unwrap();
6245                    state
6246                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6247                        .unwrap();
6248                    state.set_token_presentation(
6249                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6250                    );
6251                    // The pointer moves A -> B; GPUI dispatches B's enter
6252                    // before A's exit.
6253                    state
6254                        .token_hover(0, bounds, true, None)
6255                        .expect("hover enters A");
6256                    state
6257                        .token_hover(3, bounds, true, None)
6258                        .expect("hover enters B");
6259                    let (_, exit_a) = state.token_hover(0, bounds, false, None).expect("A exits");
6260                    assert!(!exit_a.is_hovered());
6261                    // B's snapshot must survive A's late exit.
6262                    assert_eq!(
6263                        state
6264                            .hovered_token
6265                            .as_ref()
6266                            .expect("B still hovered")
6267                            .span
6268                            .token()
6269                            .id()
6270                            .as_ref(),
6271                        "b"
6272                    );
6273                    // Removing B afterwards still produces B's reconciled exit.
6274                    state.set_value("no tokens", window, cx);
6275                    state.token_bounds.clear();
6276                    let (listener, exit_b) = state.reconcile_token_hover().expect("B must exit");
6277                    assert!(!exit_b.is_hovered());
6278                    assert_eq!(exit_b.token().id().as_ref(), "b");
6279                    drop(listener);
6280                });
6281            })
6282            .unwrap();
6283    }
6284
6285    #[gpui::test]
6286    fn test_inline_token_hover_late_exit_matches_replaced_token(cx: &mut TestAppContext) {
6287        use crate::input::{InlineToken, InlineTokenPresentation};
6288        cx.update(crate::init);
6289        let view = InputView::build(cx, |state| state.default_value("@a"));
6290        view.window_handle
6291            .update(cx, |_, window, cx| {
6292                view.input.update(cx, |state, cx| {
6293                    let a = InlineToken::new("a", "@a");
6294                    let b = InlineToken::new("b", "@a");
6295                    state
6296                        .replace_range_with_token(0..2, a.clone(), window, cx)
6297                        .unwrap();
6298                    state.set_token_presentation(
6299                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6300                    );
6301                    let bounds = gpui::Bounds::default();
6302                    state.token_hover(0, bounds, true, Some(&a)).unwrap();
6303                    state
6304                        .replace_range_with_token(0..2, b.clone(), window, cx)
6305                        .unwrap();
6306                    state.token_hover(0, bounds, true, Some(&b)).unwrap();
6307                    let (_, exit_a) = state.token_hover(0, bounds, false, Some(&a)).unwrap();
6308                    assert_eq!(exit_a.token().id().as_ref(), "a");
6309                    assert_eq!(state.hovered_token.as_ref().unwrap().span.token(), &b);
6310                    let (_, exit_b) = state.token_hover(0, bounds, false, Some(&b)).unwrap();
6311                    assert_eq!(exit_b.token().id().as_ref(), "b");
6312                    assert!(state.pending_token_hover_exits.is_empty());
6313                });
6314            })
6315            .unwrap();
6316    }
6317
6318    #[gpui::test]
6319    fn test_inline_token_hover_exit_keeps_entry_utf16_after_edit(cx: &mut TestAppContext) {
6320        use crate::input::{InlineToken, InlineTokenPresentation};
6321        use gpui::EntityInputHandler as _;
6322        cx.update(crate::init);
6323        let view = InputView::build(cx, |state| state.default_value("🙂 @a"));
6324        view.window_handle
6325            .update(cx, |_, window, cx| {
6326                view.input.update(cx, |state, cx| {
6327                    state
6328                        .replace_range_with_token(5..7, InlineToken::new("a", "@a"), window, cx)
6329                        .unwrap();
6330                    state.set_token_presentation(
6331                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6332                    );
6333                    let bounds = gpui::Bounds::default();
6334                    let (_, enter) = state.token_hover(5, bounds, true, None).unwrap();
6335                    assert_eq!(enter.range_utf16(), (3, 5));
6336                    state.replace_text_in_range(Some(0..2), "abcd", window, cx);
6337                    assert_eq!(state.token_spans()[0].range(), 5..7);
6338                    let (_, exit) = state.token_hover(5, bounds, false, None).unwrap();
6339                    assert_eq!(exit.range_utf16(), (3, 5));
6340                });
6341            })
6342            .unwrap();
6343    }
6344
6345    #[gpui::test]
6346    fn test_set_selected_text_range(cx: &mut TestAppContext) {
6347        use gpui::EntityInputHandler as _;
6348        cx.update(crate::init);
6349        // "🙂" is 2 UTF-16 units and 4 bytes.
6350        let view = InputView::build(cx, |state| state.default_value("🙂 hello world"));
6351        view.window_handle
6352            .update(cx, |_, window, cx| {
6353                view.input.update(cx, |state, cx| {
6354                    fn selection(
6355                        state: &mut InputBaseState<InputMode>,
6356                        window: &mut Window,
6357                        cx: &mut Context<InputBaseState<InputMode>>,
6358                    ) -> (Range<usize>, bool) {
6359                        let selection = state.selected_text_range(false, window, cx).unwrap();
6360                        (selection.range, selection.reversed)
6361                    }
6362
6363                    state.set_selected_text_range(3..8, window, cx);
6364                    assert_eq!(state.selected_range(), 5..10);
6365                    assert_eq!(selection(state, window, cx), (3..8, false));
6366
6367                    // Dragging the end handle keeps the selection forward.
6368                    state.set_selected_text_range(3..14, window, cx);
6369                    assert_eq!(selection(state, window, cx), (3..14, false));
6370                    assert_eq!(state.cursor(), 16);
6371
6372                    // Dragging the start handle reverses it, so the start is the cursor.
6373                    state.set_selected_text_range(9..14, window, cx);
6374                    assert_eq!(selection(state, window, cx), (9..14, true));
6375                    assert_eq!(state.cursor(), 11);
6376
6377                    // A repeated range keeps its direction.
6378                    state.set_selected_text_range(9..14, window, cx);
6379                    assert_eq!(selection(state, window, cx), (9..14, true));
6380
6381                    // Out of range clamps; a backwards range is normalized.
6382                    state.set_selected_text_range(100..9, window, cx);
6383                    assert_eq!(selection(state, window, cx), (9..14, true));
6384
6385                    // Either handle can cross the stationary end.
6386                    state.set_selected_text_range(3..8, window, cx);
6387                    state.set_selected_text_range(2..3, window, cx);
6388                    assert_eq!(selection(state, window, cx), (2..3, true));
6389                    assert_eq!(state.cursor(), 4);
6390                    state.set_selected_text_range(3..8, window, cx);
6391                    state.set_selected_text_range(8..9, window, cx);
6392                    assert_eq!(selection(state, window, cx), (8..9, false));
6393                    assert_eq!(state.cursor(), 11);
6394
6395                    // Collapsing places a forward cursor and leaves the text alone.
6396                    state.set_selected_text_range(2..2, window, cx);
6397                    assert_eq!(selection(state, window, cx), (2..2, false));
6398                    assert_eq!(state.value(), "🙂 hello world");
6399                });
6400            })
6401            .unwrap();
6402    }
6403
6404    #[gpui::test]
6405    fn test_inline_token_hover_callback_edit_preserves_both_exits(cx: &mut TestAppContext) {
6406        use crate::input::{InlineToken, InlineTokenPresentation};
6407        cx.update(crate::init);
6408        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6409        view.window_handle
6410            .update(cx, |_, window, cx| {
6411                view.input.update(cx, |state, cx| {
6412                    state
6413                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6414                        .unwrap();
6415                    state
6416                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6417                        .unwrap();
6418                    state.set_token_presentation(
6419                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6420                    );
6421                    let bounds = gpui::Bounds::default();
6422                    state.token_hover(0, bounds, true, None).unwrap();
6423                    state.token_hover(3, bounds, true, None).unwrap();
6424                    // Model an edit in B's enter callback before A's queued exit.
6425                    state.set_value("gone", window, cx);
6426                    let (_, exit_a) = state.token_hover(0, bounds, false, None).unwrap();
6427                    assert_eq!(exit_a.token().id().as_ref(), "a");
6428                    let (_, exit_b) = state.reconcile_token_hover().unwrap();
6429                    assert_eq!(exit_b.token().id().as_ref(), "b");
6430                    assert!(state.token_hover(0, bounds, false, None).is_none());
6431                    assert!(state.reconcile_token_hover().is_none());
6432                });
6433            })
6434            .unwrap();
6435    }
6436
6437    #[gpui::test]
6438    fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
6439        let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
6440        view.window_handle
6441            .update(cx, |_, window, cx| {
6442                view.input.update(cx, |state, cx| {
6443                    let token =
6444                        crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
6445                    state
6446                        .replace_range_with_token(4..10, token.clone(), window, cx)
6447                        .unwrap();
6448                    assert_eq!(state.value().as_ref(), "问 @alice!");
6449                    assert_eq!(state.tokens()[0].range(), 4..10);
6450                    assert_eq!(state.next_end_of_word_at(4), 10);
6451                    assert_eq!(state.previous_start_of_word_at(10), 4);
6452                    state.undo(&Undo, window, cx);
6453                    assert!(
6454                        state.tokens().is_empty(),
6455                        "identity-only association is undoable"
6456                    );
6457                    assert_eq!(state.value().as_ref(), "问 @alice!");
6458                    state.redo(&Redo, window, cx);
6459                    assert_eq!(state.tokens()[0].token(), &token);
6460                    state.set_selected_range(6..7, cx);
6461                    assert_eq!(state.selected_range(), 4..10);
6462                    state.replace("", window, cx);
6463                    assert_eq!(state.value().as_ref(), "问 !");
6464                    assert!(state.tokens().is_empty());
6465                    state.undo(&Undo, window, cx);
6466                    assert_eq!(state.tokens()[0].token(), &token);
6467                    state.set_selected_range(0..0, cx);
6468                    state.replace("🙂", window, cx);
6469                    assert_eq!(state.tokens()[0].range(), 8..14);
6470                    state.undo(&Undo, window, cx);
6471                    assert_eq!(state.tokens()[0].range(), 4..10);
6472                    let before = state.content();
6473                    state
6474                        .replace_range_with_token(0..0, token.clone(), window, cx)
6475                        .expect("the same reference may occur twice");
6476                    assert_eq!(state.value().as_ref(), "@alice问 @alice!");
6477                    assert_eq!(state.tokens().len(), 2);
6478                    assert_eq!(state.tokens()[1].token(), &token);
6479                    state.undo(&Undo, window, cx);
6480                    assert_eq!(state.content(), before);
6481                    state.set_value(before.text().clone(), window, cx);
6482                    assert!(state.tokens().is_empty());
6483                    assert!(!state.undo_manager.has_undos());
6484                });
6485            })
6486            .unwrap();
6487    }
6488
6489    #[gpui::test]
6490    fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
6491        use crate::input::{InlineToken, InlineTokenError, InputContent};
6492        let view = InputView::build_textarea(cx, |state| state);
6493        view.window_handle
6494            .update(cx, |_, window, cx| {
6495                view.input.update(cx, |state, cx| {
6496                    let content = InputContent::new("@a@b\n后面")
6497                        .with_token(0..2, InlineToken::new("a", "@a"))
6498                        .unwrap()
6499                        .with_token(2..4, InlineToken::new("b", "@b"))
6500                        .unwrap();
6501                    state.set_value(content.clone(), window, cx);
6502                    state.set_selected_range(2..2, cx);
6503                    assert_eq!(state.previous_boundary(2), 0);
6504                    assert_eq!(state.next_boundary(2), 4);
6505                    state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
6506                    assert_eq!(state.value().as_ref(), "中@b\n后面");
6507                    assert_eq!(state.tokens().len(), 1);
6508                    assert_eq!(
6509                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6510                        Err(InlineTokenError::CompositionActive)
6511                    );
6512                    state.replace_text_in_range(None, "中文", window, cx);
6513                    state.undo(&Undo, window, cx);
6514                    assert_eq!(state.content(), content);
6515                    state.redo(&Redo, window, cx);
6516                    assert_eq!(state.value().as_ref(), "中文@b\n后面");
6517                    state.undo(&Undo, window, cx);
6518                    state.replace_all("plain", window, cx);
6519                    assert!(state.tokens().is_empty());
6520                    state.undo(&Undo, window, cx);
6521                    assert_eq!(state.content(), content);
6522                });
6523            })
6524            .unwrap();
6525        let view = InputView::build(cx, |state| state);
6526        view.window_handle
6527            .update(cx, |_, window, cx| {
6528                view.input.update(cx, |state, cx| {
6529                    assert_eq!(
6530                        InputContent::new("a\u{301}")
6531                            .with_token(0..1, InlineToken::new("bad", "a"))
6532                            .err(),
6533                        Some(InlineTokenError::InvalidBoundary)
6534                    );
6535                    assert_eq!(
6536                        InputContent::new("@a@a")
6537                            .with_token(0..2, InlineToken::new("a", "@a"))
6538                            .unwrap()
6539                            .with_token(1..3, InlineToken::new("x", "a@"))
6540                            .err(),
6541                        Some(InlineTokenError::OverlappingTokens)
6542                    );
6543                    state
6544                        .replace_with_token(InlineToken::new("a", "@a"), window, cx)
6545                        .unwrap();
6546                    let before = state.content();
6547                    state.set_masked(true, window, cx);
6548                    assert!(!state.tokens_visible());
6549                    assert_eq!(
6550                        state.replace_with_token(InlineToken::new("b", "b"), window, cx),
6551                        Err(InlineTokenError::UnsupportedMode)
6552                    );
6553                    assert_eq!(state.content(), before);
6554                    state.undo(&Undo, window, cx);
6555                    assert!(state.tokens().is_empty());
6556                    state.redo(&Redo, window, cx);
6557                    assert_eq!(state.content(), before);
6558                    assert!(!state.tokens_visible());
6559                });
6560            })
6561            .unwrap();
6562    }
6563
6564    use crate::theme::Theme;
6565    use gpui::{TestAppContext, VisualTestContext, size};
6566
6567    use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TabSize, TextareaMode};
6568
6569    fn set_test_syntax_provider(
6570        provider: Rc<dyn crate::input::SyntaxContextProvider>,
6571        cx: &mut App,
6572    ) {
6573        struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
6574        impl crate::input::LanguageProvider for TestLanguages {
6575            fn syntax_context_provider(
6576                &self,
6577                _: &str,
6578            ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
6579                Some(self.0.clone())
6580            }
6581        }
6582        crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
6583    }
6584
6585    struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
6586
6587    impl<M: InputModeKind> Render for TestRoot<M> {
6588        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6589            div().size_full().child(self.0.clone())
6590        }
6591    }
6592
6593    struct InputView<M: InputModeKind> {
6594        input: Entity<InputBaseState<M>>,
6595        window_handle: gpui::WindowHandle<TestRoot<M>>,
6596    }
6597
6598    /// Helper to open a state of one mode in a window for testing.
6599    impl<M: InputModeKind> InputView<M> {
6600        fn build_with(
6601            cx: &mut TestAppContext,
6602            make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
6603            + 'static,
6604        ) -> Self {
6605            let mut input: Option<Entity<InputBaseState<M>>> = None;
6606
6607            let window = cx.update(|cx| {
6608                cx.open_window(Default::default(), |window, cx| {
6609                    // Set up the theme first
6610                    cx.set_global(Theme::default());
6611                    // Initialize input keybindings
6612                    super::super::init(cx);
6613
6614                    input = Some(cx.new(|cx| make(window, cx)));
6615
6616                    cx.new(|_| TestRoot(input.clone().unwrap()))
6617                })
6618                .unwrap()
6619            });
6620
6621            Self {
6622                input: input.clone().unwrap(),
6623                window_handle: window,
6624            }
6625        }
6626    }
6627
6628    impl InputView<EditorMode> {
6629        /// An editor state, for the tests that exercise code-editor behavior.
6630        fn new(cx: &mut TestAppContext) -> Self {
6631            Self::build_editor(cx, |state| state)
6632        }
6633
6634        fn build_editor(
6635            cx: &mut TestAppContext,
6636            f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
6637        ) -> Self {
6638            Self::build_with(cx, move |window, cx| {
6639                f(crate::input::EditorState::new(window, cx).language("sql"))
6640            })
6641        }
6642    }
6643
6644    impl InputView<TextareaMode> {
6645        fn build_textarea(
6646            cx: &mut TestAppContext,
6647            f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
6648        ) -> Self {
6649            Self::build_with(cx, move |window, cx| {
6650                f(crate::input::TextareaState::new(window, cx))
6651            })
6652        }
6653    }
6654
6655    impl InputView<InputMode> {
6656        /// A single-line state, the default these tests were written against.
6657        fn build(
6658            cx: &mut TestAppContext,
6659            f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
6660        ) -> Self {
6661            Self::build_with(cx, move |window, cx| {
6662                f(crate::input::InputState::new(window, cx))
6663            })
6664        }
6665    }
6666
6667    /// Sends one trackpad packet straight to the input.
6668    fn swipe<M: InputModeKind>(
6669        view: &InputView<M>,
6670        cx: &mut VisualTestContext,
6671        dy: f32,
6672        phase: gpui::TouchPhase,
6673    ) {
6674        cx.update(|window, cx| {
6675            view.input.update(cx, |state, cx| {
6676                state.on_scroll_wheel(
6677                    &ScrollEvent {
6678                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(dy))),
6679                        touch_phase: phase,
6680                        ..Default::default()
6681                    },
6682                    window,
6683                    cx,
6684                )
6685            })
6686        });
6687    }
6688
6689    fn long_text() -> String {
6690        (0..60)
6691            .map(|n| format!("line {n}"))
6692            .collect::<Vec<_>>()
6693            .join("\n")
6694    }
6695
6696    #[gpui::test]
6697    fn test_scroll_bounce_stretches_past_the_end_and_springs_back(cx: &mut TestAppContext) {
6698        use gpui::TouchPhase::{Ended, Moved, Started};
6699
6700        let view = InputView::build_textarea(cx, |state| {
6701            state.scroll_bounce(true).default_value(long_text())
6702        });
6703        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6704        cx.update(|window, cx| window.draw(cx).clear(cx));
6705        let drawn_at = |cx: &mut VisualTestContext| {
6706            view.input
6707                .read_with(cx, |state, _| state.last_bounds.unwrap().origin.y)
6708        };
6709
6710        swipe(&view, &mut cx, -20., Started);
6711        swipe(&view, &mut cx, -100_000., Moved);
6712        let (end, stretch) = view.input.read_with(&cx, |state, _| {
6713            (state.scroll_handle.offset().y, state.overscroll.offset())
6714        });
6715        assert!(end < px(0.), "the text scrolled to its end");
6716        assert!(stretch < 0., "the rest stretched the edge: {stretch}");
6717        cx.update(|window, cx| window.draw(cx).clear(cx));
6718        let stretched_at = drawn_at(&mut cx);
6719
6720        swipe(&view, &mut cx, 0., Ended);
6721        for _ in 0..120 {
6722            cx.executor()
6723                .advance_clock(std::time::Duration::from_millis(16));
6724            cx.update(|window, cx| window.draw(cx).clear(cx));
6725        }
6726        view.input.read_with(&cx, |state, _| {
6727            assert_eq!(state.overscroll.offset(), 0., "the edge sprang back");
6728            assert_eq!(
6729                state.scroll_handle.offset().y,
6730                end,
6731                "scrolling stayed exact"
6732            );
6733        });
6734        let moved = (stretched_at - drawn_at(&mut cx)).as_f32();
6735        assert!(
6736            (moved - stretch).abs() < 0.001,
6737            "the stretch only moved where the text was drawn: {moved} vs {stretch}"
6738        );
6739    }
6740
6741    /// Swipes far past the end of the text and returns where the text
6742    /// scrolled to and how far its edge stretched.
6743    fn swipe_past_the_end(
6744        view: &InputView<TextareaMode>,
6745        cx: &mut VisualTestContext,
6746    ) -> (Pixels, f32) {
6747        use gpui::TouchPhase::{Moved, Started};
6748
6749        cx.update(|window, cx| window.draw(cx).clear(cx));
6750        swipe(view, cx, -20., Started);
6751        swipe(view, cx, -100_000., Moved);
6752        view.input.read_with(cx, |state, _| {
6753            (state.scroll_handle.offset().y, state.overscroll.offset())
6754        })
6755    }
6756
6757    #[gpui::test]
6758    fn test_scroll_bounce_stays_put_under_reduced_motion(cx: &mut TestAppContext) {
6759        cx.update(|cx| cx.set_reduce_motion(true));
6760        let view = InputView::build_textarea(cx, |state| {
6761            state.scroll_bounce(true).default_value(long_text())
6762        });
6763        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6764        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6765        assert!(end < px(0.), "the text still scrolls");
6766        assert_eq!(stretch, 0., "the edge does not stretch");
6767    }
6768
6769    #[gpui::test]
6770    fn test_scroll_bounce_follows_the_platform_by_default(cx: &mut TestAppContext) {
6771        let view = InputView::build_textarea(cx, |state| state.default_value(long_text()));
6772        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6773        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6774        assert!(end < px(0.), "the text scrolls");
6775        assert_eq!(
6776            stretch != 0.,
6777            crate::ScrollBounce::enabled_by_default(),
6778            "the edge stretches where the platform's scroll views do"
6779        );
6780    }
6781
6782    #[gpui::test]
6783    fn test_scroll_bounce_leaves_text_that_fits(cx: &mut TestAppContext) {
6784        let view = InputView::build_textarea(cx, |state| {
6785            state.scroll_bounce(true).default_value("one line")
6786        });
6787        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6788        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6789        assert_eq!((end, stretch), (px(0.), 0.));
6790    }
6791
6792    #[gpui::test]
6793    fn test_scroll_bounce_resets_when_replacement_text_fits(cx: &mut TestAppContext) {
6794        let view = InputView::build_textarea(cx, |state| {
6795            state.scroll_bounce(true).default_value(long_text())
6796        });
6797        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6798        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6799        assert!(stretch < 0.);
6800        cx.update(|window, cx| {
6801            view.input
6802                .update(cx, |state, cx| state.set_value("short", window, cx));
6803            window.draw(cx).clear(cx);
6804        });
6805        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
6806        view.input.read_with(&cx, |state, _| {
6807            assert_eq!(state.overscroll.offset(), 0.);
6808            assert_eq!(state.scroll_handle.offset().y, px(0.));
6809        });
6810    }
6811
6812    #[gpui::test]
6813    fn test_scroll_bounce_releases_when_the_end_packet_is_horizontal(cx: &mut TestAppContext) {
6814        let view = InputView::build_textarea(cx, |state| {
6815            state.scroll_bounce(true).default_value(long_text())
6816        });
6817        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6818        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6819        assert!(stretch < 0.);
6820        cx.update(|window, cx| {
6821            view.input.update(cx, |state, cx| {
6822                state.on_scroll_wheel(
6823                    &ScrollEvent {
6824                        delta: gpui::ScrollDelta::Pixels(point(px(1.), px(0.))),
6825                        touch_phase: gpui::TouchPhase::Ended,
6826                        ..Default::default()
6827                    },
6828                    window,
6829                    cx,
6830                );
6831            });
6832        });
6833        for _ in 0..120 {
6834            cx.executor()
6835                .advance_clock(std::time::Duration::from_millis(16));
6836            cx.update(|window, cx| window.draw(cx).clear(cx));
6837        }
6838        assert_eq!(
6839            view.input
6840                .read_with(&cx, |state, _| state.overscroll.offset()),
6841            0.
6842        );
6843    }
6844
6845    #[gpui::test]
6846    fn test_scroll_bounce_ordinary_mouse_wheel_does_not_stretch(cx: &mut TestAppContext) {
6847        let view = InputView::build_textarea(cx, |state| {
6848            state.scroll_bounce(true).default_value(long_text())
6849        });
6850        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6851        cx.update(|window, cx| {
6852            window.draw(cx).clear(cx);
6853            view.input.update(cx, |state, cx| {
6854                state.on_scroll_wheel(
6855                    &ScrollEvent {
6856                        delta: gpui::ScrollDelta::Lines(point(0., -100_000.)),
6857                        touch_phase: gpui::TouchPhase::Moved,
6858                        ..Default::default()
6859                    },
6860                    window,
6861                    cx,
6862                );
6863                assert!(state.scroll_handle.offset().y < px(0.));
6864                assert_eq!(state.overscroll.offset(), 0.);
6865            });
6866        });
6867    }
6868
6869    #[gpui::test]
6870    fn test_scroll_bounce_new_wheel_input_interrupts_the_return(cx: &mut TestAppContext) {
6871        let view = InputView::build_textarea(cx, |state| {
6872            state.scroll_bounce(true).default_value(long_text())
6873        });
6874        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6875        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6876        assert!(stretch < 0.);
6877        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
6878        cx.executor()
6879            .advance_clock(std::time::Duration::from_millis(16));
6880        cx.update(|window, cx| {
6881            window.draw(cx).clear(cx);
6882            view.input.update(cx, |state, cx| {
6883                state.on_scroll_wheel(
6884                    &ScrollEvent {
6885                        delta: gpui::ScrollDelta::Lines(point(0., 2.)),
6886                        touch_phase: gpui::TouchPhase::Moved,
6887                        ..Default::default()
6888                    },
6889                    window,
6890                    cx,
6891                );
6892                assert!(state.scroll_handle.offset().y > end);
6893                assert_eq!(state.overscroll.offset(), 0.);
6894            });
6895        });
6896    }
6897
6898    #[gpui::test]
6899    fn test_turning_scroll_bounce_off_drops_the_stretch(cx: &mut TestAppContext) {
6900        let view = InputView::build_textarea(cx, |state| {
6901            state.scroll_bounce(true).default_value(long_text())
6902        });
6903        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6904        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6905        assert!(stretch < 0., "the edge stretched: {stretch}");
6906        view.input
6907            .update(&mut cx, |state, cx| state.set_scroll_bounce(false, cx));
6908        assert_eq!(
6909            view.input
6910                .read_with(&cx, |state, _| state.overscroll.offset()),
6911            0.
6912        );
6913    }
6914
6915    /// The frame is laid out by the application, which should not have to
6916    /// center a single line inside it.
6917    #[gpui::test]
6918    fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
6919        struct Frame(Entity<InputBaseState<InputMode>>);
6920        impl Render for Frame {
6921            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6922                crate::input::InputBase::new("frame")
6923                    .h(px(60.))
6924                    .child(crate::input::Input::new(&self.0))
6925            }
6926        }
6927
6928        cx.update(crate::init);
6929        let mut input = None;
6930        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6931            let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
6932            input = Some(state.clone());
6933            Frame(state)
6934        });
6935        let input = input.unwrap();
6936        let mut cx = VisualTestContext::from_window(window.into(), cx);
6937        cx.update(|window, cx| window.draw(cx).clear(cx));
6938
6939        input.read_with(&cx, |state, _| {
6940            let line = state.input_bounds;
6941            assert_eq!(line.center().y, px(30.), "line {line:?}");
6942        });
6943    }
6944
6945    #[gpui::test]
6946    fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
6947        use std::{cell::Cell, rc::Rc};
6948
6949        cx.update(crate::init);
6950        let mut input = None;
6951        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6952            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
6953            gpui::EmptyView
6954        });
6955        let input = input.unwrap();
6956        input.update(cx, |state, cx| {
6957            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
6958            state.scroll_size = size(px(100.), px(20.));
6959            state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
6960        });
6961        let notifications = Rc::new(Cell::new(0));
6962        let count = notifications.clone();
6963        let _subscription =
6964            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
6965
6966        window
6967            .update(cx, |_, window, cx| {
6968                input.update(cx, |state, cx| {
6969                    state.on_scroll_wheel(
6970                        &ScrollEvent {
6971                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
6972                            ..Default::default()
6973                        },
6974                        window,
6975                        cx,
6976                    );
6977                    assert_eq!(state.scroll_handle.offset(), Point::default());
6978                    assert!(state.diagnostic_popover().is_none());
6979                });
6980            })
6981            .unwrap();
6982        assert_eq!(
6983            notifications.get(),
6984            1,
6985            "clearing a diagnostic must notify even when scrolling is clamped"
6986        );
6987        window
6988            .update(cx, |_, window, cx| {
6989                input.update(cx, |state, cx| {
6990                    state.on_scroll_wheel(
6991                        &ScrollEvent {
6992                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
6993                            ..Default::default()
6994                        },
6995                        window,
6996                        cx,
6997                    );
6998                });
6999            })
7000            .unwrap();
7001        assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
7002    }
7003
7004    /// Hover must reach the whole visible editor after scrolling, not only
7005    /// the part that overlaps the unscrolled text bounds.
7006    #[gpui::test]
7007    fn test_hover_reaches_bottom_of_scrolled_editor(cx: &mut TestAppContext) {
7008        use crate::input::{Diagnostic, Position};
7009        struct Frame(Entity<crate::input::EditorState>);
7010        impl Render for Frame {
7011            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7012                crate::input::InputBase::new("frame")
7013                    .h(px(100.))
7014                    .child(crate::input::Editor::new(&self.0))
7015            }
7016        }
7017
7018        cx.update(crate::init);
7019        let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
7020        let mut input = None;
7021        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7022            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
7023            input = Some(state.clone());
7024            Frame(state)
7025        });
7026        let input = input.unwrap();
7027        let mut cx = VisualTestContext::from_window(window.into(), cx);
7028        input.update(&mut cx, |state, _| {
7029            state.diagnostics_mut().unwrap().push(Diagnostic::new(
7030                Position::new(0, 0)..Position::new(100, 0),
7031                "everywhere",
7032            ));
7033        });
7034        cx.update(|window, cx| window.draw(cx).clear(cx));
7035        cx.update(|window, cx| {
7036            input.update(cx, |state, cx| {
7037                state.on_scroll_wheel(
7038                    &ScrollEvent {
7039                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-400.))),
7040                        ..Default::default()
7041                    },
7042                    window,
7043                    cx,
7044                );
7045            })
7046        });
7047        cx.update(|window, cx| window.draw(cx).clear(cx));
7048
7049        let bounds = input.read_with(&cx, |state, _| state.input_bounds);
7050        cx.simulate_mouse_move(
7051            point(bounds.center().x, bounds.bottom() - px(5.)),
7052            None,
7053            gpui::Modifiers::default(),
7054        );
7055        assert!(
7056            input.read_with(&cx, |state, _| state.diagnostic_popover().is_some()),
7057            "no hover at the bottom of a scrolled editor, bounds {bounds:?}"
7058        );
7059    }
7060
7061    #[gpui::test]
7062    fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
7063        use std::{cell::Cell, rc::Rc};
7064        struct Panel {
7065            input: Entity<crate::input::EditorState>,
7066            observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
7067        }
7068        impl Render for Panel {
7069            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7070                self.observed.set(self.input.read(cx).cursor_layout());
7071                div().size_full().child(self.input.clone())
7072            }
7073        }
7074        struct Root(Entity<Panel>);
7075        impl Render for Root {
7076            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7077                div().size_full().child(
7078                    self.0
7079                        .clone()
7080                        .cached(gpui::StyleRefinement::default().size_full()),
7081                )
7082            }
7083        }
7084        cx.update(crate::init);
7085        let observed = Rc::new(Cell::new(None));
7086        let mut input = None;
7087        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7088            let state = cx.new(|cx| {
7089                let mut state = crate::input::EditorState::new(window, cx);
7090                state.set_value("abcdefgh", window, cx);
7091                state
7092            });
7093            input = Some(state.clone());
7094            Root(cx.new(|_| Panel {
7095                input: state,
7096                observed: observed.clone(),
7097            }))
7098        });
7099        cx.run_until_parked();
7100        let input = input.unwrap();
7101        let before = input.read_with(cx, |state, _| state.cursor_layout());
7102        // The caret geometry only exists once the input has painted, and a
7103        // notify sent from inside a draw marks the view dirty without asking
7104        // for another frame, so the consumer reads the geometry on the next
7105        // invalidation rather than during the paint that produced it.
7106        input.update(cx, |_, cx| cx.notify());
7107        cx.run_until_parked();
7108        assert_eq!(observed.get(), before);
7109        window
7110            .update(cx, |_, _, cx| {
7111                input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
7112            })
7113            .unwrap();
7114        cx.run_until_parked();
7115        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7116        let after = input.read_with(cx, |state, _| state.cursor_layout());
7117        assert_ne!(after, before, "the caret must actually move");
7118        assert_eq!(
7119            observed.get(),
7120            after,
7121            "render consumers must receive the newly painted caret geometry"
7122        );
7123    }
7124
7125    #[gpui::test]
7126    fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
7127        use std::{cell::Cell, rc::Rc};
7128
7129        cx.update(crate::init);
7130        let mut input = None;
7131        let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7132            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7133            gpui::EmptyView
7134        });
7135        let input = input.unwrap();
7136        let notifications = Rc::new(Cell::new(0));
7137        let count = notifications.clone();
7138        let _subscription =
7139            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7140
7141        input.update(cx, |state, _| {
7142            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7143            state.scroll_size = size(px(300.), px(20.));
7144        });
7145        for target in [
7146            None,
7147            Some(point(px(0.), px(0.))),
7148            Some(point(px(20.), px(50.))),
7149        ] {
7150            input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
7151            assert_eq!(
7152                notifications.get(),
7153                0,
7154                "an unchanged clamped offset must stay quiet"
7155            );
7156        }
7157        input.update(cx, |state, cx| {
7158            state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
7159            assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
7160        });
7161        assert_eq!(notifications.get(), 1, "a scroll must notify");
7162        input.update(cx, |state, cx| {
7163            state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
7164            assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
7165        });
7166        assert_eq!(notifications.get(), 2);
7167        input.update(cx, |state, cx| {
7168            state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
7169        });
7170        assert_eq!(
7171            notifications.get(),
7172            2,
7173            "clamping to the current offset must stay quiet"
7174        );
7175        input.update(cx, |state, cx| {
7176            state.scroll_size.width = px(110.);
7177            state.update_scroll_offset(None, cx);
7178            assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
7179        });
7180        assert_eq!(
7181            notifications.get(),
7182            3,
7183            "a smaller scroll range must clamp and notify"
7184        );
7185    }
7186
7187    #[gpui::test]
7188    fn test_set_line_number_notifies_only_on_change(cx: &mut TestAppContext) {
7189        use std::{cell::Cell, rc::Rc};
7190
7191        cx.update(crate::init);
7192        let mut input = None;
7193        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7194            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7195            gpui::EmptyView
7196        });
7197        let input = input.unwrap();
7198        let shown = input.read_with(cx, |state, _| state.mode.line_number());
7199        let notifications = Rc::new(Cell::new(0));
7200        let count = notifications.clone();
7201        let _subscription =
7202            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7203
7204        window
7205            .update(cx, |_, window, cx| {
7206                input.update(cx, |state, cx| state.set_line_number(shown, window, cx))
7207            })
7208            .unwrap();
7209        assert_eq!(notifications.get(), 0);
7210
7211        window
7212            .update(cx, |_, window, cx| {
7213                input.update(cx, |state, cx| state.set_line_number(!shown, window, cx))
7214            })
7215            .unwrap();
7216        assert_eq!(notifications.get(), 1);
7217        assert_eq!(
7218            input.read_with(cx, |state, _| state.mode.line_number()),
7219            !shown
7220        );
7221    }
7222
7223    #[gpui::test]
7224    fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
7225        use std::{cell::Cell, rc::Rc};
7226
7227        cx.update(crate::init);
7228        let mut input = None;
7229        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7230            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7231            gpui::EmptyView
7232        });
7233        let input = input.unwrap();
7234        cx.run_until_parked();
7235
7236        let notifications = Rc::new(Cell::new(0));
7237        let count = notifications.clone();
7238        let _subscription =
7239            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7240        cx.run_until_parked();
7241
7242        // Seeding a form is a write, so it notifies once. The input is not
7243        // focused and draws no caret, so nothing may notify after that.
7244        window
7245            .update(cx, |_, window, cx| {
7246                input.update(cx, |state, cx| state.set_value("seeded", window, cx));
7247            })
7248            .unwrap();
7249        cx.run_until_parked();
7250        let settled = notifications.get();
7251
7252        cx.executor()
7253            .advance_clock(std::time::Duration::from_secs(3));
7254        cx.run_until_parked();
7255
7256        assert_eq!(
7257            notifications.get(),
7258            settled,
7259            "an unfocused input is blinking, and every blink repaints the view it is in"
7260        );
7261    }
7262
7263    #[gpui::test]
7264    fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
7265        use std::{cell::Cell, rc::Rc};
7266
7267        struct Panel {
7268            input: Entity<crate::input::InputState>,
7269            renders: Rc<Cell<usize>>,
7270        }
7271        impl Render for Panel {
7272            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7273                self.renders.set(self.renders.get() + 1);
7274                div().size_full().child(self.input.clone())
7275            }
7276        }
7277        struct Root(Entity<Panel>);
7278        impl Render for Root {
7279            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7280                div().size_full().child(
7281                    self.0
7282                        .clone()
7283                        .cached(gpui::StyleRefinement::default().size_full()),
7284                )
7285            }
7286        }
7287
7288        cx.update(crate::init);
7289        let renders = Rc::new(Cell::new(0));
7290        let mut input = None;
7291        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7292            let state = cx.new(|cx| crate::input::InputState::new(window, cx));
7293            input = Some(state.clone());
7294            Root(cx.new(|_| Panel {
7295                input: state,
7296                renders: renders.clone(),
7297            }))
7298        });
7299        cx.run_until_parked();
7300        let before = renders.get();
7301        assert!(before > 0);
7302        for _ in 0..60 {
7303            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7304        }
7305        assert_eq!(
7306            renders.get(),
7307            before,
7308            "an idle input must not invalidate its cached parent"
7309        );
7310
7311        let input = input.unwrap();
7312        window
7313            .update(cx, |_, window, cx| {
7314                input.update(cx, |state, cx| state.set_value("changed", window, cx));
7315            })
7316            .unwrap();
7317        assert!(
7318            renders.get() > before,
7319            "text changes must invalidate the parent"
7320        );
7321        // The first paint reports the changed text extent to layout consumers.
7322        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7323        let before = renders.get();
7324        for _ in 0..60 {
7325            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7326        }
7327        assert_eq!(renders.get(), before, "the edited input must settle again");
7328
7329        cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
7330        cx.run_until_parked();
7331        assert!(renders.get() > before, "resizing must invalidate layout");
7332    }
7333
7334    #[gpui::test]
7335    fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
7336        cx.update(crate::init);
7337        let view = InputView::build_textarea(cx, |state| state);
7338        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7339        cx.update(|window, cx| {
7340            view.input.update(cx, |state, cx| {
7341                for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
7342                    state.set_value(original, window, cx);
7343                    let newline = original.find('\n').unwrap();
7344                    let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
7345                        newline - 1
7346                    } else {
7347                        newline
7348                    };
7349                    state.end(&MoveEnd, window, cx);
7350                    assert_eq!(state.cursor(), end);
7351                    state.right(&MoveRight, window, cx);
7352                    assert_eq!(state.cursor(), newline + 1);
7353                    state.left(&MoveLeft, window, cx);
7354                    assert_eq!(state.cursor(), end);
7355                    state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
7356                    assert_eq!(state.selected_range(), end..end);
7357                    state.move_to_end(&MoveToEnd, window, cx);
7358                    assert_eq!(state.cursor(), original.len());
7359                    state.move_to_start(&MoveToStart, window, cx);
7360                    assert_eq!(state.cursor(), 0);
7361                    assert_eq!(state.value().as_bytes(), original.as_bytes());
7362                }
7363                // A lone CR is an ordinary character; it must not skip its neighbour.
7364                state.set_value("a\rb", window, cx);
7365                state.right(&MoveRight, window, cx);
7366                assert_eq!(state.cursor(), 1);
7367                state.right(&MoveRight, window, cx);
7368                assert_eq!(state.cursor(), 2);
7369            })
7370        });
7371    }
7372
7373    #[gpui::test]
7374    fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
7375        cx.update(crate::init);
7376
7377        // A single-line input keeps its caret in view by moving its own offset;
7378        // it has no viewport to drag, so a scrollbar in a text field is a
7379        // control that does not exist.
7380        let single = InputView::build(cx, |state| state);
7381        single
7382            .input
7383            .update(cx, |state, _| assert!(!state.shows_scrollbar()));
7384
7385        let multi = InputView::build_textarea(cx, |state| state);
7386        multi
7387            .input
7388            .update(cx, |state, _| assert!(state.shows_scrollbar()));
7389    }
7390
7391    #[gpui::test]
7392    fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
7393        use std::{cell::Cell, rc::Rc};
7394        cx.update(crate::init);
7395        let input_view = InputView::new(cx);
7396        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7397        let input = input_view.input;
7398        let calls = Rc::new(Cell::new(0usize));
7399        let items = Rc::new(Cell::new(0usize));
7400        let menu_focus = cx.update(|_, cx| cx.focus_handle());
7401
7402        cx.update(|window, cx| {
7403            input.update(cx, |state, cx| {
7404                let calls2 = calls.clone();
7405                let items2 = items.clone();
7406                let menu_focus = menu_focus.clone();
7407                state.on_context_menu(Rc::new(move |menu, _, _, window, cx| {
7408                    calls2.set(calls2.get() + 1);
7409                    items2.set(menu.items.len());
7410                    menu_focus.focus(window, cx);
7411                }));
7412                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7413            })
7414        });
7415        assert_eq!(calls.get(), 1);
7416        assert_eq!(items.get(), 0);
7417        input.read_with(&cx, |state, _| {
7418            assert_eq!(
7419                state
7420                    .selection_focus
7421                    .as_ref()
7422                    .and_then(WeakFocusHandle::upgrade)
7423                    .as_ref(),
7424                Some(&menu_focus),
7425                "the menu callback must retain selection without reborrowing its input"
7426            );
7427        });
7428
7429        // A custom handler may keep using the same, already-focused menu.
7430        cx.update(|window, cx| {
7431            input.update(cx, |state, cx| {
7432                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7433            });
7434        });
7435        assert_eq!(calls.get(), 2);
7436        cx.update(|window, cx| {
7437            assert!(input.read(cx).has_selection_focus(window, cx));
7438        });
7439
7440        cx.update(|window, cx| {
7441            input.update(cx, |state, cx| {
7442                state.disabled = true;
7443                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7444            })
7445        });
7446        assert_eq!(calls.get(), 2);
7447    }
7448
7449    #[gpui::test]
7450    fn context_menu_handler_can_read_its_input(cx: &mut TestAppContext) {
7451        use std::{cell::Cell, rc::Rc};
7452        cx.update(crate::init);
7453        let input_view = InputView::new(cx);
7454        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7455        let input = input_view.input;
7456        let cursor = Rc::new(Cell::new(None));
7457
7458        cx.update(|window, cx| {
7459            input.update(cx, |state, cx| {
7460                state.set_value("hello", window, cx);
7461                let weak = cx.weak_entity();
7462                let cursor = cursor.clone();
7463                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7464                    cursor.set(weak.upgrade().map(|input| input.read(cx).cursor()));
7465                }));
7466                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7467            })
7468        });
7469        assert_eq!(cursor.get(), Some(2));
7470    }
7471
7472    #[gpui::test]
7473    fn context_menu_handler_can_read_the_offset_under_the_pointer(cx: &mut TestAppContext) {
7474        use std::{cell::Cell, rc::Rc};
7475        cx.update(crate::init);
7476        let input_view = InputView::new(cx);
7477        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7478        let input = input_view.input;
7479        let seen = Rc::new(Cell::new(None));
7480
7481        cx.update(|window, cx| {
7482            input.update(cx, |state, cx| {
7483                state.set_value("hello world", window, cx);
7484                assert_eq!(state.context_menu_offset(), None);
7485                state.select_all(window, cx);
7486                let weak = cx.weak_entity();
7487                let seen = seen.clone();
7488                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7489                    seen.set(weak.upgrade().map(|input| {
7490                        let input = input.read(cx);
7491                        (input.cursor(), input.context_menu_offset())
7492                    }));
7493                }));
7494                // A right-click inside the selection keeps the cursor at its end.
7495                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7496            })
7497        });
7498        assert_eq!(seen.get(), Some((11, Some(2))));
7499    }
7500
7501    #[gpui::test]
7502    fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
7503        let input_view = InputView::new(cx);
7504        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7505        let input = input_view.input;
7506
7507        cx.update(|window, cx| {
7508            input.update(cx, |state, cx| {
7509                state.set_value("hello", window, cx);
7510                state.set_readonly(true, cx);
7511            });
7512        });
7513
7514        cx.update(|_, cx| {
7515            input.read_with(cx, |state, _| {
7516                assert!(!state.is_editable());
7517                assert!(!state.is_replaceable());
7518            });
7519        });
7520
7521        // Typing (and IME) goes through the input handler, it must be rejected.
7522        cx.update(|window, cx| {
7523            input.update(cx, |state, cx| {
7524                state.replace_text_in_range(None, " world", window, cx);
7525                state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
7526            });
7527        });
7528        cx.update(|_, cx| {
7529            input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
7530        });
7531
7532        // The programmatic APIs are not limited by the readonly mode.
7533        cx.update(|window, cx| {
7534            input.update(cx, |state, cx| {
7535                state.insert(" world", window, cx);
7536                state.set_value("changed", window, cx);
7537            });
7538        });
7539        cx.update(|_, cx| {
7540            input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
7541        });
7542
7543        // And the user can edit again after leaving the readonly mode.
7544        // The caret is at the start, because `set_value` has reset the selection.
7545        cx.update(|window, cx| {
7546            input.update(cx, |state, cx| {
7547                state.set_readonly(false, cx);
7548                state.replace_text_in_range(None, "!", window, cx);
7549            });
7550        });
7551        cx.update(|_, cx| {
7552            input.read_with(cx, |state, _| {
7553                assert!(state.is_editable());
7554                assert_eq!(state.value(), "!changed");
7555            });
7556        });
7557    }
7558
7559    /// Regression test: editing at a caret that sits far outside the viewport
7560    /// must reveal it in one frame. The cursor-follow in `layout_cursors` runs
7561    /// only on the frame the selection changes, so its old one-line step left
7562    /// the caret offscreen after typing at the end of a long paste.
7563    #[gpui::test]
7564    fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
7565        let mut input = None;
7566        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7567            cx.set_global(Theme::default());
7568            super::super::init(cx);
7569            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
7570            input = Some(state.clone());
7571            TestRoot(state)
7572        });
7573        let mut cx = VisualTestContext::from_window(window.into(), cx);
7574        let input = input.unwrap();
7575
7576        let text: String = (1..=100)
7577            .map(|i| format!("line {i}"))
7578            .collect::<Vec<_>>()
7579            .join("\n");
7580        cx.update(|window, cx| {
7581            input.update(cx, |state, cx| {
7582                state.set_value(text, window, cx);
7583                let end = state.text.len();
7584                state.set_selection(end, end);
7585            });
7586        });
7587        cx.run_until_parked();
7588
7589        // The user scrolled back to the top to read the pasted text.
7590        cx.update(|_, cx| {
7591            input.update(cx, |state, cx| {
7592                state.scroll_handle.set_offset(point(px(0.), px(0.)));
7593                cx.notify();
7594            });
7595        });
7596        cx.run_until_parked();
7597
7598        cx.update(|window, cx| {
7599            input.update(cx, |state, cx| {
7600                state.replace_text_in_range(None, "X", window, cx);
7601            });
7602        });
7603        cx.run_until_parked();
7604
7605        cx.update(|_, cx| {
7606            input.read_with(cx, |state, _| {
7607                assert!(state.value().ends_with("line 100X"));
7608                let (caret, _) = state.cursor_layout().expect("caret painted");
7609                let viewport = state.input_bounds();
7610                let scroll_y = state.scroll_handle.offset().y;
7611                let top = caret.origin.y - viewport.origin.y + scroll_y;
7612                assert!(
7613                    top >= px(0.) && top + caret.size.height <= viewport.size.height,
7614                    "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
7615                    viewport.size.height,
7616                );
7617            });
7618        });
7619    }
7620
7621    /// Regression test: changing the auto-grow limits keeps the rows fitted to
7622    /// the text. `set_auto_grow` used to start over at `min_rows`, and the rows
7623    /// were counted again only on the next edit or wrap width change.
7624    #[gpui::test]
7625    fn test_set_auto_grow_keeps_rows_fitted(cx: &mut TestAppContext) {
7626        let mut input = None;
7627        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7628            cx.set_global(Theme::default());
7629            super::super::init(cx);
7630            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 10));
7631            input = Some(state.clone());
7632            TestRoot(state)
7633        });
7634        let mut cx = VisualTestContext::from_window(window.into(), cx);
7635        let input = input.unwrap();
7636
7637        let text: String = (1..=8)
7638            .map(|i| format!("line {i}"))
7639            .collect::<Vec<_>>()
7640            .join("\n");
7641        cx.update(|window, cx| {
7642            input.update(cx, |state, cx| state.set_value(text, window, cx));
7643        });
7644        cx.run_until_parked();
7645        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7646
7647        // A larger maximum keeps all eight rows.
7648        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 12, cx)));
7649        cx.run_until_parked();
7650        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7651
7652        // A smaller maximum caps them.
7653        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 4, cx)));
7654        cx.run_until_parked();
7655        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 4)));
7656    }
7657
7658    /// Regression test: `scroll_to` at end-of-buffer must produce a deferred
7659    /// scroll target within the safe scroll range, so the painted frame
7660    /// matches what `update_scroll_offset` persists (no jitter). A small
7661    /// `cursor_surrounding_lines` override used to mismatch the hardcoded
7662    /// 3-line edge clearance in `scroll_to`, overshooting `safe_y_min`.
7663    #[gpui::test]
7664    fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
7665        let input_view = InputView::new(cx);
7666        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7667        let input = input_view.input;
7668
7669        // JetBrains-style: 1 trailing empty row + 1-line cursor surrounding.
7670        cx.update(|window, cx| {
7671            input.update(cx, |state, cx| {
7672                state.set_scroll_beyond_last_line(Some(1), window, cx);
7673                state.set_cursor_surrounding_lines(Some(1), window, cx);
7674                let text: String = (1..=50)
7675                    .map(|i| format!("line {i}"))
7676                    .collect::<Vec<_>>()
7677                    .join("\n");
7678                state.set_value(text, window, cx);
7679            });
7680        });
7681        cx.run_until_parked();
7682
7683        // Sanity: paint populated `scroll_size` and `input_bounds` — without
7684        // these, `safe_y_min` below collapses to 0 and the assertion is vacuous.
7685        cx.update(|_, cx| {
7686            input.read_with(cx, |state, _| {
7687                assert!(
7688                    state.scroll_size.height > px(0.),
7689                    "scroll_size not populated by initial paint"
7690                );
7691                assert!(
7692                    state.input_bounds.size.height > px(0.),
7693                    "input_bounds not populated by initial paint"
7694                );
7695            });
7696        });
7697
7698        // Move cursor to end with downward direction — same code path as a
7699        // `Down` keystroke at EOB. `scroll_to` runs synchronously inside
7700        // `move_to`; inspect `deferred_scroll_offset` in the same closure
7701        // before the next paint consumes and clears it.
7702        cx.update(|_, cx| {
7703            input.update(cx, |state, cx| {
7704                let end = state.text.len();
7705                state.move_to(end, Some(MoveDirection::Down), cx);
7706
7707                let deferred = state
7708                    .deferred_scroll_offset
7709                    .expect("scroll_to should populate deferred_scroll_offset");
7710                let safe_y_min =
7711                    (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
7712
7713                assert!(
7714                    deferred.y >= safe_y_min,
7715                    "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
7716                     — paint would jitter (Bug C regression)",
7717                    deferred.y,
7718                    safe_y_min,
7719                );
7720            });
7721        });
7722    }
7723
7724    #[gpui::test]
7725    fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
7726        assert_search_reveals_with_padding_after_manual_scroll(false, cx);
7727    }
7728
7729    #[gpui::test]
7730    fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
7731        cx: &mut TestAppContext,
7732    ) {
7733        assert_search_reveals_with_padding_after_manual_scroll(true, cx);
7734    }
7735
7736    fn assert_search_reveals_with_padding_after_manual_scroll(
7737        previous: bool,
7738        cx: &mut TestAppContext,
7739    ) {
7740        let input_view = InputView::new(cx);
7741        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7742        let input = input_view.input;
7743        let text = (0..160)
7744            .map(|row| {
7745                if matches!(row, 20 | 60 | 100) {
7746                    format!("match on row {row}")
7747                } else {
7748                    format!("line {row}")
7749                }
7750            })
7751            .collect::<Vec<_>>()
7752            .join("\n");
7753        let start = text.match_indices("match").nth(1).unwrap().0;
7754        let expected_match = start..start + "match".len();
7755        cx.update(|window, cx| {
7756            input.update(cx, |state, cx| {
7757                state.set_cursor_surrounding_lines(Some(3), window, cx);
7758                state.set_value(text, window, cx);
7759                state.set_search_query("match", true, cx);
7760                if previous {
7761                    state.search_session.matcher.next();
7762                    state.search_session.matcher.next();
7763                }
7764            });
7765        });
7766        cx.run_until_parked();
7767        cx.update(|_, cx| {
7768            input.update(cx, |state, cx| {
7769                let line_height = state.last_layout.as_ref().unwrap().line_height;
7770                let y = if previous { px(0.) } else { -line_height * 80. };
7771                state.set_scroll_offset(point(px(0.), y), cx);
7772            });
7773        });
7774        cx.run_until_parked();
7775        input.read_with(&cx, |state, _| {
7776            let visible = state.visible_row_range().unwrap();
7777            if previous {
7778                assert!(visible.end <= 60, "target must be below the viewport");
7779            } else {
7780                assert!(visible.start > 60, "target must be above the viewport");
7781            }
7782        });
7783        cx.update(|_, cx| {
7784            input.update(cx, |state, cx| {
7785                let range = if previous {
7786                    state.previous_search_match(cx)
7787                } else {
7788                    state.next_search_match(cx)
7789                };
7790                assert_eq!(range, Some(expected_match));
7791                assert_eq!(state.search_session.matcher.label(), "2/3");
7792            });
7793        });
7794        cx.run_until_parked();
7795        input.read_with(&cx, |state, _| {
7796            assert!(state.visible_row_range().unwrap().contains(&60));
7797            let line_height = state.last_layout.as_ref().unwrap().line_height;
7798            let target_y = line_height * 60. + state.scroll_handle.offset().y;
7799            // Three lines of edge clearance include the matched line itself.
7800            assert!(target_y >= line_height * 2. - px(0.1));
7801            assert!(
7802                target_y + line_height * 3.
7803                    <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
7804                "search must preserve the configured surrounding-line padding"
7805            );
7806        });
7807    }
7808
7809    /// A host that wants the search shortcut for its own search UI.
7810    struct SearchHost {
7811        editor: Entity<InputBaseState<EditorMode>>,
7812        search_requests: Rc<Cell<usize>>,
7813    }
7814
7815    impl Render for SearchHost {
7816        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7817            let search_requests = self.search_requests.clone();
7818            div()
7819                .size_full()
7820                .on_action(cx.listener(move |_, _: &Search, _, _| {
7821                    search_requests.set(search_requests.get() + 1);
7822                }))
7823                .child(self.editor.clone())
7824        }
7825    }
7826
7827    /// Opens an editor inside [`SearchHost`], focused, and presses the search
7828    /// shortcut once. Returns the editor and the host's request count.
7829    fn press_search_shortcut(
7830        cx: &mut TestAppContext,
7831        searchable: bool,
7832    ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
7833        let search_requests = Rc::new(Cell::new(0));
7834        let mut editor = None;
7835        let window = cx.update(|cx| {
7836            cx.open_window(Default::default(), |window, cx| {
7837                cx.set_global(Theme::default());
7838                super::super::init(cx);
7839                let state =
7840                    cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
7841                editor = Some(state.clone());
7842                cx.new(|_| SearchHost {
7843                    editor: state,
7844                    search_requests: search_requests.clone(),
7845                })
7846            })
7847            .unwrap()
7848        });
7849        let editor = editor.unwrap();
7850        let mut cx = VisualTestContext::from_window(window.into(), cx);
7851        cx.update(|window, cx| {
7852            editor.update(cx, |state, cx| state.focus(window, cx));
7853        });
7854        cx.run_until_parked();
7855        #[cfg(target_os = "macos")]
7856        cx.simulate_keystrokes("cmd-f");
7857        #[cfg(not(target_os = "macos"))]
7858        cx.simulate_keystrokes("ctrl-f");
7859        cx.run_until_parked();
7860        (editor, search_requests)
7861    }
7862
7863    #[gpui::test]
7864    fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
7865        let (editor, search_requests) = press_search_shortcut(cx, false);
7866        assert_eq!(search_requests.get(), 1);
7867        editor.read_with(cx, |state, _| {
7868            assert!(!state.search_session().open);
7869            assert!(!state.search_session().is_active());
7870        });
7871    }
7872
7873    #[gpui::test]
7874    fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
7875        let (editor, search_requests) = press_search_shortcut(cx, true);
7876        assert_eq!(search_requests.get(), 0);
7877        editor.read_with(cx, |state, _| {
7878            assert!(state.search_session().open);
7879            assert!(state.search_session().is_active());
7880        });
7881    }
7882
7883    #[gpui::test]
7884    fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
7885        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7886        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7887        let input = input_view.input;
7888        cx.update(|window, cx| {
7889            input.update(cx, |state, cx| {
7890                state.set_value("foo bar foo", window, cx);
7891                state.set_search_query("foo", true, cx);
7892            });
7893        });
7894        cx.run_until_parked();
7895        input.read_with(&cx, |state, _| {
7896            let session = state.search_session();
7897            assert!(session.is_active());
7898            assert!(!session.open);
7899            assert_eq!(session.matcher.len(), 2);
7900        });
7901        cx.update(|_, cx| {
7902            input.update(cx, |state, cx| state.close_search(cx));
7903        });
7904        input.read_with(&cx, |state, _| {
7905            assert!(!state.search_session().is_active());
7906        });
7907    }
7908
7909    /// A closed search skips rescanning on edits, so every path that reads
7910    /// the matches again must see the edited text, not the text at close.
7911    #[gpui::test]
7912    fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
7913        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7914        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7915        let input = input_view.input;
7916        cx.update(|window, cx| {
7917            input.update(cx, |state, cx| {
7918                state.set_value("foo bar foo", window, cx);
7919                state.set_search_query("foo", true, cx);
7920                state.close_search(cx);
7921
7922                state.set_value("bar foo", window, cx);
7923                assert_eq!(state.next_search_match(cx), Some(4..7));
7924
7925                state.set_value("foo foo foo", window, cx);
7926                state.set_search_query("foo", true, cx);
7927                assert_eq!(state.search_session().matcher.len(), 3);
7928            });
7929        });
7930    }
7931
7932    #[gpui::test]
7933    fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
7934        let input_view = InputView::new(cx);
7935        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7936        let input = input_view.input;
7937        let text = format!(
7938            "match\n{}\n{}match\n{}",
7939            "line\n".repeat(80),
7940            "wrapped text ".repeat(500),
7941            "line\n".repeat(80)
7942        );
7943        cx.update(|window, cx| {
7944            input.update(cx, |state, cx| {
7945                state.set_cursor_surrounding_lines(Some(3), window, cx);
7946                state.set_value(text, window, cx);
7947                state.set_search_query("match", true, cx);
7948            });
7949        });
7950        cx.run_until_parked();
7951        cx.update(|_, cx| {
7952            input.update(cx, |state, cx| {
7953                state.next_search_match(cx).unwrap();
7954            });
7955        });
7956        cx.run_until_parked();
7957        input.read_with(&cx, |state, _| {
7958            let range = state.search_session.matcher.matched_ranges()[1].clone();
7959            let layout = state.last_layout.as_ref().unwrap();
7960            let (_, _, position) = state.line_and_position_for_offset(range.end);
7961            let y = position.expect("wrapped match must be laid out").y
7962                + state.scroll_handle.offset().y;
7963            assert!(y >= layout.line_height * 2. - px(0.1));
7964            assert!(
7965                y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
7966                "wrapped match must retain surrounding display rows"
7967            );
7968        });
7969    }
7970
7971    #[gpui::test]
7972    fn test_number_input_normalization(cx: &mut TestAppContext) {
7973        let input_view = InputView::build(cx, |state| {
7974            state.mask_pattern(MaskPattern::Number {
7975                separator: None,
7976                fraction: None,
7977            })
7978        });
7979        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7980        let input = input_view.input;
7981
7982        // Full-width digits and the ideographic full stop are normalized,
7983        // and the cursor is at the end (in normalized bytes, not the
7984        // original 12 bytes).
7985        cx.update(|window, cx| {
7986            input.update(cx, |state, cx| {
7987                state.replace_text_in_range(None, "12。5", window, cx);
7988            });
7989        });
7990        cx.run_until_parked();
7991        cx.update(|_, cx| {
7992            input.read_with(cx, |state, _| {
7993                assert_eq!(state.value(), "12.5");
7994                let cursor: Range<usize> = state.selected_range();
7995                assert_eq!(cursor, 4..4);
7996            });
7997        });
7998
7999        // Non-numeric input is rejected.
8000        cx.update(|window, cx| {
8001            input.update(cx, |state, cx| {
8002                state.replace_text_in_range(None, "abc", window, cx);
8003            });
8004        });
8005        cx.run_until_parked();
8006        cx.update(|_, cx| {
8007            input.read_with(cx, |state, _| {
8008                assert_eq!(state.value(), "12.5");
8009            });
8010        });
8011
8012        // A bare leading dot is kept as-is (normalized from the ideographic
8013        // full stop), not completed to "0.", so it stays editable.
8014        cx.update(|window, cx| {
8015            input.update(cx, |state, cx| {
8016                let range = state.range_to_utf16(&(0..state.text.len()));
8017                state.replace_text_in_range(Some(range), "。", window, cx);
8018            });
8019        });
8020        cx.run_until_parked();
8021        cx.update(|_, cx| {
8022            input.read_with(cx, |state, _| {
8023                assert_eq!(state.value(), ".");
8024                let cursor: Range<usize> = state.selected_range();
8025                assert_eq!(cursor, 1..1);
8026            });
8027        });
8028    }
8029
8030    #[gpui::test]
8031    fn test_mask_pattern_accepts_non_ascii_text(cx: &mut TestAppContext) {
8032        let input_view = InputView::build(cx, |state| state.mask_pattern("9999年99月"));
8033        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8034        let input = input_view.input;
8035
8036        cx.update(|window, cx| {
8037            input.update(cx, |state, cx| {
8038                state.replace_text_in_range(None, "2024年12月", window, cx);
8039            });
8040        });
8041        cx.run_until_parked();
8042        cx.update(|_, cx| {
8043            input.read_with(cx, |state, _| {
8044                assert_eq!(state.value(), "2024年12月");
8045            });
8046        });
8047    }
8048
8049    #[gpui::test]
8050    fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
8051        let input_view = InputView::build(cx, |state| {
8052            state.mask_pattern(MaskPattern::Number {
8053                separator: Some(','),
8054                fraction: Some(2),
8055            })
8056        });
8057        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8058        let input = input_view.input;
8059
8060        cx.update(|window, cx| {
8061            input.update(cx, |state, cx| {
8062                state.replace_text_in_range(None, "1234", window, cx);
8063            });
8064        });
8065        cx.run_until_parked();
8066        cx.update(|_, cx| {
8067            input.read_with(cx, |state, _| {
8068                assert_eq!(state.value(), "1,234");
8069                assert_eq!(state.unmask_value(), "1234");
8070            });
8071        });
8072    }
8073
8074    #[gpui::test]
8075    fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
8076        let input_view = InputView::build(cx, |state| {
8077            state
8078                .mask_pattern(MaskPattern::Number {
8079                    separator: None,
8080                    fraction: None,
8081                })
8082                .min(10.)
8083                .max(100.)
8084        });
8085        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8086        let input = input_view.input;
8087
8088        // Out-of-range values are allowed while typing, and clamped on blur.
8089        cx.update(|window, cx| {
8090            input.update(cx, |state, cx| {
8091                state.replace_text_in_range(None, "1000", window, cx);
8092                assert_eq!(state.value(), "1000");
8093                state.clamp_number_value(window, cx);
8094                assert_eq!(state.value(), "100");
8095
8096                let range = state.range_to_utf16(&(0..state.text.len()));
8097                state.replace_text_in_range(Some(range), "1", window, cx);
8098                assert_eq!(state.value(), "1");
8099                state.clamp_number_value(window, cx);
8100                assert_eq!(state.value(), "10");
8101            });
8102        });
8103    }
8104
8105    #[gpui::test]
8106    fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
8107        let input_view = InputView::build(cx, |state| {
8108            state.mask_pattern(MaskPattern::Number {
8109                separator: Some(','),
8110                fraction: None,
8111            })
8112        });
8113        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8114        let input = input_view.input;
8115
8116        // When the mask changes the text (regrouping separators), a
8117        // whole-document change is recorded, so undo/redo can restore it.
8118        cx.update(|window, cx| {
8119            input.update(cx, |state, cx| {
8120                state.replace_text_in_range(None, "1234", window, cx);
8121                assert_eq!(state.value(), "1,234");
8122                state.replace_text_in_range(None, "5", window, cx);
8123                assert_eq!(state.value(), "12,345");
8124
8125                // Each whole-document mask rewrite is an atomic undo step.
8126                // Before the whole-document history fix, undo produced a
8127                // corrupted value like "1,2344".
8128                state.undo(&Undo, window, cx);
8129                assert_eq!(state.value(), "1,234");
8130                state.undo(&Undo, window, cx);
8131                assert_eq!(state.value(), "");
8132                state.redo(&Redo, window, cx);
8133                assert_eq!(state.value(), "1,234");
8134                state.redo(&Redo, window, cx);
8135                assert_eq!(state.value(), "12,345");
8136            });
8137        });
8138    }
8139
8140    #[gpui::test]
8141    fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
8142        let input_view = InputView::build(cx, |state| state);
8143        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8144        let input = input_view.input;
8145
8146        cx.update(|window, cx| {
8147            input.update(cx, |state, cx| {
8148                state.replace_text_in_range(None, "a", window, cx);
8149                state.replace_text_in_range(None, "b", window, cx);
8150                assert_eq!(state.value(), "ab");
8151
8152                state.undo(&Undo, window, cx);
8153                assert_eq!(state.value(), "");
8154            });
8155        });
8156    }
8157
8158    #[gpui::test]
8159    fn test_undo_manager_cursor_movement_splits_typing(cx: &mut TestAppContext) {
8160        let input_view = InputView::build(cx, |state| state);
8161        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8162        let input = input_view.input;
8163
8164        cx.update(|window, cx| {
8165            input.update(cx, |state, cx| {
8166                state.replace_text_in_range(None, "a", window, cx);
8167                state.replace_text_in_range(None, "b", window, cx);
8168                state.left(&MoveLeft, window, cx);
8169                state.replace_text_in_range(None, "x", window, cx);
8170                assert_eq!(state.value(), "axb");
8171
8172                state.undo(&Undo, window, cx);
8173                assert_eq!(state.value(), "ab");
8174                state.undo(&Undo, window, cx);
8175                assert_eq!(state.value(), "");
8176            });
8177        });
8178    }
8179
8180    #[gpui::test]
8181    fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
8182        let input_view = InputView::build(cx, |state| state);
8183        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8184        let input = input_view.input;
8185
8186        cx.update(|window, cx| {
8187            input.update(cx, |state, cx| {
8188                state.set_value("abcd", window, cx);
8189                state.set_selected_range(2..2, cx);
8190                state.backspace(&Backspace, window, cx);
8191                state.delete(&Delete, window, cx);
8192                assert_eq!(state.value(), "ad");
8193
8194                state.undo(&Undo, window, cx);
8195                assert_eq!(state.value(), "acd");
8196                state.undo(&Undo, window, cx);
8197                assert_eq!(state.value(), "abcd");
8198            });
8199        });
8200    }
8201
8202    #[gpui::test]
8203    fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
8204        let input_view = InputView::build(cx, |state| state);
8205        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8206        let input = input_view.input;
8207
8208        cx.update(|window, cx| {
8209            input.update(cx, |state, cx| {
8210                state.set_value("abcd", window, cx);
8211                state.backspace(&Backspace, window, cx);
8212                state.backspace(&Backspace, window, cx);
8213                assert_eq!(state.value(), "ab");
8214                state.undo(&Undo, window, cx);
8215                assert_eq!(state.value(), "abcd");
8216                assert_eq!(state.selected_range(), 4..4);
8217
8218                state.set_value("abcd", window, cx);
8219                state.set_selected_range(1..1, cx);
8220                state.delete(&Delete, window, cx);
8221                state.delete(&Delete, window, cx);
8222                assert_eq!(state.value(), "ad");
8223                state.undo(&Undo, window, cx);
8224                assert_eq!(state.value(), "abcd");
8225                assert_eq!(state.selected_range(), 1..1);
8226            });
8227        });
8228    }
8229
8230    #[gpui::test]
8231    fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
8232        let input_view = InputView::build(cx, |state| state);
8233        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8234        let input = input_view.input;
8235
8236        cx.update(|window, cx| {
8237            cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
8238            input.update(cx, |state, cx| {
8239                state.replace_text_in_range(None, "a", window, cx);
8240                state.paste(&Paste, window, cx);
8241                state.replace_text_in_range(None, "b", window, cx);
8242                assert_eq!(state.value(), "aPb");
8243
8244                state.undo(&Undo, window, cx);
8245                assert_eq!(state.value(), "aP");
8246                state.undo(&Undo, window, cx);
8247                assert_eq!(state.value(), "a");
8248                state.undo(&Undo, window, cx);
8249                assert_eq!(state.value(), "");
8250            });
8251        });
8252    }
8253
8254    #[gpui::test]
8255    fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
8256        let input_view = InputView::build(cx, |state| state);
8257        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8258        let input = input_view.input;
8259
8260        cx.update(|window, cx| {
8261            input.update(cx, |state, cx| {
8262                state.replace_text_in_range(None, "a", window, cx);
8263                state.insert("P", window, cx);
8264                state.replace_text_in_range(None, "b", window, cx);
8265                assert_eq!(state.value(), "aPb");
8266
8267                state.undo(&Undo, window, cx);
8268                assert_eq!(state.value(), "aP");
8269                state.undo(&Undo, window, cx);
8270                assert_eq!(state.value(), "a");
8271            });
8272        });
8273    }
8274
8275    #[gpui::test]
8276    fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
8277        let input_view = InputView::build(cx, |state| state);
8278        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8279        let input = input_view.input;
8280
8281        cx.update(|window, cx| {
8282            input.update(cx, |state, cx| {
8283                state.replace_text_in_range(None, "a", window, cx);
8284                state.replace_text_in_range(None, "b", window, cx);
8285                state.select_all(window, cx);
8286                state.unselect(window, cx);
8287                state.replace_text_in_range(None, "c", window, cx);
8288
8289                state.undo(&Undo, window, cx);
8290                assert_eq!(state.value(), "ab");
8291                state.undo(&Undo, window, cx);
8292                assert_eq!(state.value(), "");
8293            });
8294        });
8295    }
8296
8297    #[gpui::test]
8298    fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
8299        let input_view = InputView::build_textarea(cx, |state| state);
8300        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8301        let input = input_view.input;
8302
8303        cx.update(|window, cx| {
8304            input.update(cx, |state, cx| {
8305                state.replace_text_in_range(None, "a", window, cx);
8306                state.enter(
8307                    &Enter {
8308                        secondary: false,
8309                        shift: false,
8310                    },
8311                    window,
8312                    cx,
8313                );
8314                state.replace_text_in_range(None, "b", window, cx);
8315
8316                state.undo(&Undo, window, cx);
8317                assert_eq!(state.value(), "a\n");
8318                state.undo(&Undo, window, cx);
8319                assert_eq!(state.value(), "a");
8320                state.undo(&Undo, window, cx);
8321                assert_eq!(state.value(), "");
8322            });
8323        });
8324    }
8325
8326    #[gpui::test]
8327    fn test_textarea_secondary_enter_does_not_insert_newline(cx: &mut TestAppContext) {
8328        let input_view = InputView::build_textarea(cx, |state| state);
8329        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8330        let input = input_view.input;
8331
8332        cx.update(|window, cx| {
8333            input.update(cx, |state, cx| {
8334                state.replace_text_in_range(None, "hello", window, cx);
8335                state.set_selection(0, 0);
8336                state.enter(
8337                    &Enter {
8338                        secondary: true,
8339                        shift: false,
8340                    },
8341                    window,
8342                    cx,
8343                );
8344                assert_eq!(state.value(), "hello");
8345            });
8346        });
8347    }
8348
8349    #[gpui::test]
8350    fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
8351        let input_view = InputView::build(cx, |state| state);
8352        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8353        let input = input_view.input;
8354
8355        cx.update(|window, cx| {
8356            input.update(cx, |state, cx| {
8357                for part in ["a", "b", "c"] {
8358                    state.replace_text_in_range(None, part, window, cx);
8359                }
8360                state.enter(
8361                    &Enter {
8362                        secondary: false,
8363                        shift: false,
8364                    },
8365                    window,
8366                    cx,
8367                );
8368                for part in ["d", "e", "f"] {
8369                    state.replace_text_in_range(None, part, window, cx);
8370                }
8371                assert_eq!(state.value(), "abcdef");
8372
8373                state.undo(&Undo, window, cx);
8374                assert_eq!(state.value(), "abc");
8375                state.undo(&Undo, window, cx);
8376                assert_eq!(state.value(), "");
8377            });
8378        });
8379    }
8380
8381    #[gpui::test]
8382    fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
8383        let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
8384        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8385        let input = input_view.input;
8386
8387        cx.update(|window, cx| {
8388            input.update(cx, |state, cx| {
8389                state.replace_text_in_range(None, "before submit", window, cx);
8390                state.enter(
8391                    &Enter {
8392                        secondary: false,
8393                        shift: false,
8394                    },
8395                    window,
8396                    cx,
8397                );
8398                state.replace_text_in_range(None, " after submit", window, cx);
8399                assert_eq!(state.value(), "before submit after submit");
8400
8401                state.undo(&Undo, window, cx);
8402                assert_eq!(state.value(), "before submit");
8403                state.undo(&Undo, window, cx);
8404                assert_eq!(state.value(), "");
8405            });
8406        });
8407    }
8408
8409    #[gpui::test]
8410    fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
8411        let input_view = InputView::build(cx, |state| state);
8412        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8413        let input = input_view.input;
8414
8415        cx.update(|window, cx| {
8416            input.update(cx, |state, cx| {
8417                state.replace_text_in_range(None, "before blur", window, cx);
8418                state.on_blur(window, cx);
8419                state.on_focus(window, cx);
8420                state.replace_text_in_range(None, " after focus", window, cx);
8421                assert_eq!(state.value(), "before blur after focus");
8422
8423                state.undo(&Undo, window, cx);
8424                assert_eq!(state.value(), "before blur");
8425                state.undo(&Undo, window, cx);
8426                assert_eq!(state.value(), "");
8427            });
8428        });
8429    }
8430
8431    #[gpui::test]
8432    fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
8433        let input_view = InputView::build_textarea(cx, |state| state);
8434        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8435        let input = input_view.input;
8436
8437        cx.update(|window, cx| {
8438            input.update(cx, |state, cx| {
8439                let enter = Enter {
8440                    secondary: false,
8441                    shift: false,
8442                };
8443                state.replace_text_in_range(None, "a", window, cx);
8444                state.enter(&enter, window, cx);
8445                state.replace_text_in_range(None, "b", window, cx);
8446                state.enter(&enter, window, cx);
8447                state.replace_text_in_range(None, "c", window, cx);
8448                assert_eq!(state.value(), "a\nb\nc");
8449
8450                for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
8451                    state.undo(&Undo, window, cx);
8452                    assert_eq!(state.value(), expected);
8453                }
8454            });
8455        });
8456    }
8457
8458    #[gpui::test]
8459    fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
8460        let input_view = InputView::build_textarea(cx, |state| state);
8461        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8462        let input = input_view.input;
8463        let parts = [
8464            "The ",
8465            "quick ",
8466            "brown fox, ",
8467            "你好,世界 ",
8468            "🦀 jumps over 13 lazy dogs.",
8469        ];
8470        let expected = parts.concat();
8471
8472        cx.update(|window, cx| {
8473            input.update(cx, |state, cx| {
8474                for part in parts {
8475                    state.replace_text_in_range(None, part, window, cx);
8476                }
8477                assert_eq!(state.value(), expected);
8478
8479                state.undo(&Undo, window, cx);
8480                assert_eq!(state.value(), "");
8481                state.redo(&Redo, window, cx);
8482                assert_eq!(state.value(), expected);
8483            });
8484        });
8485    }
8486
8487    #[gpui::test]
8488    fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
8489        cx: &mut TestAppContext,
8490    ) {
8491        let input_view = InputView::build_textarea(cx, |state| state);
8492        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8493        let input = input_view.input;
8494        let enter = Enter {
8495            secondary: false,
8496            shift: false,
8497        };
8498
8499        cx.update(|window, cx| {
8500            input.update(cx, |state, cx| {
8501                for (index, line) in [
8502                    "first line with punctuation!",
8503                    "第二行包含 Unicode 🦀",
8504                    "third line has several words",
8505                ]
8506                .into_iter()
8507                .enumerate()
8508                {
8509                    for chunk in line.split_inclusive(' ') {
8510                        state.replace_text_in_range(None, chunk, window, cx);
8511                    }
8512                    if index < 2 {
8513                        state.enter(&enter, window, cx);
8514                    }
8515                }
8516
8517                assert_eq!(
8518                    state.value(),
8519                    "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
8520                );
8521                state.undo(&Undo, window, cx);
8522                assert_eq!(
8523                    state.value(),
8524                    "first line with punctuation!\n第二行包含 Unicode 🦀\n"
8525                );
8526                state.undo(&Undo, window, cx);
8527                assert_eq!(
8528                    state.value(),
8529                    "first line with punctuation!\n第二行包含 Unicode 🦀"
8530                );
8531                state.undo(&Undo, window, cx);
8532                assert_eq!(state.value(), "first line with punctuation!\n");
8533            });
8534        });
8535    }
8536
8537    #[gpui::test]
8538    fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
8539        let input_view = InputView::build(cx, |state| state);
8540        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8541        let input = input_view.input;
8542
8543        cx.update(|window, cx| {
8544            input.update(cx, |state, cx| {
8545                state.set_value("hunter2", window, cx);
8546                state.set_masked(true, window, cx);
8547                state.select_all(window, cx);
8548                cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
8549
8550                state.copy(&Copy, window, cx);
8551                assert_eq!(
8552                    cx.read_from_clipboard().and_then(|item| item.text()),
8553                    Some("sentinel".to_string())
8554                );
8555
8556                // Cut neither copies nor deletes.
8557                state.cut(&Cut, window, cx);
8558                assert_eq!(state.value(), "hunter2");
8559                assert_eq!(
8560                    cx.read_from_clipboard().and_then(|item| item.text()),
8561                    Some("sentinel".to_string())
8562                );
8563
8564                // Revealing the value restores both.
8565                state.set_masked(false, window, cx);
8566                state.copy(&Copy, window, cx);
8567                assert_eq!(
8568                    cx.read_from_clipboard().and_then(|item| item.text()),
8569                    Some("hunter2".to_string())
8570                );
8571            });
8572        });
8573    }
8574
8575    #[gpui::test]
8576    fn test_masked_input_redacts_ime_text(cx: &mut TestAppContext) {
8577        let input_view = InputView::build(cx, |state| state.masked(true).default_value("a🦀b"));
8578        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8579        cx.update(|window, cx| {
8580            input_view.input.update(cx, |state, cx| {
8581                let mut adjusted = None;
8582                assert_eq!(
8583                    state.text_for_range(1..5, &mut adjusted, window, cx),
8584                    Some("•••".into())
8585                );
8586                assert_eq!(adjusted, Some(1..4));
8587
8588                state.set_masked(false, window, cx);
8589                assert_eq!(
8590                    state.text_for_range(1..5, &mut adjusted, window, cx),
8591                    Some("🦀b".into())
8592                );
8593                assert_eq!(adjusted, Some(1..4));
8594            });
8595        });
8596    }
8597
8598    #[gpui::test]
8599    fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
8600        let input_view = InputView::build(cx, |state| state);
8601        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8602        let input = input_view.input;
8603
8604        cx.update(|window, cx| {
8605            input.update(cx, |state, cx| {
8606                state.set_value("aaa bbb ccc", window, cx);
8607                state.set_masked(true, window, cx);
8608                state.set_selected_range(7..7, cx);
8609
8610                // The mask hides word boundaries, so a word delete takes
8611                // everything before the caret and leaves the rest.
8612                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8613                assert_eq!(state.value(), " ccc");
8614                assert_eq!(state.selected_range(), 0..0);
8615
8616                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
8617                assert_eq!(state.value(), "");
8618
8619                // A double click takes the whole value, not one word.
8620                state.set_value("aaa bbb ccc", window, cx);
8621                state.select_word(9, window, cx);
8622                assert_eq!(state.selected_range(), 0..11);
8623
8624                // Unmasked, the same delete only takes one word.
8625                state.set_masked(false, window, cx);
8626                state.set_value("aaa bbb ccc", window, cx);
8627                state.set_selected_range(11..11, cx);
8628                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8629                assert_eq!(state.value(), "aaa bbb ");
8630
8631                state.set_value("aaa bbb ccc", window, cx);
8632                state.select_word(9, window, cx);
8633                assert_eq!(state.selected_range(), 8..11);
8634            });
8635        });
8636    }
8637
8638    #[gpui::test]
8639    fn test_ctrl_delete_stops_at_whitespace(cx: &mut TestAppContext) {
8640        let input_view = InputView::build_textarea(cx, |state| state);
8641        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8642        let input = input_view.input;
8643
8644        cx.update(|window, cx| {
8645            input.update(cx, |state, cx| {
8646                // Indentation goes on its own, the word after it stays.
8647                state.set_value("    four leading spaces", window, cx);
8648                assert_eq!(state.next_word_delete_end_at(0, true), 4);
8649                assert_eq!(state.next_word_delete_end_at(4, true), 8);
8650                assert_eq!(state.next_word_delete_end_at(8, true), 9);
8651                // macOS Option+Delete still takes the blanks and the word.
8652                assert_eq!(state.next_word_delete_end_at(0, false), 8);
8653
8654                // At a line end only the line break goes, not the next
8655                // line's indentation or first word.
8656                state.set_value("one\n    two", window, cx);
8657                assert_eq!(state.next_word_delete_end_at(3, true), 4);
8658                state.set_value("one\r\n  two", window, cx);
8659                assert_eq!(state.next_word_delete_end_at(3, true), 5);
8660                // Trailing blanks stop at the line break.
8661                state.set_value("one  \ntwo", window, cx);
8662                assert_eq!(state.next_word_delete_end_at(3, true), 5);
8663
8664                state.set_value("    four leading spaces", window, cx);
8665                state.set_selected_range(0..0, cx);
8666                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
8667                #[cfg(not(target_os = "macos"))]
8668                assert_eq!(state.value(), "four leading spaces");
8669                #[cfg(target_os = "macos")]
8670                assert_eq!(state.value(), " leading spaces");
8671            });
8672        });
8673    }
8674
8675    #[gpui::test]
8676    fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
8677        let input_view = InputView::build(cx, |state| state);
8678        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8679        let input = input_view.input;
8680
8681        cx.update(|window, cx| {
8682            input.update(cx, |state, cx| {
8683                state.set_value("hunter2", window, cx);
8684                state.select_all(window, cx);
8685                assert!(state.context_menu_capabilities().is_copyable());
8686
8687                state.set_masked(true, window, cx);
8688                let capabilities = state.context_menu_capabilities();
8689                assert!(capabilities.is_masked());
8690                assert!(capabilities.has_selection());
8691                assert!(!capabilities.is_copyable());
8692            });
8693        });
8694    }
8695
8696    #[gpui::test]
8697    fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
8698        cx: &mut TestAppContext,
8699    ) {
8700        let input_view = InputView::build(cx, |state| state);
8701        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8702        let input = input_view.input;
8703
8704        cx.update(|window, cx| {
8705            input.update(cx, |state, cx| {
8706                state.replace_text_in_range(None, "alpha beta gamma", window, cx);
8707                state.set_selected_range(6..10, cx);
8708                state.cut(&Cut, window, cx);
8709                assert_eq!(state.value(), "alpha  gamma");
8710
8711                state.paste(&Paste, window, cx);
8712                state.paste(&Paste, window, cx);
8713                assert_eq!(state.value(), "alpha betabeta gamma");
8714
8715                state.undo(&Undo, window, cx);
8716                assert_eq!(state.value(), "alpha beta gamma");
8717                state.undo(&Undo, window, cx);
8718                assert_eq!(state.value(), "alpha  gamma");
8719                state.undo(&Undo, window, cx);
8720                assert_eq!(state.value(), "alpha beta gamma");
8721            });
8722        });
8723    }
8724
8725    #[gpui::test]
8726    fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
8727        let input_view = InputView::build_textarea(cx, |state| state);
8728        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8729        let input = input_view.input;
8730
8731        cx.update(|window, cx| {
8732            input.update(cx, |state, cx| {
8733                state.set_value("one two three\nfour five", window, cx);
8734                state.set_selected_range(13..13, cx);
8735                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8736                assert_eq!(state.value(), "one two \nfour five");
8737                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
8738                assert_eq!(state.value(), "one two four five");
8739
8740                state.undo(&Undo, window, cx);
8741                assert_eq!(state.value(), "one two \nfour five");
8742                state.undo(&Undo, window, cx);
8743                assert_eq!(state.value(), "one two three\nfour five");
8744            });
8745        });
8746    }
8747
8748    #[gpui::test]
8749    fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
8750        let input_view = InputView::build_textarea(cx, |state| state);
8751        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8752        let input = input_view.input;
8753
8754        cx.update(|window, cx| {
8755            input.update(cx, |state, cx| {
8756                state.replace_text_in_range(None, "before", window, cx);
8757                state.set_selected_range(0..6, cx);
8758                state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
8759                assert_eq!(state.value(), "line one\nline two\n第三行");
8760
8761                state.undo(&Undo, window, cx);
8762                assert_eq!(state.value(), "before");
8763                assert_eq!(state.selected_range(), 0..6);
8764                state.redo(&Redo, window, cx);
8765                assert_eq!(state.value(), "line one\nline two\n第三行");
8766            });
8767        });
8768    }
8769
8770    #[gpui::test]
8771    fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
8772        let input_view = InputView::build(cx, |state| state);
8773        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8774        let input = input_view.input;
8775
8776        cx.update(|window, cx| {
8777            input.update(cx, |state, cx| {
8778                state.replace_text_in_range(None, "prefix ", window, cx);
8779                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
8780                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
8781                state.replace_and_mark_text_in_range(None, "你", None, window, cx);
8782                state.unmark_text(window, cx);
8783                state.replace_text_in_range(None, " suffix", window, cx);
8784                assert_eq!(state.value(), "prefix 你 suffix");
8785
8786                state.undo(&Undo, window, cx);
8787                assert_eq!(state.value(), "prefix 你");
8788                state.undo(&Undo, window, cx);
8789                assert_eq!(state.value(), "prefix ");
8790                state.undo(&Undo, window, cx);
8791                assert_eq!(state.value(), "");
8792            });
8793        });
8794    }
8795
8796    #[gpui::test]
8797    fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
8798        let input_view = InputView::build(cx, |state| state);
8799        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8800        let input = input_view.input;
8801
8802        cx.update(|window, cx| {
8803            input.update(cx, |state, cx| {
8804                state.replace_text_in_range(None, "abc", window, cx);
8805                state.set_selected_range(1..2, cx);
8806                state.replace_text_in_range(None, "X", window, cx);
8807                state.replace_text_in_range(None, "z", window, cx);
8808                assert_eq!(state.value(), "aXzc");
8809
8810                state.undo(&Undo, window, cx);
8811                assert_eq!(state.value(), "aXc");
8812                state.undo(&Undo, window, cx);
8813                assert_eq!(state.value(), "abc");
8814                state.undo(&Undo, window, cx);
8815                assert_eq!(state.value(), "");
8816            });
8817        });
8818    }
8819
8820    #[gpui::test]
8821    fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
8822        let input_view = InputView::build(cx, |state| {
8823            state.mask_pattern(MaskPattern::Number {
8824                separator: None,
8825                fraction: None,
8826            })
8827        });
8828        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8829        let input = input_view.input;
8830
8831        cx.update(|window, cx| {
8832            input.update(cx, |state, cx| {
8833                state.replace_text_in_range(None, "1.2", window, cx);
8834
8835                // Delete the integer part "1": the value keeps the leading dot
8836                // (".2"), not completed to "0.2", so the digits before the dot
8837                // stay editable.
8838                let range = state.range_to_utf16(&(0..1));
8839                state.replace_text_in_range(Some(range), "", window, cx);
8840                assert_eq!(state.value(), ".2");
8841                let cursor: Range<usize> = state.selected_range();
8842                assert_eq!(cursor, 0..0);
8843
8844                // The user can type a new integer part.
8845                state.replace_text_in_range(Some(0..0), "3", window, cx);
8846                assert_eq!(state.value(), "3.2");
8847            });
8848        });
8849    }
8850
8851    #[gpui::test]
8852    fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
8853        // A pre-existing invalid text (e.g. a `default_value` that does not
8854        // conform) must not trap the user, the edit is allowed to fix it.
8855        let input_view = InputView::build(cx, |state| {
8856            state
8857                .mask_pattern(MaskPattern::Number {
8858                    separator: None,
8859                    fraction: None,
8860                })
8861                .default_value("1,234")
8862        });
8863        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8864        let input = input_view.input;
8865
8866        cx.update(|window, cx| {
8867            input.update(cx, |state, cx| {
8868                // Delete the last char, the pending text "1,23" is still
8869                // invalid, but the edit is allowed since the old text was
8870                // already invalid.
8871                let range = state.range_to_utf16(&(4..5));
8872                state.replace_text_in_range(Some(range), "", window, cx);
8873                assert_eq!(state.value(), "1,23");
8874
8875                // Once the text becomes valid, the validation works as usual.
8876                let range = state.range_to_utf16(&(1..2));
8877                state.replace_text_in_range(Some(range), "", window, cx);
8878                assert_eq!(state.value(), "123");
8879                state.replace_text_in_range(None, "a", window, cx);
8880                assert_eq!(state.value(), "123");
8881            });
8882        });
8883    }
8884
8885    /// After `set_value` on a single-line input the caret sits at the end (like
8886    /// HTML `<input>`), yet the view is scrolled back to the start so a long
8887    /// value shows its beginning instead of its tail.
8888    #[gpui::test]
8889    fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
8890        let input_view = InputView::build(cx, |state| state);
8891        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8892        let input = input_view.input;
8893
8894        // Long enough to overflow any reasonable single-line input width.
8895        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8896        let len = value.len();
8897
8898        // Right after `set_value`, before the next paint consumes the deferred
8899        // offset: caret is at the end, and the view is forced back to the start.
8900        cx.update(|window, cx| {
8901            input.update(cx, |state, cx| {
8902                state.set_value(value.clone(), window, cx);
8903
8904                assert_eq!(
8905                    state.selected_range(),
8906                    len..len,
8907                    "single-line caret should be at the end after set_value"
8908                );
8909                assert_eq!(
8910                    state.deferred_scroll_offset,
8911                    Some(point(px(0.), px(0.))),
8912                    "the view should be forced back to the start"
8913                );
8914            });
8915        });
8916
8917        // After a paint, the steady-state view stays at the start (x == 0) even
8918        // though the caret is at the far end.
8919        cx.run_until_parked();
8920        cx.update(|_, cx| {
8921            input.read_with(cx, |state, _| {
8922                assert!(
8923                    state.scroll_size.width > state.input_bounds.size.width,
8924                    "value must overflow the input width or this test is vacuous"
8925                );
8926                assert_eq!(
8927                    state.scroll_handle.offset().x,
8928                    px(0.),
8929                    "long value should display from its start, not its tail"
8930                );
8931            });
8932        });
8933    }
8934
8935    /// `replace_all` on a single-line input replaces the text, puts the
8936    /// caret at the end, and — like `set_value` — snaps the view back to the
8937    /// start so a long value shows its beginning instead of its tail.
8938    #[gpui::test]
8939    fn test_replace_all_single_line(cx: &mut TestAppContext) {
8940        let input_view = InputView::build(cx, |state| state);
8941        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8942        let input = input_view.input;
8943
8944        // Long enough to overflow any reasonable single-line input width.
8945        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8946        let len = value.len();
8947
8948        // Right after `replace_all`, before the next paint consumes the
8949        // deferred offset: caret is at the end, and the view is forced back
8950        // to the start.
8951        cx.update(|window, cx| {
8952            input.update(cx, |state, cx| {
8953                state.set_value("hello", window, cx);
8954                state.replace_all(value.clone(), window, cx);
8955                assert_eq!(state.value(), value);
8956                assert_eq!(
8957                    state.selected_range(),
8958                    len..len,
8959                    "single-line caret should be at the end after replace_all"
8960                );
8961                assert_eq!(
8962                    state.scroll_handle.offset(),
8963                    point(px(0.), px(0.)),
8964                    "the scroll offset should be reset to the start"
8965                );
8966                assert_eq!(
8967                    state.deferred_scroll_offset,
8968                    Some(point(px(0.), px(0.))),
8969                    "single-line should set a deferred scroll offset to keep the start visible"
8970                );
8971            });
8972        });
8973
8974        // After a paint, the steady-state view stays at the start (x == 0)
8975        // even though the caret is at the far end.
8976        cx.run_until_parked();
8977        cx.update(|_, cx| {
8978            input.read_with(cx, |state, _| {
8979                assert!(
8980                    state.scroll_size.width > state.input_bounds.size.width,
8981                    "value must overflow the input width or this test is vacuous"
8982                );
8983                assert_eq!(
8984                    state.scroll_handle.offset().x,
8985                    px(0.),
8986                    "long value should display from its start, not its tail"
8987                );
8988            });
8989        });
8990    }
8991
8992    /// Pasting past the right edge of a single-line input scrolls the caret
8993    /// into view in the paint that lays the pasted text out.
8994    #[gpui::test]
8995    fn test_paste_reveals_caret_single_line(cx: &mut TestAppContext) {
8996        let input_view = InputView::build(cx, |state| state);
8997        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8998        let input = input_view.input;
8999        cx.run_until_parked();
9000
9001        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9002        cx.update(|window, cx| {
9003            cx.write_to_clipboard(ClipboardItem::new_string(value.clone()));
9004            input.update(cx, |state, cx| state.paste(&Paste, window, cx));
9005        });
9006        cx.run_until_parked();
9007
9008        cx.update(|_, cx| {
9009            input.read_with(cx, |state, _| {
9010                assert!(
9011                    state.scroll_size.width > state.input_bounds.size.width,
9012                    "value must overflow the input width or this test is vacuous"
9013                );
9014                let caret = state
9015                    .last_layout
9016                    .as_ref()
9017                    .and_then(|layout| layout.cursor_bounds)
9018                    .expect("a caret");
9019                assert!(
9020                    caret.left() >= state.input_bounds.left()
9021                        && caret.right() <= state.input_bounds.right(),
9022                    "the caret at {caret:?} should be inside {:?}",
9023                    state.input_bounds
9024                );
9025            });
9026        });
9027    }
9028
9029    #[gpui::test]
9030    fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
9031        let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
9032        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9033        let input = input_view.input;
9034
9035        cx.update(|window, cx| {
9036            input.update(cx, |state, cx| {
9037                assert_eq!(state.value(), "defaultvalue");
9038
9039                state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
9040                assert_eq!(state.value(), "firstsecondthirdfourth");
9041
9042                state.set_value("", window, cx);
9043                state.insert("a\nb", window, cx);
9044                assert_eq!(state.value(), "ab");
9045            });
9046
9047            cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
9048            input.update(cx, |state, cx| {
9049                state.set_value("", window, cx);
9050                state.paste(&Paste, window, cx);
9051                assert_eq!(state.value(), "abcd");
9052            });
9053        });
9054
9055        cx.run_until_parked();
9056    }
9057
9058    /// `replace_all` on a multi-line (non-code-editor) input clears the
9059    /// selection to `0..0` and resets the scroll offset, but does not set a
9060    /// deferred scroll offset (single-line only).
9061    #[gpui::test]
9062    fn test_replace_all_multi_line(cx: &mut TestAppContext) {
9063        let input_view = InputView::build_textarea(cx, |state| state);
9064        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9065        let input = input_view.input;
9066
9067        cx.update(|window, cx| {
9068            input.update(cx, |state, cx| {
9069                state.set_value("foo\nbar", window, cx);
9070                state.replace_all("baz\nqux", window, cx);
9071                assert_eq!(state.value(), "baz\nqux");
9072                assert_eq!(
9073                    state.selected_range(),
9074                    0..0,
9075                    "multi-line selection should be cleared after replace_all"
9076                );
9077                assert_eq!(
9078                    state.scroll_handle.offset(),
9079                    point(px(0.), px(0.)),
9080                    "the scroll offset should be reset to the start"
9081                );
9082                assert!(
9083                    state.deferred_scroll_offset.is_none(),
9084                    "multi-line should not set a deferred scroll offset"
9085                );
9086            });
9087        });
9088    }
9089
9090    /// Unlike `set_value`, `replace_all` records the change so the user can
9091    /// undo it back to the previous text and redo to the new text.
9092    #[gpui::test]
9093    fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
9094        let input_view = InputView::build(cx, |state| state);
9095        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9096        let input = input_view.input;
9097
9098        cx.update(|window, cx| {
9099            input.update(cx, |state, cx| {
9100                // Seed with a value and clear history so the baseline is clean.
9101                state.set_value("first", window, cx);
9102                assert!(
9103                    !state.undo_manager.has_undos(),
9104                    "history should be empty after set_value"
9105                );
9106
9107                // replace_all records a single undoable change.
9108                state.replace_all("second", window, cx);
9109                assert_eq!(state.value(), "second");
9110                assert!(
9111                    state.undo_manager.has_undos(),
9112                    "replace_all should record an undo step"
9113                );
9114
9115                // Undo restores the previous text.
9116                state.undo(&Undo, window, cx);
9117                assert_eq!(state.value(), "first");
9118
9119                // Redo reapplies the replacement.
9120                state.redo(&Redo, window, cx);
9121                assert_eq!(state.value(), "second");
9122            });
9123        });
9124    }
9125
9126    /// `replace_all` on a code editor marks a pending update and resets LSP
9127    /// state, so diagnostics/completions refresh against the new text.
9128    #[gpui::test]
9129    fn test_replace_all_code_editor(cx: &mut TestAppContext) {
9130        let input_view = InputView::new(cx);
9131        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9132        let input = input_view.input;
9133
9134        cx.update(|window, cx| {
9135            input.update(cx, |state, cx| {
9136                // Plant a pending-update flag and some LSP state to verify reset.
9137                state.set_value("select 1", window, cx);
9138                state._pending_update = false;
9139
9140                state.replace_all("select 2", window, cx);
9141                assert_eq!(state.value(), "select 2");
9142                assert!(
9143                    state._pending_update,
9144                    "replace_all on a code editor should request a pending update"
9145                );
9146            });
9147        });
9148    }
9149
9150    #[gpui::test]
9151    fn test_set_selected_range(cx: &mut TestAppContext) {
9152        let input_view = InputView::build(cx, |state| state.default_value("hello world"));
9153        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9154        let input = input_view.input;
9155
9156        cx.update(|_, cx| {
9157            input.update(cx, |s, cx| {
9158                s.set_selected_range(0..5, cx);
9159                assert_eq!(s.selected_range(), 0..5);
9160                assert_eq!(s.selected_text().to_string(), "hello");
9161
9162                s.set_selected_range(6..11, cx);
9163                assert_eq!(s.selected_text().to_string(), "world");
9164
9165                // clamped + collapsed
9166                s.set_selected_range(100..100, cx);
9167                assert_eq!(s.selected_range(), 11..11);
9168            });
9169        });
9170    }
9171
9172    /// A single-edit batch round-trips through undo/redo.
9173    #[gpui::test]
9174    fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
9175        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9176        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9177        let input = input_view.input;
9178
9179        cx.update(|window, cx| {
9180            input.update(cx, |s, cx| {
9181                s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
9182                assert_eq!(s.value(), "HELLO world");
9183
9184                s.undo(&Undo, window, cx);
9185                assert_eq!(s.value(), "hello world");
9186
9187                s.redo(&Redo, window, cx);
9188                assert_eq!(s.value(), "HELLO world");
9189            });
9190        });
9191    }
9192
9193    /// A single undo restores the exact original text and a single redo
9194    /// re-applies all edits, verifying the back-to-front application ordering.
9195    #[gpui::test]
9196    fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
9197        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9198        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9199        let input = input_view.input;
9200
9201        cx.update(|window, cx| {
9202            input.update(cx, |s, cx| {
9203                // Two edits at different positions, given in pre-edit
9204                // coordinates and in arbitrary (non-sorted) order.
9205                s.replace_text_in_ranges(
9206                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9207                    window,
9208                    cx,
9209                );
9210                assert_eq!(s.value(), "X bbb Y");
9211
9212                // One collapsed cursor per edit, at the end of each inserted text.
9213                let cursors: Vec<usize> =
9214                    s.selections.iter().map(|sel| sel.cursor_offset()).collect();
9215                assert_eq!(cursors, vec![1, 7]);
9216
9217                // The whole batch is a single undo transaction.
9218                assert_eq!(s.undo_manager.undo_count(), 1);
9219
9220                // One undo restores the exact original text.
9221                s.undo(&Undo, window, cx);
9222                assert_eq!(s.value(), "aaa bbb ccc");
9223
9224                // One redo re-applies all edits.
9225                s.redo(&Redo, window, cx);
9226                assert_eq!(s.value(), "X bbb Y");
9227            });
9228        });
9229    }
9230
9231    /// A multi-edit change reaches the highlighter once, with every edit in
9232    /// application order and the text right after each, which is what the
9233    /// default `update_batch` replays through `update` one edit at a time.
9234    #[gpui::test]
9235    fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
9236        use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
9237        use gpui::HighlightStyle;
9238        use std::cell::RefCell;
9239
9240        struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
9241
9242        impl InputHighlighter for RecordingHighlighter {
9243            fn language(&self) -> SharedString {
9244                "recording".into()
9245            }
9246
9247            fn update(
9248                &mut self,
9249                _: Option<InputEdit>,
9250                text: &Rope,
9251                _: bool,
9252                _: &mut Window,
9253                _: &mut Context<EditorState>,
9254            ) {
9255                self.0.borrow_mut().push(vec![text.to_string()]);
9256            }
9257
9258            fn update_batch(
9259                &mut self,
9260                edits: &[(InputEdit, Rope)],
9261                _: bool,
9262                _: &mut Window,
9263                _: &mut Context<EditorState>,
9264            ) {
9265                let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
9266                self.0.borrow_mut().push(texts);
9267            }
9268
9269            fn styles(
9270                &self,
9271                range: &Range<usize>,
9272                _: &dyn HighlightStyleResolver,
9273            ) -> Vec<(Range<usize>, HighlightStyle)> {
9274                vec![(range.clone(), HighlightStyle::default())]
9275            }
9276
9277            fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
9278                Vec::new()
9279            }
9280        }
9281
9282        let updates = Rc::new(RefCell::new(Vec::new()));
9283        let input_view = InputView::new(cx);
9284        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9285        let input = input_view.input;
9286
9287        cx.update(|window, cx| {
9288            input.update(cx, |s, cx| {
9289                s.set_value("aaa bbb ccc", window, cx);
9290                let recorded = updates.clone();
9291                s.set_highlighter_factory(
9292                    Rc::new(move |_: &str| {
9293                        let highlighter: Box<dyn InputHighlighter> =
9294                            Box::new(RecordingHighlighter(recorded.clone()));
9295                        Some(highlighter)
9296                    }),
9297                    cx,
9298                );
9299                s.replace_text_in_ranges(
9300                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9301                    window,
9302                    cx,
9303                );
9304            });
9305        });
9306
9307        assert_eq!(
9308            *updates.borrow(),
9309            vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
9310        );
9311    }
9312
9313    /// One keypress records a single edit with the text right after it.
9314    #[gpui::test]
9315    fn test_last_input_edits_single_insert(cx: &mut TestAppContext) {
9316        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9317        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9318        let input = input_view.input;
9319
9320        cx.update(|window, cx| {
9321            input.update(cx, |state, cx| {
9322                state.replace_text_in_ranges(&[(5..5, " big".to_string())], window, cx);
9323
9324                let edits = state.last_input_edits.as_slice();
9325                assert_eq!(edits.len(), 1);
9326                let (edit, text_after) = &edits[0];
9327                assert_eq!(edit.start_byte, 5);
9328                assert_eq!(edit.old_end_byte, 5);
9329                assert_eq!(edit.new_end_byte, 9);
9330                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9331                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9332                assert_eq!(edit.new_end_position, crate::input::Point::new(0, 9));
9333                assert_eq!(text_after.to_string(), "hello big world");
9334            });
9335        });
9336    }
9337
9338    /// Deletion and a multi-line paste each describe their whole replacement.
9339    #[gpui::test]
9340    fn test_last_input_edits_delete_and_paste(cx: &mut TestAppContext) {
9341        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9342        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9343        let input = input_view.input;
9344
9345        cx.update(|window, cx| {
9346            input.update(cx, |state, cx| {
9347                state.replace_text_in_ranges(&[(5..11, String::new())], window, cx);
9348                assert_eq!(state.value(), "hello");
9349
9350                let edits = state.last_input_edits.as_slice();
9351                assert_eq!(edits.len(), 1);
9352                let (edit, text_after) = &edits[0];
9353                assert_eq!(edit.start_byte, 5);
9354                assert_eq!(edit.old_end_byte, 11);
9355                assert_eq!(edit.new_end_byte, 5);
9356                assert_eq!(text_after.to_string(), "hello");
9357
9358                state.replace_text_in_ranges(&[(5..5, "\nnext".to_string())], window, cx);
9359                assert_eq!(state.value(), "hello\nnext");
9360
9361                let edits = state.last_input_edits.as_slice();
9362                assert_eq!(edits.len(), 1);
9363                let (edit, text_after) = &edits[0];
9364                assert_eq!(edit.start_byte, 5);
9365                assert_eq!(edit.old_end_byte, 5);
9366                assert_eq!(edit.new_end_byte, 10);
9367                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9368                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9369                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 4));
9370                assert_eq!(text_after.to_string(), "hello\nnext");
9371            });
9372        });
9373    }
9374
9375    /// A grouped change records every applied edit in application order.
9376    #[gpui::test]
9377    fn test_last_input_edits_grouped_change(cx: &mut TestAppContext) {
9378        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9379        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9380        let input = input_view.input;
9381
9382        cx.update(|window, cx| {
9383            input.update(cx, |state, cx| {
9384                state.replace_text_in_ranges(
9385                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9386                    window,
9387                    cx,
9388                );
9389                assert_eq!(state.value(), "X bbb Y");
9390
9391                let edits = state.last_input_edits.as_slice();
9392                assert_eq!(edits.len(), 2);
9393                // The higher offset is applied first, before the lower one.
9394                assert_eq!(edits[0].0.start_byte, 8);
9395                assert_eq!(edits[0].0.old_end_byte, 11);
9396                assert_eq!(edits[0].0.new_end_byte, 9);
9397                assert_eq!(edits[0].0.start_position, crate::input::Point::new(0, 8));
9398                assert_eq!(edits[0].0.old_end_position, crate::input::Point::new(0, 11));
9399                assert_eq!(edits[0].0.new_end_position, crate::input::Point::new(0, 9));
9400                assert_eq!(edits[0].1.to_string(), "aaa bbb Y");
9401
9402                assert_eq!(edits[1].0.start_byte, 0);
9403                assert_eq!(edits[1].0.old_end_byte, 3);
9404                assert_eq!(edits[1].0.new_end_byte, 1);
9405                assert_eq!(edits[1].0.start_position, crate::input::Point::new(0, 0));
9406                assert_eq!(edits[1].0.old_end_position, crate::input::Point::new(0, 3));
9407                assert_eq!(edits[1].0.new_end_position, crate::input::Point::new(0, 1));
9408                assert_eq!(edits[1].1.to_string(), "X bbb Y");
9409            });
9410        });
9411    }
9412
9413    /// Edits are recorded even when no highlighter can be installed.
9414    #[gpui::test]
9415    fn test_last_input_edits_without_a_highlighter(cx: &mut TestAppContext) {
9416        let input_view = InputView::new(cx);
9417        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9418        let input = input_view.input;
9419
9420        cx.update(|window, cx| {
9421            input.update(cx, |state, cx| {
9422                state.set_value("fn main() {}", window, cx);
9423                let no_highlighter: InputHighlighterFactory = Rc::new(|_: &str| None);
9424                state.set_highlighter_factory(no_highlighter, cx);
9425                assert!(state.last_input_edits.as_slice().is_empty());
9426
9427                state.replace_text_in_ranges(&[(12..12, "\n".to_string())], window, cx);
9428                assert_eq!(state.value(), "fn main() {}\n");
9429
9430                let edits = state.last_input_edits.as_slice();
9431                assert_eq!(edits.len(), 1);
9432                let (edit, text_after) = &edits[0];
9433                assert_eq!(edit.start_byte, 12);
9434                assert_eq!(edit.old_end_byte, 12);
9435                assert_eq!(edit.new_end_byte, 13);
9436                assert_eq!(edit.start_position, crate::input::Point::new(0, 12));
9437                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 12));
9438                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 0));
9439                assert_eq!(text_after.to_string(), "fn main() {}\n");
9440            });
9441        });
9442    }
9443
9444    /// `set_value` is silent and leaves no edits behind for the next change.
9445    #[gpui::test]
9446    fn test_last_input_edits_cleared_by_set_value(cx: &mut TestAppContext) {
9447        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9448        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9449        let input = input_view.input;
9450
9451        cx.update(|window, cx| {
9452            input.update(cx, |state, cx| {
9453                state.replace_text_in_ranges(&[(5..5, "!".to_string())], window, cx);
9454                assert_eq!(state.last_input_edits.as_slice().len(), 1);
9455
9456                state.set_value("replaced", window, cx);
9457                assert!(state.last_input_edits.as_slice().is_empty());
9458
9459                state.replace_text_in_ranges(&[(8..8, "?".to_string())], window, cx);
9460                let edits = state.last_input_edits.as_slice();
9461                assert_eq!(edits.len(), 1);
9462                assert_eq!(edits[0].1.to_string(), "replaced?");
9463            });
9464        });
9465    }
9466
9467    /// Apply an emitted batch as an incremental consumer would and verify every snapshot.
9468    fn replay_input_edits(text: &mut String, event: &InputEditsEvent) {
9469        for (edit, after) in event.edits() {
9470            let replacement = after.slice(edit.start_byte..edit.new_end_byte).to_string();
9471            text.replace_range(edit.start_byte..edit.old_end_byte, &replacement);
9472            assert_eq!(*text, after.to_string());
9473        }
9474    }
9475
9476    #[gpui::test]
9477    fn input_edits_events_preserve_queued_changes_and_undo(cx: &mut TestAppContext) {
9478        let view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9479        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9480        let input = view.input;
9481        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9482        let seen = observed.clone();
9483        let _subscription = cx.update(|_, cx| {
9484            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9485                seen.borrow_mut().push(event.clone());
9486            })
9487        });
9488        cx.update(|window, cx| {
9489            input.update(cx, |state, cx| {
9490                state.replace_text_in_ranges(&[(5..5, "!".into())], window, cx);
9491                state.replace_text_in_ranges(&[(6..6, "?".into())], window, cx);
9492                state.undo(&Undo, window, cx);
9493            });
9494        });
9495        let events = observed.borrow();
9496        assert!(events.len() >= 3);
9497        let mut text = "hello".to_string();
9498        for event in events.iter() {
9499            replay_input_edits(&mut text, event);
9500        }
9501        assert_eq!(
9502            text,
9503            input.read_with(&cx, |state, _| state.value().to_string())
9504        );
9505        assert_eq!(events[0].edits()[0].1.to_string(), "hello!");
9506        assert_eq!(events[1].edits()[0].1.to_string(), "hello!?");
9507    }
9508
9509    #[gpui::test]
9510    fn input_edits_event_replays_ime_commit(cx: &mut TestAppContext) {
9511        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9512        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9513        let input = view.input;
9514        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9515        let seen = observed.clone();
9516        let _subscription = cx.update(|_, cx| {
9517            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9518                seen.borrow_mut().push(event.clone());
9519            })
9520        });
9521        cx.update(|window, cx| {
9522            input.update(cx, |state, cx| {
9523                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9524                state.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
9525                state.replace_text_in_range(None, "你", window, cx);
9526            });
9527        });
9528        let events = observed.borrow();
9529        assert_eq!(events.len(), 1);
9530        let mut text = String::new();
9531        replay_input_edits(&mut text, &events[0]);
9532        assert_eq!(text, "你");
9533    }
9534
9535    #[gpui::test]
9536    fn input_edits_event_replays_after_cancelled_composition(cx: &mut TestAppContext) {
9537        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9538        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9539        let input = view.input;
9540        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9541        let seen = observed.clone();
9542        let _subscription = cx.update(|_, cx| {
9543            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9544                seen.borrow_mut().push(event.clone());
9545            })
9546        });
9547        cx.update(|window, cx| {
9548            input.update(cx, |state, cx| {
9549                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9550                state.replace_and_mark_text_in_range(None, "", None, window, cx);
9551                state.replace_text_in_range(None, "x", window, cx);
9552            });
9553        });
9554        let events = observed.borrow();
9555        assert_eq!(events.len(), 1);
9556        let mut text = String::new();
9557        replay_input_edits(&mut text, &events[0]);
9558        assert_eq!(text, "x");
9559    }
9560
9561    /// A platform may end a composition with `unmark_text` alone, keeping the
9562    /// preedit as committed text; that is one change, and only one.
9563    #[gpui::test]
9564    fn unmark_reports_the_kept_preedit_as_one_change(cx: &mut TestAppContext) {
9565        let view = InputView::build(cx, |state| state.default_value(""));
9566        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9567        let input = view.input;
9568        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9569        let seen = observed.clone();
9570        let _subscription = cx.update(|_, cx| {
9571            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9572                seen.borrow_mut().push(event.clone());
9573            })
9574        });
9575        let step = |cx: &mut VisualTestContext,
9576                    f: &dyn Fn(
9577            &mut crate::input::InputState,
9578            &mut Window,
9579            &mut Context<crate::input::InputState>,
9580        )| {
9581            cx.update(|window, cx| input.update(cx, |state, cx| f(state, window, cx)));
9582            observed.borrow().len()
9583        };
9584
9585        let composed = step(&mut cx, &|state, window, cx| {
9586            state.replace_and_mark_text_in_range(None, "s", None, window, cx);
9587            state.replace_and_mark_text_in_range(None, "slider", None, window, cx);
9588        });
9589        assert_eq!(composed, 0);
9590        assert_eq!(
9591            step(&mut cx, &|state, window, cx| state.unmark_text(window, cx)),
9592            1
9593        );
9594        let mut text = String::new();
9595        replay_input_edits(&mut text, &observed.borrow()[0]);
9596        assert_eq!(text, "slider");
9597
9598        // Unmarking again, or after a cancelled preedit, changes nothing.
9599        let after = step(&mut cx, &|state, window, cx| {
9600            state.unmark_text(window, cx);
9601            state.replace_and_mark_text_in_range(None, "x", None, window, cx);
9602            state.replace_and_mark_text_in_range(None, "", None, window, cx);
9603            state.unmark_text(window, cx);
9604        });
9605        assert_eq!(after, 1);
9606        input.read_with(&cx, |state, _| assert_eq!(state.value(), "slider"));
9607    }
9608
9609    /// Text input is accepted only while focused, so a platform ends the
9610    /// composition of an input that loses focus.
9611    #[gpui::test]
9612    fn ime_accepts_text_only_while_focused(cx: &mut TestAppContext) {
9613        let view = InputView::build(cx, |state| state);
9614        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9615        let input = view.input;
9616        cx.update(|window, cx| {
9617            assert!(!input.update(cx, |state, cx| state.accepts_text_input(window, cx)));
9618            input.update(cx, |state, cx| state.focus(window, cx));
9619            assert!(input.update(cx, |state, cx| state.accepts_text_input(window, cx)));
9620            cx.focus_handle().focus(window, cx);
9621            assert!(!input.update(cx, |state, cx| state.accepts_text_input(window, cx)));
9622        });
9623    }
9624
9625    #[gpui::test]
9626    fn input_edits_event_replays_mask_rewrite(cx: &mut TestAppContext) {
9627        let view = InputView::build(cx, |state| {
9628            state
9629                .mask_pattern(MaskPattern::Number {
9630                    separator: Some(','),
9631                    fraction: None,
9632                })
9633                .default_value("999")
9634        });
9635        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9636        let input = view.input;
9637        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9638        let seen = observed.clone();
9639        let _subscription = cx.update(|_, cx| {
9640            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9641                seen.borrow_mut().push(event.clone());
9642            })
9643        });
9644        cx.update(|window, cx| {
9645            input.update(cx, |state, cx| {
9646                state.set_cursor_to(3);
9647                state.replace_text_in_range(None, "9", window, cx)
9648            });
9649        });
9650        let events = observed.borrow();
9651        assert_eq!(events.len(), 1);
9652        let mut text = "999".to_string();
9653        replay_input_edits(&mut text, &events[0]);
9654        assert_eq!(text, "9,999");
9655    }
9656
9657    /// An IME composition (marking then commit) undoes as a single unit.
9658    #[gpui::test]
9659    fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
9660        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
9661        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9662        let input = input_view.input;
9663
9664        cx.update(|window, cx| {
9665            input.update(cx, |s, cx| {
9666                // Simulate an IME composition: mark, refine, then commit.
9667                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9668                s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
9669                s.replace_text_in_range(None, "你", window, cx);
9670                assert_eq!(s.value(), "你");
9671
9672                // The entire composition is one undo transaction.
9673                assert_eq!(s.undo_manager.undo_count(), 1);
9674
9675                s.undo(&Undo, window, cx);
9676                assert_eq!(s.value(), "");
9677
9678                s.redo(&Redo, window, cx);
9679                assert_eq!(s.value(), "你");
9680            });
9681        });
9682    }
9683
9684    /// A keystroke right after a committed composition must be its own undo
9685    /// entry, not merged into the (finalized) composition transaction.
9686    #[gpui::test]
9687    fn test_edit_after_composition_is_separate_undo(cx: &mut TestAppContext) {
9688        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
9689        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9690        let input = input_view.input;
9691
9692        cx.update(|window, cx| {
9693            input.update(cx, |s, cx| {
9694                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9695                s.replace_text_in_range(None, "你", window, cx);
9696                assert_eq!(s.value(), "你");
9697                assert_eq!(s.undo_manager.undo_count(), 1);
9698
9699                // Typing after the commit is a distinct transaction.
9700                s.replace_text_in_range(None, "x", window, cx);
9701                assert_eq!(s.value(), "你x");
9702                assert_eq!(s.undo_manager.undo_count(), 2);
9703
9704                s.undo(&Undo, window, cx);
9705                assert_eq!(s.value(), "你");
9706                s.undo(&Undo, window, cx);
9707                assert_eq!(s.value(), "");
9708            });
9709        });
9710    }
9711
9712    /// Canceling a composition via `unmark_text` closes its transaction so it
9713    /// does not leak and swallow a later edit.
9714    #[gpui::test]
9715    fn test_composition_cancel_via_unmark_does_not_leak(cx: &mut TestAppContext) {
9716        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
9717        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9718        let input = input_view.input;
9719
9720        cx.update(|window, cx| {
9721            input.update(cx, |s, cx| {
9722                // Start a composition, then cancel it via unmark.
9723                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9724                s.unmark_text(window, cx);
9725                let after_cancel = s.undo_manager.undo_count();
9726
9727                // A later edit is recorded independently.
9728                s.replace_text_in_range(None, "x", window, cx);
9729                assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
9730            });
9731        });
9732    }
9733
9734    #[gpui::test]
9735    fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
9736        let input_view = InputView::build(cx, |state| state.default_value("éx"));
9737        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9738        let input = input_view.input;
9739
9740        cx.update(|window, cx| {
9741            input.update(cx, |state, cx| {
9742                state.set_selected_range(0..1, cx);
9743                assert_eq!(state.selected_range(), 0..2);
9744                state.copy(&Copy, window, cx);
9745
9746                state.set_selected_range(1..1, cx);
9747                assert_eq!(state.selected_range(), 0..0);
9748            });
9749        });
9750    }
9751
9752    #[gpui::test]
9753    fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
9754        let input_view = InputView::build(cx, |state| state.default_value("你好 "));
9755        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9756        let input = input_view.input;
9757
9758        cx.update(|window, cx| {
9759            input.update(cx, |state, cx| {
9760                state.set_selected_range(7..7, cx);
9761                state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
9762                state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
9763
9764                assert_eq!(state.value(), "你好 sh");
9765                assert_eq!(state.selected_range(), 9..9);
9766                assert_eq!(state.ime_marked_range, Some((7..9).into()));
9767            });
9768        });
9769    }
9770
9771    #[gpui::test]
9772    fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
9773        let input_view = InputView::build(cx, |state| state);
9774        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9775        let input = input_view.input;
9776
9777        cx.update(|window, cx| {
9778            input.update(cx, |state, cx| {
9779                state.set_value("a", window, cx);
9780                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
9781                state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
9782                state.replace_text_in_range(None, "是", window, cx);
9783                assert_eq!(state.value(), "a是");
9784
9785                state.undo(&Undo, window, cx);
9786                assert_eq!(state.value(), "a");
9787                state.redo(&Redo, window, cx);
9788                assert_eq!(state.value(), "a是");
9789            });
9790        });
9791    }
9792
9793    #[gpui::test]
9794    fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
9795        let input_view = InputView::build(cx, |state| state);
9796        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9797        let input = input_view.input;
9798
9799        cx.update(|window, cx| {
9800            input.update(cx, |state, cx| {
9801                // First composition: "jin" -> "今天"
9802                state.replace_and_mark_text_in_range(None, "j", None, window, cx);
9803                state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
9804                state.replace_text_in_range(None, "今天", window, cx);
9805                // Second composition: "wo" -> "我们"
9806                state.replace_and_mark_text_in_range(None, "w", None, window, cx);
9807                state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
9808                state.replace_text_in_range(None, "我们", window, cx);
9809                assert_eq!(state.value(), "今天我们");
9810                assert_eq!(state.selected_range(), 12..12);
9811
9812                state.undo(&Undo, window, cx);
9813                assert_eq!(state.value(), "今天");
9814                assert_eq!(state.selected_range(), 6..6);
9815
9816                state.undo(&Undo, window, cx);
9817                assert_eq!(state.value(), "");
9818                assert_eq!(state.selected_range(), 0..0);
9819
9820                state.redo(&Redo, window, cx);
9821                assert_eq!(state.value(), "今天");
9822                assert_eq!(state.selected_range(), 6..6);
9823
9824                state.redo(&Redo, window, cx);
9825                assert_eq!(state.value(), "今天我们");
9826                assert_eq!(state.selected_range(), 12..12);
9827            });
9828        });
9829    }
9830
9831    #[gpui::test]
9832    fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
9833        let input_view = InputView::build(cx, |state| state);
9834        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9835        let input = input_view.input;
9836
9837        cx.update(|window, cx| {
9838            input.update(cx, |state, cx| {
9839                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
9840                state.replace_text_in_range(None, "你", window, cx);
9841                state.undo_manager.set_pending_intent(EditIntent::Typing);
9842                state.replace_text_in_range(None, "a", window, cx);
9843                state.undo_manager.set_pending_intent(EditIntent::Typing);
9844                state.replace_text_in_range(None, "b", window, cx);
9845                assert_eq!(state.value(), "你ab");
9846
9847                state.undo(&Undo, window, cx);
9848                assert_eq!(state.value(), "你");
9849
9850                state.undo(&Undo, window, cx);
9851                assert_eq!(state.value(), "");
9852            });
9853        });
9854    }
9855
9856    #[gpui::test]
9857    fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
9858        let input_view = InputView::build(cx, |state| state);
9859        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9860        let input = input_view.input;
9861
9862        cx.update(|window, cx| {
9863            input.update(cx, |state, cx| {
9864                state.set_value("a", window, cx);
9865                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
9866                state.replace_and_mark_text_in_range(None, "", None, window, cx);
9867
9868                assert_eq!(state.value(), "a");
9869                assert!(!state.undo_manager.has_undos());
9870            });
9871        });
9872    }
9873
9874    /// The macOS Korean IME rewrites the character it just inserted.
9875    #[gpui::test]
9876    fn test_undo_manager_ime_rewrites_of_typed_char_are_one_group(cx: &mut TestAppContext) {
9877        let input_view = InputView::build(cx, |state| state);
9878        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9879        let input = input_view.input;
9880
9881        cx.update(|window, cx| {
9882            input.update(cx, |state, cx| {
9883                state.set_value("é ", window, cx);
9884                state.set_selected_range(3..3, cx);
9885                // g k s r m f: "ㅎ" -> "하" -> "한", then "ㄱ" -> "그" -> "글"
9886                state.replace_text_in_range(None, "ㅎ", window, cx);
9887                state.replace_text_in_range(Some(2..3), "하", window, cx);
9888                state.replace_text_in_range(Some(2..3), "한", window, cx);
9889                state.replace_text_in_range(None, "ㄱ", window, cx);
9890                state.replace_text_in_range(Some(3..4), "그", window, cx);
9891                state.replace_text_in_range(Some(3..4), "글", window, cx);
9892                assert_eq!(state.value(), "é 한글");
9893                assert_eq!(state.undo_manager.undo_count(), 1);
9894
9895                state.undo(&Undo, window, cx);
9896                assert_eq!(state.value(), "é ");
9897                assert_eq!(state.selected_range(), 3..3);
9898
9899                state.redo(&Redo, window, cx);
9900                assert_eq!(state.value(), "é 한글");
9901                assert_eq!(state.selected_range(), 9..9);
9902            });
9903        });
9904    }
9905
9906    #[gpui::test]
9907    fn test_undo_manager_rewrite_after_cursor_movement_is_separate(cx: &mut TestAppContext) {
9908        let input_view = InputView::build(cx, |state| state);
9909        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9910        let input = input_view.input;
9911
9912        cx.update(|window, cx| {
9913            input.update(cx, |state, cx| {
9914                state.replace_text_in_range(None, "c", window, cx);
9915                state.replace_text_in_range(None, "e", window, cx);
9916                state.left(&MoveLeft, window, cx);
9917                state.right(&MoveRight, window, cx);
9918                state.replace_text_in_range(Some(1..2), "é", window, cx);
9919                assert_eq!(state.value(), "cé");
9920
9921                state.undo(&Undo, window, cx);
9922                assert_eq!(state.value(), "ce");
9923                state.undo(&Undo, window, cx);
9924                assert_eq!(state.value(), "");
9925            });
9926        });
9927    }
9928
9929    #[gpui::test]
9930    fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
9931        let input_view = InputView::build(cx, |state| state);
9932        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9933        let input = input_view.input;
9934
9935        cx.update(|window, cx| {
9936            input.update(cx, |state, cx| {
9937                state.set_value("abc", window, cx);
9938                state.set_selected_range(1..2, cx);
9939                state.replace_text_in_range(None, "X", window, cx);
9940
9941                state.undo(&Undo, window, cx);
9942                assert_eq!(state.value(), "abc");
9943                assert_eq!(state.selected_range(), 1..2);
9944
9945                state.redo(&Redo, window, cx);
9946                assert_eq!(state.value(), "aXc");
9947                assert_eq!(state.selected_range(), 2..2);
9948            });
9949        });
9950    }
9951
9952    #[gpui::test]
9953    fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
9954        let input_view = InputView::build(cx, |state| state);
9955        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9956        let input = input_view.input;
9957
9958        cx.update(|window, cx| {
9959            input.update(cx, |state, cx| {
9960                state.set_value("abc", window, cx);
9961                state.set_selected_range(1..1, cx);
9962                state.delete(&Delete, window, cx);
9963
9964                state.undo(&Undo, window, cx);
9965                assert_eq!(state.value(), "abc");
9966                assert_eq!(state.selected_range(), 1..1);
9967            });
9968        });
9969    }
9970
9971    #[gpui::test]
9972    fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
9973        let input_view = InputView::build(cx, |state| state);
9974        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9975        let input = input_view.input;
9976
9977        cx.update(|window, cx| {
9978            input.update(cx, |state, cx| {
9979                state.replace_text_in_range(None, "ab", window, cx);
9980                state.undo(&Undo, window, cx);
9981                state.set_selected_range(0..0, cx);
9982                state.redo(&Redo, window, cx);
9983                assert_eq!(state.value(), "ab");
9984
9985                state.undo(&Undo, window, cx);
9986                state.replace_text_in_range(None, "x", window, cx);
9987                state.redo(&Redo, window, cx);
9988                assert_eq!(state.value(), "x");
9989            });
9990        });
9991    }
9992
9993    #[gpui::test]
9994    fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
9995        let input_view = InputView::build(cx, |state| state);
9996        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9997        let input = input_view.input;
9998
9999        cx.update(|window, cx| {
10000            input.update(cx, |state, cx| {
10001                state.replace_text_in_range(None, "a", window, cx);
10002                state.move_to(0, None, cx);
10003                state.replace_text_in_range(None, "", window, cx);
10004                state.undo(&Undo, window, cx);
10005                assert_eq!(state.value(), "");
10006                state.redo(&Redo, window, cx);
10007                assert_eq!(state.value(), "a");
10008                assert_eq!(state.cursor(), 1);
10009            });
10010        });
10011    }
10012
10013    #[gpui::test]
10014    fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
10015        let input_view = InputView::build(cx, |state| state);
10016        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10017        let input = input_view.input;
10018
10019        cx.update(|window, cx| {
10020            input.update(cx, |state, cx| {
10021                state.replace_text_in_range(None, "a", window, cx);
10022                state.left(&MoveLeft, window, cx);
10023                state.right(&MoveRight, window, cx);
10024                state.replace_text_in_range(None, "b", window, cx);
10025
10026                state.undo(&Undo, window, cx);
10027                assert_eq!(state.value(), "a");
10028                state.undo(&Undo, window, cx);
10029                assert_eq!(state.value(), "");
10030            });
10031        });
10032    }
10033
10034    #[gpui::test]
10035    fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
10036        cx: &mut TestAppContext,
10037    ) {
10038        let input_view = InputView::build(cx, |state| state);
10039        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10040        let input = input_view.input;
10041
10042        cx.update(|window, cx| {
10043            input.update(cx, |state, cx| {
10044                state.replace_text_in_range(None, "alpha", window, cx);
10045                state.replace_text_in_range(None, "", window, cx);
10046                state.replace_text_in_range(None, "beta", window, cx);
10047                assert_eq!(state.value(), "alphabeta");
10048
10049                state.undo(&Undo, window, cx);
10050                assert_eq!(state.value(), "alpha");
10051                state.undo(&Undo, window, cx);
10052                assert_eq!(state.value(), "");
10053            });
10054        });
10055    }
10056
10057    #[gpui::test]
10058    fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
10059        let input_view = InputView::build(cx, |state| {
10060            state.mask_pattern(MaskPattern::Number {
10061                separator: Some(','),
10062                fraction: None,
10063            })
10064        });
10065        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10066        let input = input_view.input;
10067
10068        cx.update(|window, cx| {
10069            input.update(cx, |state, cx| {
10070                state.set_value("12345", window, cx);
10071                state.set_selected_range(2..2, cx);
10072                state.replace_text_in_range(None, "9", window, cx);
10073                let selection_after_edit = state.selected_range();
10074                assert_ne!(selection_after_edit.end, state.value().len());
10075
10076                state.undo(&Undo, window, cx);
10077                state.redo(&Redo, window, cx);
10078                assert_eq!(state.selected_range(), selection_after_edit);
10079            });
10080        });
10081    }
10082
10083    /// Unfolding at a position opens exactly the folds hiding it.
10084    ///
10085    /// A fold keeps its own first and last line visible, so a position on
10086    /// either of them opens nothing. Nested folds all open at once, sibling
10087    /// folds stay closed, and the opened ranges stay fold candidates.
10088    #[gpui::test]
10089    fn test_unfold_at(cx: &mut TestAppContext) {
10090        use crate::input::{FoldRange, Position};
10091
10092        let view = InputView::<EditorMode>::new(cx);
10093        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10094        let input = view.input;
10095
10096        // An outer fold over lines 0..=5, a fold nested inside it, and a
10097        // sibling fold that must never be touched.
10098        cx.update(|window, cx| {
10099            input.update(cx, |state, cx| {
10100                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
10101                state.apply_highlighter_fold_candidates(
10102                    vec![
10103                        FoldRange::new(0, 5),
10104                        FoldRange::new(2, 4),
10105                        FoldRange::new(7, 10),
10106                    ],
10107                    cx,
10108                );
10109                state.display_map.set_folded(0, true);
10110                state.display_map.set_folded(2, true);
10111                state.display_map.set_folded(7, true);
10112            });
10113        });
10114
10115        // The outer fold's own first and last line stay visible, so neither
10116        // position opens anything.
10117        for line in [0, 5] {
10118            cx.update(|_, cx| {
10119                input.update(cx, |state, cx| {
10120                    assert!(!state.display_map.is_buffer_line_hidden(line));
10121                    assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
10122                });
10123                input.read_with(cx, |state, _| {
10124                    assert!(state.display_map.is_folded_at(0));
10125                    assert!(state.display_map.is_folded_at(2));
10126                    assert!(state.display_map.is_folded_at(7));
10127                });
10128            });
10129        }
10130
10131        // Line 3 is hidden by both the outer and the nested fold, so both
10132        // open; the sibling fold does not.
10133        cx.update(|_, cx| {
10134            input.update(cx, |state, cx| {
10135                assert!(state.unfold_at(Position::new(3, 0), cx));
10136            });
10137            input.read_with(cx, |state, _| {
10138                assert!(!state.display_map.is_buffer_line_hidden(3));
10139                assert!(!state.display_map.is_folded_at(0));
10140                assert!(!state.display_map.is_folded_at(2));
10141                assert!(state.display_map.is_folded_at(7));
10142                // The opened ranges are still candidates for refolding.
10143                assert!(state.display_map.is_fold_candidate(0));
10144                assert!(state.display_map.is_fold_candidate(2));
10145            });
10146        });
10147
10148        // Nothing is hidden there any more, so a second call is a no-op.
10149        cx.update(|_, cx| {
10150            input.update(cx, |state, cx| {
10151                assert!(!state.unfold_at(Position::new(3, 0), cx));
10152            });
10153        });
10154    }
10155
10156    /// Losing focus hides the hover popover but keeps the decorations.
10157    ///
10158    /// Both used to be dropped by one call, so clicking away threw away
10159    /// decorations the application had installed and never asked to remove.
10160    #[gpui::test]
10161    fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
10162        let view = InputView::<EditorMode>::new(cx);
10163        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10164        let input = view.input;
10165
10166        cx.update(|window, cx| {
10167            input.update(cx, |state, cx| {
10168                state.set_value("select 1", window, cx);
10169                let _collection = state.create_decorations_collection(
10170                    vec![crate::input::TextDecoration::new(
10171                        0..6,
10172                        gpui::HighlightStyle {
10173                            font_weight: Some(gpui::FontWeight::BOLD),
10174                            ..Default::default()
10175                        },
10176                    )],
10177                    cx,
10178                );
10179                state.present_hover(
10180                    0..6,
10181                    lsp_types::Hover {
10182                        contents: lsp_types::HoverContents::Scalar(
10183                            lsp_types::MarkedString::String("docs".into()),
10184                        ),
10185                        range: None,
10186                    },
10187                    cx,
10188                );
10189                assert!(state.hover_popover().is_some());
10190
10191                state.on_blur(window, cx);
10192
10193                assert!(
10194                    state.hover_popover().is_none(),
10195                    "blur should hide the hover popover"
10196                );
10197                let decorations = state.extras.decoration_layers();
10198                assert!(
10199                    decorations.iter().any(|layer| !layer.is_empty()),
10200                    "blur must not discard decorations"
10201                );
10202            });
10203        });
10204    }
10205
10206    /// The mode marker is the only source of truth for the kind of input.
10207    ///
10208    /// An auto-growing textarea capped at one row used to report itself as
10209    /// single-line, because the answer was derived from the row counts.
10210    #[gpui::test]
10211    fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
10212        let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
10213        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10214        view.input.read_with(&mut cx, |state, _| {
10215            assert!(state.is_multi_line());
10216            assert!(!state.is_single_line());
10217            assert!(!state.is_code_editor());
10218        });
10219    }
10220
10221    #[gpui::test]
10222    fn test_textarea_prewrap_prepares_content_rows_before_layout(cx: &mut TestAppContext) {
10223        cx.update(crate::init);
10224        for (value, expected_rows) in [("", 1), ("one\ntwo", 2)] {
10225            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10226                let font = window.text_style().font();
10227                cx.new(|cx| {
10228                    let mut state = crate::input::TextareaState::new(window, cx)
10229                        .rows(12)
10230                        .default_value(value);
10231                    assert_eq!(state.display_map().wrap_row_count(), 0);
10232                    state.prewrap(font, px(14.), px(120.), cx);
10233                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10234                    assert_eq!(state.value(), value);
10235                    state
10236                });
10237                gpui::EmptyView
10238            });
10239        }
10240    }
10241
10242    #[gpui::test]
10243    fn test_textarea_prewrap_respects_soft_wrap_before_layout(cx: &mut TestAppContext) {
10244        cx.update(crate::init);
10245        let value = "select id, name, email, phone from users where active\nlimit 10";
10246        for soft_wrap in [true, false] {
10247            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10248                let font = window.text_style().font();
10249                cx.new(|cx| {
10250                    let mut state = crate::input::TextareaState::new(window, cx)
10251                        .rows(1)
10252                        .soft_wrap(soft_wrap)
10253                        .default_value(value);
10254                    state.prewrap(font, px(14.), px(120.), cx);
10255                    let rows = state.display_map().wrap_row_count();
10256                    if soft_wrap {
10257                        assert!(rows > 2, "the first logical line must wrap");
10258                    } else {
10259                        assert_eq!(rows, 2);
10260                    }
10261                    assert_eq!(state.value(), value);
10262                    state
10263                });
10264                gpui::EmptyView
10265            });
10266        }
10267    }
10268
10269    #[gpui::test]
10270    fn test_prewrap_counts_wrapped_rows_before_the_first_paint(cx: &mut TestAppContext) {
10271        cx.update(crate::init);
10272        let text = "select id, name, email, phone from users where active\nlimit 10";
10273        for (soft_wrap, wraps) in [(true, true), (false, false)] {
10274            let mut input = None;
10275            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10276                let font = window.text_style().font();
10277                let editor = cx.new(|cx| {
10278                    let mut state = crate::input::EditorState::new(window, cx)
10279                        .soft_wrap(soft_wrap)
10280                        .default_value(text);
10281                    state.prewrap(font, px(14.), px(120.), cx);
10282                    state
10283                });
10284                input = Some(editor);
10285                gpui::EmptyView
10286            });
10287            let rows = input
10288                .unwrap()
10289                .read_with(cx, |state, _| state.display_map().wrap_row_count());
10290            // Two lines; at 120px the first wraps unless soft wrap is off.
10291            assert_eq!(rows > 2, wraps, "soft_wrap({soft_wrap}): {rows} rows");
10292            if !wraps {
10293                assert_eq!(rows, 2);
10294            }
10295        }
10296    }
10297
10298    #[gpui::test]
10299    fn test_prewrap_uses_the_configured_tab_stops(cx: &mut TestAppContext) {
10300        cx.update(crate::init);
10301        cx.open_window(size(px(400.), px(100.)), |window, cx| {
10302            let font = window.text_style().font();
10303            let font_size = px(14.);
10304            let font_id = window.text_system().resolve_font(&font);
10305            let space_width = window.text_system().layout_width(font_id, font_size, ' ');
10306            cx.new(|cx| {
10307                let mut state = crate::input::EditorState::new(window, cx)
10308                    .tab_size(TabSize {
10309                        tab_size: 4,
10310                        hard_tabs: true,
10311                    })
10312                    .default_value("\t\t");
10313                for (tab_size, expected_rows) in [(4, 2), (2, 1), (8, 2)] {
10314                    state.set_tab_size(
10315                        TabSize {
10316                            tab_size,
10317                            hard_tabs: true,
10318                        },
10319                        cx,
10320                    );
10321                    state.prewrap(font.clone(), font_size, space_width * 5. + RIGHT_MARGIN, cx);
10322                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10323                }
10324                state
10325            });
10326            gpui::EmptyView
10327        });
10328    }
10329
10330    /// Prewrap counts with the state's wrapping indent, as the first layout
10331    /// does: continuation rows indented as deep as their line take more rows.
10332    #[gpui::test]
10333    fn test_prewrap_wraps_with_the_wrapping_indent(cx: &mut TestAppContext) {
10334        cx.update(crate::init);
10335        let text = "            select id, name, email, phone from users where active";
10336        let mut rows = Vec::new();
10337        for indent in [WrappingIndent::Same, WrappingIndent::None] {
10338            let mut input = None;
10339            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10340                let font = window.text_style().font();
10341                input = Some(cx.new(|cx| {
10342                    let mut state = crate::input::EditorState::new(window, cx)
10343                        .wrapping_indent(indent)
10344                        .default_value(text);
10345                    state.prewrap(font, px(14.), px(200.), cx);
10346                    state
10347                }));
10348                gpui::EmptyView
10349            });
10350            rows.push(
10351                input
10352                    .unwrap()
10353                    .read_with(cx, |state, _| state.display_map().wrap_row_count()),
10354            );
10355        }
10356        assert!(rows[0] > rows[1], "rows with Same, None: {rows:?}");
10357    }
10358
10359    /// Once the editor is laid out, layout owns the wrap and prewrap leaves it.
10360    #[gpui::test]
10361    fn test_prewrap_does_nothing_once_laid_out(cx: &mut TestAppContext) {
10362        struct Frame(Entity<crate::input::EditorState>);
10363        impl Render for Frame {
10364            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10365                crate::input::InputBase::new("frame")
10366                    .h(px(100.))
10367                    .child(crate::input::Editor::new(&self.0))
10368            }
10369        }
10370
10371        cx.update(crate::init);
10372        let text = "select id, name, email, phone from users where active\nlimit 10";
10373        let mut input = None;
10374        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
10375            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
10376            input = Some(state.clone());
10377            Frame(state)
10378        });
10379        let input = input.unwrap();
10380        let mut cx = VisualTestContext::from_window(window.into(), cx);
10381        cx.update(|window, cx| window.draw(cx).clear(cx));
10382
10383        let laid_out = input.read_with(&cx, |state, _| state.display_map().wrap_row_count());
10384        assert!(laid_out >= 2, "laid out to {laid_out} rows");
10385        let font = cx.update(|window, _| window.text_style().font());
10386        input.update(&mut cx, |state, cx| {
10387            state.prewrap(font, px(14.), px(60.), cx)
10388        });
10389        assert_eq!(
10390            input.read_with(&cx, |state, _| state.display_map().wrap_row_count()),
10391            laid_out
10392        );
10393    }
10394
10395    /// Soft wrap is on by default, for every mode that can wrap.
10396    ///
10397    /// The default lives in the shared constructor, where a mode-specific
10398    /// `new` can silently fail to restore it; this pins it down.
10399    #[gpui::test]
10400    fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
10401        let textarea = InputView::build_textarea(cx, |state| state);
10402        let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
10403        textarea
10404            .input
10405            .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
10406
10407        let editor = InputView::<EditorMode>::new(cx);
10408        let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
10409        editor
10410            .input
10411            .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
10412    }
10413
10414    /// Parse a cursor spec into `(text, cursor_offsets)`. Non-empty lines are
10415    /// joined with `\n` plus a trailing `\n`. `|` marks a cursor. Leading
10416    /// whitespace is kept, so a spec can express indentation.
10417    fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
10418        let mut full_text = String::new();
10419        let mut cursor_offsets = Vec::new();
10420        let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
10421
10422        for (line_idx, line) in non_empty_lines.iter().enumerate() {
10423            let mut positions = Vec::new();
10424            let mut text = String::new();
10425            for ch in line.chars() {
10426                if ch == '|' {
10427                    positions.push(text.len());
10428                } else {
10429                    text.push(ch);
10430                }
10431            }
10432
10433            if line_idx > 0 {
10434                full_text.push('\n');
10435            }
10436            let line_start = full_text.len();
10437            for pos in positions {
10438                cursor_offsets.push(line_start + pos);
10439            }
10440            full_text.push_str(&text);
10441        }
10442        full_text.push('\n');
10443
10444        (full_text, cursor_offsets)
10445    }
10446
10447    /// Build a multi-line input for multi-cursor tests.
10448    fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
10449        InputView::build_textarea(cx, |state| state)
10450    }
10451
10452    /// Set the text and cursor positions from a spec (see [`parse_cursor_spec`]).
10453    fn setup_cursors<M: InputModeKind>(
10454        cx: &mut VisualTestContext,
10455        input: &Entity<InputBaseState<M>>,
10456        spec: &str,
10457    ) {
10458        let (full_text, offsets) = parse_cursor_spec(spec);
10459        cx.update(|window, cx| {
10460            input.update(cx, |state, cx| {
10461                state.set_value(&full_text, window, cx);
10462                let selections = offsets
10463                    .into_iter()
10464                    .map(|offset| {
10465                        CursorSelection::new(state.selections.generate_id(), offset, offset)
10466                    })
10467                    .collect();
10468                state.selections.replace_all(selections);
10469                cx.notify();
10470            });
10471        });
10472    }
10473
10474    /// Assert the text and cursor positions match a spec.
10475    #[track_caller]
10476    fn assert_cursors<M: InputModeKind>(
10477        cx: &mut VisualTestContext,
10478        input: &Entity<InputBaseState<M>>,
10479        spec: &str,
10480    ) {
10481        let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
10482        expected_cursors.sort();
10483
10484        let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
10485            (
10486                state.text.to_string(),
10487                state
10488                    .selections
10489                    .iter()
10490                    .map(|s| s.cursor_offset())
10491                    .collect::<Vec<_>>(),
10492            )
10493        });
10494        actual_cursors.sort();
10495
10496        assert_eq!(
10497            actual_text, expected_text,
10498            "Text mismatch:\nExpected: {expected_text:?}\nActual:   {actual_text:?}"
10499        );
10500        assert_eq!(
10501            actual_cursors, expected_cursors,
10502            "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual:   {actual_cursors:?}"
10503        );
10504    }
10505
10506    #[gpui::test]
10507    fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
10508        cx.update(crate::init);
10509        let view = InputView::<EditorMode>::new(cx);
10510        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10511        for modifiers in [
10512            gpui::Modifiers {
10513                alt: true,
10514                ..Default::default()
10515            },
10516            gpui::Modifiers {
10517                alt: true,
10518                shift: true,
10519                ..Default::default()
10520            },
10521            #[cfg(target_os = "linux")]
10522            gpui::Modifiers {
10523                alt: true,
10524                control: true,
10525                ..Default::default()
10526            },
10527        ] {
10528            setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
10529            cx.update(|window, cx| {
10530                view.input.update(cx, |state, cx| state.focus(window, cx));
10531            });
10532            let (start, end) = view.input.read_with(&cx, |state, _| {
10533                let layout = state.last_layout.as_ref().unwrap();
10534                let origin = state.last_bounds.unwrap().origin;
10535                let position = |row: usize, col| {
10536                    let local = layout.lines[row]
10537                        .position_for_index(col, layout, false)
10538                        .unwrap();
10539                    origin
10540                        + point(
10541                            layout.line_number_width + local.x,
10542                            layout.line_height * (row as f32 + 0.5),
10543                        )
10544                };
10545                (position(0, 1), position(2, 3))
10546            });
10547            // Land inside the third column instead of exactly on its trailing
10548            // glyph boundary, where pixel rounding can select the next column.
10549            let end = point(end.x - px(0.5), end.y);
10550            // A cached Ctrl-hover definition must not steal a column gesture.
10551            cx.update(|_, cx| {
10552                view.input.update(cx, |state, _| {
10553                    state.extras.hover_definition.update(
10554                        0..4,
10555                        vec![lsp_types::LocationLink {
10556                            origin_selection_range: None,
10557                            target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
10558                            target_range: Default::default(),
10559                            target_selection_range: Default::default(),
10560                        }],
10561                    );
10562                });
10563            });
10564            cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10565            cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10566            cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10567            view.input.read_with(&cx, |state, _| {
10568                let ranges: Vec<_> = state
10569                    .selections
10570                    .iter()
10571                    .map(|sel| sel.start..sel.end)
10572                    .collect();
10573                assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
10574            });
10575            // Moving after release must leave the block intact.
10576            cx.simulate_mouse_move(start, None, modifiers);
10577            cx.simulate_keystrokes("x");
10578            assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
10579        }
10580    }
10581
10582    #[gpui::test]
10583    fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
10584        cx.update(crate::init);
10585        let view = InputView::<EditorMode>::new(cx);
10586        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10587        setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
10588        cx.update(|window, cx| {
10589            view.input.update(cx, |state, cx| state.focus(window, cx));
10590        });
10591        let (start, end) = view.input.read_with(&cx, |state, _| {
10592            let layout = state.last_layout.as_ref().unwrap();
10593            let origin = state.last_bounds.unwrap().origin;
10594            let local = layout.lines[0]
10595                .position_for_index(1, layout, false)
10596                .unwrap();
10597            let x = layout.line_number_width + local.x;
10598            (
10599                origin + point(x, layout.line_height * 2.5),
10600                origin + point(x, layout.line_height * 0.5),
10601            )
10602        });
10603        let modifiers = gpui::Modifiers {
10604            alt: true,
10605            ..Default::default()
10606        };
10607        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10608        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10609        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10610        assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
10611    }
10612
10613    #[gpui::test]
10614    fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
10615        cx.update(crate::init);
10616        let view = InputView::<EditorMode>::new(cx);
10617        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10618        setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
10619        cx.update(|window, cx| {
10620            view.input.update(cx, |state, cx| state.focus(window, cx));
10621        });
10622        // Drag from row 0 column 1 down to row 1, at the x of row 0's column 5. Row 1
10623        // only has two characters, so the pointer ends past its end.
10624        let (start, end) = view.input.read_with(&cx, |state, _| {
10625            let layout = state.last_layout.as_ref().unwrap();
10626            let origin = state.last_bounds.unwrap().origin;
10627            let x_of = |index| {
10628                layout.line_number_width
10629                    + layout.lines[0]
10630                        .position_for_index(index, layout, false)
10631                        .unwrap()
10632                        .x
10633            };
10634            (
10635                origin + point(x_of(1), layout.line_height * 0.5),
10636                origin + point(x_of(5), layout.line_height * 1.5),
10637            )
10638        });
10639        let modifiers = gpui::Modifiers {
10640            alt: true,
10641            shift: true,
10642            ..Default::default()
10643        };
10644        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10645        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10646        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10647
10648        // The short row is clipped to its own end; the long row keeps the full span.
10649        view.input.read_with(&cx, |state, _| {
10650            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
10651            assert_eq!(ranges, vec![(1, 5), (8, 9)]);
10652        });
10653    }
10654
10655    #[gpui::test]
10656    fn test_lost_mouse_release_ends_selection_on_plain_motion(cx: &mut TestAppContext) {
10657        cx.update(crate::init);
10658        let view = InputView::build_textarea(cx, |state| state);
10659        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10660        setup_cursors(&mut cx, &view.input, "|alpha bravo charlie delta");
10661        let (start, end, beyond) = view.input.read_with(&cx, |state, _| {
10662            (
10663                state.range_to_bounds(&(0..1)).unwrap().center(),
10664                state.range_to_bounds(&(6..7)).unwrap().center(),
10665                state.range_to_bounds(&(18..19)).unwrap().center(),
10666            )
10667        });
10668        cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
10669        cx.simulate_mouse_move(end, MouseButton::Left, gpui::Modifiers::default());
10670        let selected = view.input.read_with(&cx, |state, _| {
10671            assert!(state.selecting);
10672            let text = state.selected_value();
10673            assert!(!text.is_empty());
10674            text
10675        });
10676        cx.simulate_mouse_move(beyond, None, gpui::Modifiers::default());
10677        view.input.read_with(&cx, |state, _| {
10678            assert!(!state.selecting);
10679            assert_eq!(state.selected_value(), selected);
10680        });
10681    }
10682
10683    #[gpui::test]
10684    fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
10685        cx.update(crate::init);
10686        let view = InputView::<EditorMode>::new(cx);
10687        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10688        setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
10689        let position = view.input.read_with(&cx, |state, _| {
10690            let layout = state.last_layout.as_ref().unwrap();
10691            state.last_bounds.unwrap().origin
10692                + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
10693        });
10694        let modifiers = gpui::Modifiers {
10695            alt: true,
10696            ..Default::default()
10697        };
10698        cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
10699        cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
10700        view.input.read_with(&cx, |state, _| {
10701            assert!(!state.selecting);
10702            assert!(state.column_select_start.is_none());
10703        });
10704    }
10705
10706    #[gpui::test]
10707    fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
10708        let view = InputView::<EditorMode>::new(cx);
10709        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10710        setup_cursors(&mut cx, &view.input, "a|b");
10711        cx.update(|window, cx| {
10712            view.input.update(cx, |state, cx| {
10713                state.focus(window, cx);
10714                state.pause_blink_cursor(cx);
10715            });
10716        });
10717        cx.run_until_parked();
10718        cx.executor()
10719            .advance_clock(std::time::Duration::from_millis(300));
10720        cx.run_until_parked();
10721        view.input.read_with(&cx, |state, cx| {
10722            assert!(!state.blink_cursor.read(cx).visible());
10723        });
10724        // Copy consumes its shortcut without editing text or moving selections.
10725        for _ in 0..5 {
10726            #[cfg(target_os = "macos")]
10727            cx.simulate_keystrokes("cmd-c");
10728            #[cfg(not(target_os = "macos"))]
10729            cx.simulate_keystrokes("ctrl-c");
10730            cx.run_until_parked();
10731            cx.executor()
10732                .advance_clock(std::time::Duration::from_millis(200));
10733            cx.run_until_parked();
10734            view.input.read_with(&cx, |state, cx| {
10735                assert!(state.blink_cursor.read(cx).visible());
10736            });
10737        }
10738    }
10739
10740    #[gpui::test]
10741    fn test_mouse_down_shows_cursor_like_a_cursor_move(cx: &mut TestAppContext) {
10742        cx.update(crate::init);
10743        let view = InputView::<EditorMode>::new(cx);
10744        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10745        setup_cursors(&mut cx, &view.input, "abcd|efgh");
10746        let position = |offset: Pixels, cx: &mut VisualTestContext| {
10747            view.input.read_with(cx, |state, _| {
10748                let layout = state.last_layout.as_ref().unwrap();
10749                state.last_bounds.unwrap().origin
10750                    + point(layout.line_number_width + offset, layout.line_height * 0.5)
10751            })
10752        };
10753        let visible = |cx: &mut VisualTestContext| {
10754            view.input
10755                .read_with(cx, |state, cx| state.blink_cursor.read(cx).visible())
10756        };
10757
10758        // The press itself shows the caret, without waiting for the focus
10759        // observer, and the idle delay holds it there like a cursor move.
10760        let first = position(px(2.), &mut cx);
10761        cx.simulate_mouse_down(first, MouseButton::Left, Default::default());
10762        assert!(visible(&mut cx));
10763        cx.simulate_mouse_up(first, MouseButton::Left, Default::default());
10764        cx.run_until_parked();
10765
10766        // Pressing elsewhere in the focused input, in the hidden phase of the
10767        // blink, shows the caret again at the press.
10768        cx.executor()
10769            .advance_clock(std::time::Duration::from_millis(400));
10770        cx.run_until_parked();
10771        assert!(!visible(&mut cx));
10772        let second = position(px(30.), &mut cx);
10773        cx.simulate_mouse_down(second, MouseButton::Left, Default::default());
10774        assert!(visible(&mut cx));
10775        cx.executor()
10776            .advance_clock(std::time::Duration::from_millis(250));
10777        cx.run_until_parked();
10778        assert!(visible(&mut cx));
10779        cx.simulate_mouse_up(second, MouseButton::Left, Default::default());
10780    }
10781
10782    #[gpui::test]
10783    fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
10784        let view = InputView::<EditorMode>::new(cx);
10785        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10786        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
10787        // Start each action in the hidden phase without depending on a
10788        // key-down listener: actions and text input also arrive directly.
10789        for action in 0..6 {
10790            cx.update(|_, cx| {
10791                view.input.update(cx, |state, cx| {
10792                    state.blink_cursor = cx.new(BlinkCursor::new);
10793                    state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
10794                });
10795            });
10796            cx.run_until_parked();
10797            cx.executor()
10798                .advance_clock(std::time::Duration::from_millis(500));
10799            cx.run_until_parked();
10800            view.input.read_with(&cx, |state, cx| {
10801                assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
10802            });
10803
10804            cx.update(|window, cx| {
10805                view.input.update(cx, |state, cx| {
10806                    match action {
10807                        0 => state.add_cursor_above(&AddCursorAbove, window, cx),
10808                        1 => state.add_cursor_below(&AddCursorBelow, window, cx),
10809                        2 => state.select_up(&SelectUp, window, cx),
10810                        3 => state.select_down(&SelectDown, window, cx),
10811                        4 => state.replace_text_in_range(None, "x", window, cx),
10812                        _ => state.backspace(&Backspace, window, cx),
10813                    }
10814                    assert!(state.blink_cursor.read(cx).visible(), "action {action}");
10815                });
10816            });
10817        }
10818    }
10819
10820    #[gpui::test]
10821    fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
10822        let view = InputView::<EditorMode>::new(cx);
10823        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10824        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
10825        cx.update(|window, cx| {
10826            view.input.update(cx, |state, cx| state.focus(window, cx));
10827        });
10828        #[cfg(target_os = "macos")]
10829        cx.simulate_keystrokes("cmd-alt-up");
10830        #[cfg(target_os = "windows")]
10831        cx.simulate_keystrokes("ctrl-alt-up");
10832        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
10833        cx.simulate_keystrokes("alt-shift-up");
10834        view.input
10835            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
10836        #[cfg(target_os = "macos")]
10837        cx.simulate_keystrokes("cmd-alt-down");
10838        #[cfg(target_os = "windows")]
10839        cx.simulate_keystrokes("ctrl-alt-down");
10840        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
10841        cx.simulate_keystrokes("alt-shift-down");
10842        view.input
10843            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
10844        cx.simulate_keystrokes("x");
10845        assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
10846    }
10847
10848    #[gpui::test]
10849    fn test_multi_cursor_platform_word_selection_dispatch(cx: &mut TestAppContext) {
10850        let view = InputView::<EditorMode>::new(cx);
10851        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10852        setup_cursors(&mut cx, &view.input, "one |two\none |two");
10853        cx.update(|window, cx| {
10854            view.input.update(cx, |state, cx| state.focus(window, cx));
10855        });
10856        #[cfg(any(target_os = "macos", target_os = "linux"))]
10857        cx.simulate_keystrokes("alt-shift-right");
10858        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
10859        cx.simulate_keystrokes("ctrl-shift-right");
10860        cx.simulate_keystrokes("x");
10861        assert_cursors(&mut cx, &view.input, "one x|\none x|");
10862        setup_cursors(&mut cx, &view.input, "one two|\none two|");
10863        #[cfg(any(target_os = "macos", target_os = "linux"))]
10864        cx.simulate_keystrokes("alt-shift-left");
10865        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
10866        cx.simulate_keystrokes("ctrl-shift-left");
10867        cx.simulate_keystrokes("x");
10868        assert_cursors(&mut cx, &view.input, "one x|\none x|");
10869    }
10870
10871    #[cfg(not(target_os = "macos"))]
10872    #[gpui::test]
10873    fn test_multi_cursor_horizontal_selection_dispatch(cx: &mut TestAppContext) {
10874        let view = InputView::<EditorMode>::new(cx);
10875        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10876        setup_cursors(&mut cx, &view.input, "ab\na|b");
10877        cx.update(|window, cx| {
10878            view.input.update(cx, |state, cx| state.focus(window, cx));
10879        });
10880        #[cfg(target_os = "windows")]
10881        cx.simulate_keystrokes("ctrl-alt-up");
10882        #[cfg(not(target_os = "windows"))]
10883        cx.simulate_keystrokes("alt-shift-up");
10884        #[cfg(target_os = "linux")]
10885        cx.simulate_keystrokes("shift-right");
10886        #[cfg(not(target_os = "linux"))]
10887        cx.simulate_keystrokes("alt-shift-right");
10888        view.input.read_with(&cx, |state, _| {
10889            assert_eq!(
10890                state
10891                    .selections
10892                    .iter()
10893                    .map(|s| s.start..s.end)
10894                    .collect::<Vec<_>>(),
10895                vec![4..5, 1..2]
10896            );
10897        });
10898        #[cfg(target_os = "linux")]
10899        cx.simulate_keystrokes("shift-left shift-left");
10900        #[cfg(not(target_os = "linux"))]
10901        cx.simulate_keystrokes("alt-shift-left alt-shift-left");
10902        view.input.read_with(&cx, |state, _| {
10903            assert_eq!(
10904                state
10905                    .selections
10906                    .iter()
10907                    .map(|s| s.start..s.end)
10908                    .collect::<Vec<_>>(),
10909                vec![3..4, 0..1]
10910            );
10911        });
10912        cx.simulate_keystrokes("x");
10913        assert_cursors(&mut cx, &view.input, "x|b\nx|b");
10914    }
10915
10916    #[gpui::test]
10917    fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
10918        cx.update(crate::init);
10919        let view = InputView::<EditorMode>::new(cx);
10920        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10921        setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
10922        cx.update(|window, cx| {
10923            view.input.update(cx, |state, cx| state.focus(window, cx));
10924        });
10925        let position = view.input.read_with(&cx, |state, _| {
10926            let bounds = state.last_bounds.unwrap();
10927            let layout = state.last_layout.as_ref().unwrap();
10928            bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
10929        });
10930        cx.simulate_click(
10931            position,
10932            gpui::Modifiers {
10933                alt: true,
10934                ..Default::default()
10935            },
10936        );
10937        view.input
10938            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
10939    }
10940
10941    #[gpui::test]
10942    fn test_add_selection(cx: &mut TestAppContext) {
10943        let view = InputView::<EditorMode>::new(cx);
10944        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10945        cx.update(|window, cx| {
10946            view.input.update(cx, |state, cx| {
10947                state.focus(window, cx);
10948                state.set_value("foo bar foo", window, cx);
10949                state.set_selected_range(0..3, cx);
10950                // The programmatic second cursor: the next occurrence.
10951                state.add_selection(8..11, cx);
10952                // Adding a range that is already selected changes nothing.
10953                state.add_selection(0..3, cx);
10954            });
10955        });
10956        view.input.read_with(&cx, |state, _| {
10957            let mut ranges: Vec<Range<usize>> =
10958                state.selections.iter().map(|s| s.start..s.end).collect();
10959            ranges.sort_by_key(|r| r.start);
10960            assert_eq!(ranges, vec![0..3, 8..11]);
10961        });
10962        // Typing replaces every selection at once.
10963        cx.simulate_keystrokes("x");
10964        view.input.read_with(&cx, |state, _| {
10965            assert_eq!(state.text.to_string(), "x bar x")
10966        });
10967    }
10968
10969    #[gpui::test]
10970    fn test_add_selection_preserves_crlf_boundaries(cx: &mut TestAppContext) {
10971        let view = InputView::build_textarea(cx, |state| state.default_value("a\r\nb"));
10972        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10973        cx.update(|window, cx| {
10974            view.input.update(cx, |state, cx| {
10975                state.focus(window, cx);
10976                state.set_selected_range(4..4, cx);
10977                state.add_selection(2..2, cx);
10978                let ranges: Vec<_> = state.selections.iter().map(|s| s.start..s.end).collect();
10979                assert_eq!(ranges, vec![4..4, 1..1]);
10980            });
10981        });
10982        cx.simulate_keystrokes("x");
10983        view.input.read_with(&cx, |state, _| {
10984            assert_eq!(state.value(), "ax\r\nbx");
10985        });
10986        cx.update(|window, cx| {
10987            view.input.update(cx, |state, cx| {
10988                state.set_value("a\r\nb", window, cx);
10989                state.set_selected_range(4..4, cx);
10990                state.add_selection(2..3, cx);
10991                state.cut(&Cut, window, cx);
10992                assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "\r\n");
10993                assert_eq!(state.value(), "ab");
10994            });
10995        });
10996    }
10997
10998    #[gpui::test]
10999    fn test_add_selection_merges_overlaps_before_copy_and_cut(cx: &mut TestAppContext) {
11000        let view = InputView::<EditorMode>::new(cx);
11001        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11002        cx.update(|window, cx| {
11003            view.input.update(cx, |state, cx| {
11004                // Cover partial overlaps, a containing range, and a bridge
11005                // between two previously disjoint selections.
11006                for additions in [vec![2..5], vec![0..5], vec![4..5, 2..4]] {
11007                    state.set_value("abcdef", window, cx);
11008                    state.set_selected_range(0..3, cx);
11009                    let active_id = state.active_selection().id;
11010                    for range in additions {
11011                        state.add_selection(range, cx);
11012                    }
11013                    assert_eq!(state.active_selection().id, active_id);
11014                    assert_eq!(state.selected_range(), 0..5);
11015                    assert_eq!(state.selections.len(), 1);
11016                    state.copy(&Copy, window, cx);
11017                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11018                    state.cut(&Cut, window, cx);
11019                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11020                    assert_eq!(state.value(), "f");
11021                    state.undo(&Undo, window, cx);
11022                    assert_eq!(state.value(), "abcdef");
11023                    assert_eq!(state.selected_range(), 0..5);
11024                }
11025            });
11026        });
11027    }
11028
11029    #[gpui::test]
11030    fn test_add_selection_clears_inline_completion(cx: &mut TestAppContext) {
11031        use crate::input::CompletionProvider;
11032        use gpui::Task;
11033        use lsp_types::{
11034            CompletionContext, CompletionResponse, InlineCompletionContext, InlineCompletionItem,
11035            InlineCompletionResponse,
11036        };
11037        use std::time::Duration;
11038
11039        struct Provider(Rc<Cell<usize>>);
11040
11041        impl CompletionProvider for Provider {
11042            fn is_completion_trigger(&self, _: usize, _: &str, _: &mut App) -> bool {
11043                false
11044            }
11045
11046            fn completions(
11047                &self,
11048                _: &Rope,
11049                _: usize,
11050                _: CompletionContext,
11051                _: &mut Window,
11052                _: &mut App,
11053            ) -> Task<anyhow::Result<CompletionResponse>> {
11054                Task::ready(Ok(CompletionResponse::Array(vec![])))
11055            }
11056
11057            fn inline_completion(
11058                &self,
11059                _: &Rope,
11060                _: usize,
11061                _: InlineCompletionContext,
11062                _: &mut Window,
11063                _: &mut App,
11064            ) -> Task<anyhow::Result<InlineCompletionResponse>> {
11065                self.0.set(self.0.get() + 1);
11066                Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
11067            }
11068        }
11069
11070        let view = InputView::<EditorMode>::new(cx);
11071        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11072        let calls = Rc::new(Cell::new(0));
11073        cx.update(|window, cx| {
11074            view.input.update(cx, |state, cx| {
11075                state.focus(window, cx);
11076                state.set_value("aa\naa", window, cx);
11077                state.set_selected_range(2..2, cx);
11078                state.extras.inline_completion.item = Some(InlineCompletionItem {
11079                    insert_text: "suggestion".into(),
11080                    filter_text: None,
11081                    range: None,
11082                    command: None,
11083                    insert_text_format: None,
11084                });
11085                state.add_selection(5..5, cx);
11086                assert!(!state.has_inline_completion());
11087                state.indent_inline(&IndentInline, window, cx);
11088                assert_eq!(state.value(), "aa  \naa  ");
11089                assert_eq!(state.selections.len(), 2);
11090
11091                // The active cursor stays put, so only canceling the task
11092                // prevents this pending request from fetching a suggestion.
11093                state.set_value("aa\naa", window, cx);
11094                state.set_selected_range(2..2, cx);
11095                state.extras.lsp.completion_provider = Some(Rc::new(Provider(calls.clone())));
11096                state.schedule_inline_completion(window, cx);
11097            });
11098        });
11099        cx.run_until_parked();
11100        cx.update(|_, cx| {
11101            view.input
11102                .update(cx, |state, cx| state.add_selection(5..5, cx));
11103        });
11104        cx.executor().advance_clock(Duration::from_secs(1));
11105        cx.run_until_parked();
11106        assert_eq!(calls.get(), 0);
11107        view.input.read_with(&cx, |state, _| {
11108            assert!(!state.has_inline_completion());
11109            assert_eq!(state.selections.len(), 2);
11110            assert_eq!(state.value(), "aa\naa");
11111        });
11112    }
11113
11114    #[gpui::test]
11115    fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
11116        let view = multi_line(cx);
11117        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11118        setup_cursors(&mut cx, &view.input, "hello|");
11119        cx.update(|window, cx| {
11120            view.input.update(cx, |state, cx| {
11121                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
11122                state.undo(&Undo, window, cx);
11123                assert_eq!(state.selected_range(), 5..5);
11124            });
11125        });
11126    }
11127
11128    #[gpui::test]
11129    fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
11130        let view = multi_line(cx);
11131        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11132        setup_cursors(&mut cx, &view.input, "a|b|c");
11133        cx.update(|window, cx| {
11134            view.input.update(cx, |state, cx| {
11135                state.backspace(&Backspace, window, cx);
11136                state.undo(&Undo, window, cx);
11137            });
11138        });
11139        assert_cursors(&mut cx, &view.input, "a|b|c");
11140    }
11141
11142    #[gpui::test]
11143    fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
11144        let view = InputView::<EditorMode>::new(cx);
11145        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11146        cx.update(|window, cx| {
11147            view.input.update(cx, |state, cx| {
11148                state.set_value("abcdef ".repeat(30), window, cx);
11149                state.display_map.on_layout_changed(Some(px(60.)), cx);
11150                let line = state.display_map.line(0).unwrap();
11151                assert!(line.wrapped_lines.len() > 1);
11152                let boundary = line.wrapped_lines[0].end;
11153                state.move_to_with_affinity(boundary, None, true, cx);
11154                state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
11155                assert_eq!(state.selected_range(), boundary..state.text.len());
11156            });
11157        });
11158    }
11159
11160    #[gpui::test]
11161    fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
11162        let view = multi_line(cx);
11163        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11164        setup_cursors(&mut cx, &view.input, "|你好\n|世界");
11165        cx.update(|window, cx| {
11166            view.input.update(cx, |state, cx| {
11167                state.outdent(false, window, cx);
11168                state.outdent(true, window, cx);
11169            });
11170        });
11171        assert_cursors(&mut cx, &view.input, "|你好\n|世界");
11172    }
11173
11174    #[gpui::test]
11175    fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
11176        let view = multi_line(cx);
11177        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11178        setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
11179        cx.update(|window, cx| {
11180            view.input.update(cx, |state, cx| {
11181                state.build_columnar_selection(
11182                    ColumnarPoint::new(1, 0),
11183                    ColumnarPoint::new(11, 0),
11184                    cx,
11185                );
11186                let text = state.value();
11187                for sel in state.selections.iter() {
11188                    assert!(text.is_char_boundary(sel.start));
11189                    assert!(text.is_char_boundary(sel.end));
11190                }
11191                state.replace_text_in_range(None, "X", window, cx);
11192            });
11193        });
11194    }
11195
11196    #[gpui::test]
11197    fn test_cursor_moves_and_deletes_whole_graphemes(cx: &mut TestAppContext) {
11198        let input_view = InputView::build(cx, |state| state);
11199        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
11200        let input = input_view.input;
11201
11202        let graphemes = ["a", "\u{267B}\u{FE0F}", "👍🏽", "👨‍👩‍👧", "🇸🇪", "e\u{301}", "b"];
11203        let text = graphemes.concat();
11204        let ends: Vec<usize> = graphemes
11205            .iter()
11206            .scan(0, |end, g| {
11207                *end += g.len();
11208                Some(*end)
11209            })
11210            .collect();
11211
11212        cx.update(|window, cx| {
11213            input.update(cx, |state, cx| {
11214                state.set_value(text.clone(), window, cx);
11215                state.set_selected_range(0..0, cx);
11216                for &end in &ends {
11217                    state.right(&MoveRight, window, cx);
11218                    assert_eq!(state.cursor(), end);
11219                }
11220                for &end in ends.iter().rev().skip(1).chain([&0]) {
11221                    state.left(&MoveLeft, window, cx);
11222                    assert_eq!(state.cursor(), end);
11223                }
11224
11225                state.set_selected_range(ends[3]..ends[3], cx);
11226                state.backspace(&Backspace, window, cx);
11227                assert_eq!(
11228                    state.value(),
11229                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[4..].concat()
11230                );
11231                state.delete(&Delete, window, cx);
11232                assert_eq!(
11233                    state.value(),
11234                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[5..].concat()
11235                );
11236            });
11237        });
11238    }
11239
11240    #[gpui::test]
11241    fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
11242        let view = InputView::<EditorMode>::new(cx);
11243        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11244        cx.update(|window, cx| {
11245            view.input.update(cx, |state, cx| {
11246                state.set_value("abc def", window, cx);
11247                state.create_decorations_collection(
11248                    vec![crate::input::TextDecoration::new(
11249                        4..7,
11250                        gpui::HighlightStyle::default(),
11251                    )],
11252                    cx,
11253                );
11254                state.set_selected_range(0..0, cx);
11255                state.replace_text_in_range(None, "X", window, cx);
11256                let layers = state.extras.decoration_layers();
11257                assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
11258            });
11259        });
11260    }
11261
11262    #[gpui::test]
11263    fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
11264        let view = InputView::<EditorMode>::new(cx);
11265        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11266        setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
11267        cx.update(|window, cx| {
11268            view.input.update(cx, |state, cx| {
11269                set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
11270                state.backspace(&Backspace, window, cx);
11271            });
11272        });
11273        assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
11274    }
11275
11276    #[gpui::test]
11277    fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
11278        struct UnexpectedQuery;
11279        impl crate::input::SyntaxContextProvider for UnexpectedQuery {
11280            fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
11281                panic!("ordinary typing must not query syntax");
11282            }
11283        }
11284        let view = InputView::<EditorMode>::new(cx);
11285        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11286        setup_cursors(&mut cx, &view.input, "|");
11287        cx.update(|window, cx| {
11288            view.input.update(cx, |state, cx| {
11289                set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
11290                for c in ["a", "b", "c"] {
11291                    state.replace_text_in_range(None, c, window, cx);
11292                }
11293            });
11294        });
11295        assert_cursors(&mut cx, &view.input, "abc|");
11296    }
11297
11298    #[gpui::test]
11299    fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
11300        let view = InputView::<EditorMode>::new(cx);
11301        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11302        setup_cursors(&mut cx, &view.input, "|");
11303        cx.update(|window, cx| {
11304            view.input.update(cx, |state, cx| {
11305                for _ in 0..999 {
11306                    state.replace_text_in_range(None, "a", window, cx);
11307                }
11308                state.replace_text_in_range(None, "(", window, cx);
11309                state.undo(&Undo, window, cx);
11310                assert!(!state.text.to_string().contains('('));
11311                assert!(!state.text.to_string().contains(')'));
11312                state.redo(&Redo, window, cx);
11313            });
11314        });
11315        assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
11316    }
11317
11318    #[gpui::test]
11319    fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
11320        let view = InputView::<EditorMode>::new(cx);
11321        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11322        setup_cursors(&mut cx, &view.input, "// (|)");
11323        cx.update(|window, cx| {
11324            view.input.update(cx, |state, cx| {
11325                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11326                state.replace_text_in_range(None, ")", window, cx);
11327            });
11328        });
11329        assert_cursors(&mut cx, &view.input, "// ()|)");
11330    }
11331
11332    #[gpui::test]
11333    fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
11334        let view = InputView::<EditorMode>::new(cx);
11335        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11336        setup_cursors(&mut cx, &view.input, "(a|)");
11337        let before = view.input.read_with(&cx, |state, _| state.text.to_string());
11338        cx.update(|window, cx| {
11339            view.input.update(cx, |state, cx| {
11340                state.replace_text_in_range(Some(2..2), ")", window, cx);
11341            });
11342        });
11343        assert_cursors(&mut cx, &view.input, "(a)|");
11344        cx.update(|window, cx| {
11345            view.input
11346                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11347        });
11348        view.input.read_with(&cx, |state, _| {
11349            assert_eq!(
11350                state.text.to_string(),
11351                before,
11352                "skip must not remove an existing closer on undo"
11353            );
11354        });
11355    }
11356
11357    #[gpui::test]
11358    fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11359        let view = InputView::<EditorMode>::new(cx);
11360        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11361        setup_cursors(&mut cx, &view.input, "|");
11362        cx.update(|window, cx| {
11363            view.input.update(cx, |state, cx| {
11364                state.replace_text_in_range(None, "(", window, cx);
11365            });
11366        });
11367        assert_cursors(&mut cx, &view.input, "(|)");
11368        cx.update(|window, cx| {
11369            view.input.update(cx, |state, cx| {
11370                state.undo(&Undo, window, cx);
11371                state.redo(&Redo, window, cx);
11372            });
11373        });
11374        assert_cursors(&mut cx, &view.input, "(|)");
11375    }
11376
11377    #[gpui::test]
11378    fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11379        let view = InputView::<EditorMode>::new(cx);
11380        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11381        setup_cursors(&mut cx, &view.input, "{|}");
11382        cx.update(|window, cx| {
11383            view.input.update(cx, |state, cx| {
11384                state.enter(
11385                    &Enter {
11386                        secondary: false,
11387                        shift: false,
11388                    },
11389                    window,
11390                    cx,
11391                );
11392            });
11393        });
11394        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11395        cx.update(|window, cx| {
11396            view.input.update(cx, |state, cx| {
11397                state.undo(&Undo, window, cx);
11398            });
11399        });
11400        assert_cursors(&mut cx, &view.input, "{|}");
11401        cx.update(|window, cx| {
11402            view.input
11403                .update(cx, |state, cx| state.redo(&Redo, window, cx));
11404        });
11405        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11406    }
11407
11408    #[gpui::test]
11409    fn test_auto_close_parens(cx: &mut TestAppContext) {
11410        let view = InputView::<EditorMode>::new(cx);
11411        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11412        setup_cursors(&mut cx, &view.input, "|");
11413        cx.update(|window, cx| {
11414            view.input.update(cx, |state, cx| {
11415                state.replace_text_in_range(None, "(", window, cx);
11416            });
11417        });
11418        assert_cursors(&mut cx, &view.input, "(|)");
11419        // Selection must be collapsed: typing next must insert, not replace.
11420        cx.update(|window, cx| {
11421            view.input.update(cx, |state, cx| {
11422                state.replace_text_in_range(None, "x", window, cx);
11423            });
11424        });
11425        assert_cursors(&mut cx, &view.input, "(x|)");
11426    }
11427
11428    #[gpui::test]
11429    fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
11430        let view = InputView::<EditorMode>::new(cx);
11431        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11432        setup_cursors(&mut cx, &view.input, "(|)");
11433        cx.update(|window, cx| {
11434            view.input.update(cx, |state, cx| {
11435                state.replace_text_in_range(None, ")", window, cx);
11436            });
11437        });
11438        // No duplicate closer, cursor moves past the existing one.
11439        assert_cursors(&mut cx, &view.input, "()|");
11440        // Selection must be collapsed, not covering blank space.
11441        view.input.read_with(&cx, |state, _| {
11442            assert!(state.active_selection().is_empty());
11443        });
11444    }
11445
11446    #[gpui::test]
11447    fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
11448        let view = InputView::<EditorMode>::new(cx);
11449        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11450        setup_cursors(&mut cx, &view.input, "don|");
11451        cx.update(|window, cx| {
11452            view.input.update(cx, |state, cx| {
11453                state.replace_text_in_range(None, "'", window, cx);
11454            });
11455        });
11456        // Contraction: no auto-close.
11457        assert_cursors(&mut cx, &view.input, "don'|");
11458    }
11459
11460    #[gpui::test]
11461    fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
11462        let view = InputView::<EditorMode>::new(cx);
11463        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11464        // Unicode-safe previous-char lookup: must not panic on multi-byte prefix.
11465        // CJK counts as word-like, so no pairing — single quote inserted.
11466        setup_cursors(&mut cx, &view.input, "中|");
11467        cx.update(|window, cx| {
11468            view.input.update(cx, |state, cx| {
11469                state.replace_text_in_range(None, "'", window, cx);
11470            });
11471        });
11472        assert_cursors(&mut cx, &view.input, "中'|");
11473    }
11474
11475    #[gpui::test]
11476    fn test_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
11477        let view = InputView::<EditorMode>::new(cx);
11478        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11479        // Cursor before existing closing quote: typing `"` skips past it.
11480        setup_cursors(&mut cx, &view.input, "\"hello|\"");
11481        cx.update(|window, cx| {
11482            view.input.update(cx, |state, cx| {
11483                state.replace_text_in_range(None, "\"", window, cx);
11484            });
11485        });
11486        assert_cursors(&mut cx, &view.input, "\"hello\"|");
11487        view.input.read_with(&cx, |state, _| {
11488            assert!(state.active_selection().is_empty());
11489        });
11490    }
11491
11492    #[gpui::test]
11493    fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
11494        let view = InputView::<EditorMode>::new(cx);
11495        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11496        // UTF-16 conversion: deleting `()` after CJK must not touch neighbors.
11497        setup_cursors(&mut cx, &view.input, "中(|)abc");
11498        cx.update(|window, cx| {
11499            view.input
11500                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11501        });
11502        assert_cursors(&mut cx, &view.input, "中|abc");
11503    }
11504
11505    #[gpui::test]
11506    fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
11507        let view = InputView::<EditorMode>::new(cx);
11508        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11509        setup_cursors(&mut cx, &view.input, "{|}");
11510        cx.update(|window, cx| {
11511            view.input.update(cx, |state, cx| {
11512                state.set_smart_indent(false, window, cx);
11513                state.enter(
11514                    &Enter {
11515                        secondary: false,
11516                        shift: false,
11517                    },
11518                    window,
11519                    cx,
11520                );
11521            });
11522        });
11523        // Smart indent controls both structural splitting and extra indentation.
11524        assert_cursors(&mut cx, &view.input, "{\n|}");
11525    }
11526
11527    #[gpui::test]
11528    fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
11529        let view = InputView::<EditorMode>::new(cx);
11530        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11531        setup_cursors(&mut cx, &view.input, "{|}");
11532        cx.update(|window, cx| {
11533            view.input.update(cx, |state, cx| {
11534                state.set_auto_close(false, window, cx);
11535                state.enter(
11536                    &Enter {
11537                        secondary: false,
11538                        shift: false,
11539                    },
11540                    window,
11541                    cx,
11542                );
11543            });
11544        });
11545        // Disabling automatic insertion does not disable structural indentation.
11546        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11547    }
11548
11549    #[gpui::test]
11550    fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
11551        use crate::input::{AutoClosingPair, set_language_config};
11552        let view = InputView::<EditorMode>::new(cx);
11553        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11554        cx.update(|window, cx| {
11555            set_language_config(
11556                "alpha",
11557                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
11558                cx,
11559            );
11560            set_language_config(
11561                "beta",
11562                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
11563                cx,
11564            );
11565            let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
11566            let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
11567            first.update(cx, |state, cx| {
11568                state.replace_text_in_range(None, "«", window, cx);
11569                assert_eq!(state.text().to_string(), "«»");
11570                state.set_value("", window, cx);
11571                state.set_smart_indent(false, window, cx);
11572                state.set_highlighter("beta", cx);
11573                assert!(!state.mode.is_smart_indent());
11574                state.replace_text_in_range(None, "‹", window, cx);
11575                assert_eq!(state.text().to_string(), "‹›");
11576                state.set_value("", window, cx);
11577                state.set_highlighter("unknown", cx);
11578                state.replace_text_in_range(None, "(", window, cx);
11579                assert_eq!(state.text().to_string(), "()");
11580            });
11581            second.update(cx, |state, cx| {
11582                state.replace_text_in_range(None, "‹", window, cx);
11583                assert_eq!(state.text().to_string(), "‹›");
11584            });
11585        });
11586    }
11587
11588    #[gpui::test]
11589    fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
11590        use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
11591        struct StringLanguages(Rc<Cell<usize>>);
11592        impl LanguageProvider for StringLanguages {
11593            fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
11594                self.0.set(self.0.get() + 1);
11595                Some(Rc::new(StringAllProvider))
11596            }
11597        }
11598        struct CodeLanguages;
11599        impl LanguageProvider for CodeLanguages {}
11600        let view = InputView::<EditorMode>::new(cx);
11601        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11602        cx.update(|window, cx| {
11603            let creations = Rc::new(Cell::new(0));
11604            set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
11605            view.input.update(cx, |state, cx| {
11606                state.replace_text_in_range(None, "(", window, cx);
11607                state.replace_text_in_range(None, "[", window, cx);
11608                assert_eq!(state.text().to_string(), "([");
11609                assert_eq!(
11610                    creations.get(),
11611                    1,
11612                    "retain the document provider between edits"
11613                );
11614            });
11615            set_language_provider(Rc::new(CodeLanguages), cx);
11616            view.input.update(cx, |state, cx| {
11617                state.replace_text_in_range(None, "{", window, cx);
11618                assert_eq!(state.text().to_string(), "([{}");
11619            });
11620        });
11621    }
11622
11623    #[gpui::test]
11624    fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
11625        use crate::input::{AutoClosingPair, set_language_config};
11626        let view = InputView::<EditorMode>::new(cx);
11627        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11628        setup_cursors(&mut cx, &view.input, "|");
11629        cx.update(|window, cx| {
11630            view.input.update(cx, |state, cx| {
11631                state.set_highlighter("CUSTOM", cx);
11632                state.set_auto_close(false, window, cx);
11633                state.set_smart_indent(false, window, cx);
11634            });
11635            set_language_config(
11636                "custom",
11637                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
11638                cx,
11639            );
11640            // Batched registrations must update every affected language.
11641            set_language_config("other", LanguageConfig::default(), cx);
11642            view.input.update(cx, |state, cx| {
11643                assert!(!state.mode.is_auto_close());
11644                assert!(!state.mode.is_smart_indent());
11645                state.set_auto_close(true, window, cx);
11646                state.replace_text_in_range(None, "«", window, cx);
11647            });
11648        });
11649        assert_cursors(&mut cx, &view.input, "«|»");
11650    }
11651
11652    #[gpui::test]
11653    fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
11654        let view = InputView::<EditorMode>::new(cx);
11655        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11656        setup_cursors(&mut cx, &view.input, "|word");
11657        cx.update(|window, cx| {
11658            view.input.update(cx, |state, cx| {
11659                state.replace_text_in_range(None, "(", window, cx)
11660            });
11661        });
11662        assert_cursors(&mut cx, &view.input, "(|word");
11663        setup_cursors(&mut cx, &view.input, "|word");
11664        cx.update(|window, cx| {
11665            view.input.update(cx, |state, cx| {
11666                crate::input::set_language_config(
11667                    state.language_name(),
11668                    LanguageConfig::default().auto_close_before("w"),
11669                    cx,
11670                );
11671                state.replace_text_in_range(None, "(", window, cx);
11672            });
11673        });
11674        assert_cursors(&mut cx, &view.input, "(|)word");
11675    }
11676
11677    #[gpui::test]
11678    fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
11679        use crate::input::{AutoClosingPair, SyntaxContext};
11680        let view = InputView::<EditorMode>::new(cx);
11681        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11682        setup_cursors(&mut cx, &view.input, "|");
11683        cx.update(|window, cx| {
11684            view.input.update(cx, |state, cx| {
11685                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11686                crate::input::set_language_config(
11687                    state.language_name(),
11688                    LanguageConfig::default().auto_closing_pairs([
11689                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
11690                        AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
11691                    ]),
11692                    cx,
11693                );
11694                state.replace_text_in_range(None, "(", window, cx);
11695                state.replace_text_in_range(None, "[", window, cx);
11696            });
11697        });
11698        assert_cursors(&mut cx, &view.input, "([|)");
11699    }
11700
11701    #[gpui::test]
11702    fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
11703        use crate::input::{AutoClosingPair, SyntaxContext};
11704        struct BlockComment;
11705        impl crate::input::SyntaxContextProvider for BlockComment {
11706            fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
11707                if text.to_string().contains("/*") {
11708                    SyntaxContext::Comment
11709                } else {
11710                    SyntaxContext::Code
11711                }
11712            }
11713        }
11714        let view = InputView::<EditorMode>::new(cx);
11715        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11716        setup_cursors(&mut cx, &view.input, "|");
11717        cx.update(|window, cx| {
11718            view.input.update(cx, |state, cx| {
11719                set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
11720                crate::input::set_language_config(
11721                    state.language_name(),
11722                    LanguageConfig::default()
11723                        .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
11724                            .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
11725                    cx,
11726                );
11727                state.replace_text_in_range(None, "/", window, cx);
11728                state.replace_text_in_range(None, "*", window, cx);
11729            });
11730        });
11731        assert_cursors(&mut cx, &view.input, "/*|*/");
11732        cx.update(|window, cx| {
11733            view.input
11734                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11735        });
11736        assert_cursors(&mut cx, &view.input, "|");
11737        cx.update(|window, cx| {
11738            view.input.update(cx, |state, cx| {
11739                state.undo(&Undo, window, cx);
11740                state.replace_text_in_range(None, "*", window, cx);
11741                state.replace_text_in_range(None, "/", window, cx);
11742            });
11743        });
11744        assert_cursors(&mut cx, &view.input, "/**/|");
11745    }
11746
11747    #[gpui::test]
11748    fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
11749        use crate::input::BracketPair;
11750        let view = InputView::<EditorMode>::new(cx);
11751        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11752        setup_cursors(&mut cx, &view.input, "|");
11753        cx.update(|window, cx| {
11754            view.input.update(cx, |state, cx| {
11755                let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
11756                rules.auto_closing_pairs = None;
11757                crate::input::set_language_config(state.language_name(), rules.clone(), cx);
11758                state.replace_text_in_range(None, "«", window, cx);
11759                crate::input::set_language_config(
11760                    state.language_name(),
11761                    rules.auto_closing_pairs([]),
11762                    cx,
11763                );
11764                state.replace_text_in_range(None, "«", window, cx);
11765            });
11766        });
11767        assert_cursors(&mut cx, &view.input, "««|»");
11768    }
11769
11770    #[gpui::test]
11771    fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
11772        use crate::input::{AutoClosingPair, SyntaxContext};
11773        let view = InputView::<EditorMode>::new(cx);
11774        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11775        setup_cursors(&mut cx, &view.input, "|");
11776        cx.update(|window, cx| {
11777            view.input.update(cx, |state, cx| {
11778                crate::input::set_language_config(
11779                    state.language_name(),
11780                    LanguageConfig::default()
11781                        .auto_closing_pairs([
11782                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11783                        ]),
11784                    cx,
11785                );
11786                state.replace_text_in_range(None, "/", window, cx);
11787                state.replace_text_in_range(None, "*", window, cx);
11788                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11789                state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
11790                state.undo(&Undo, window, cx);
11791                state.replace_text_in_range(None, "*", window, cx);
11792                state.replace_text_in_range(None, "/", window, cx);
11793            });
11794        });
11795        assert_cursors(&mut cx, &view.input, "/**/|");
11796    }
11797
11798    #[gpui::test]
11799    fn test_undo_does_not_promote_literal_comment_delimiters(cx: &mut TestAppContext) {
11800        use crate::input::{AutoClosingPair, SyntaxContext};
11801        let view = InputView::<EditorMode>::new(cx);
11802        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11803        setup_cursors(&mut cx, &view.input, "/*|*/");
11804        cx.update(|window, cx| {
11805            view.input.update(cx, |state, cx| {
11806                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11807                crate::input::set_language_config(
11808                    state.language_name(),
11809                    LanguageConfig::default()
11810                        .auto_closing_pairs([
11811                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11812                        ]),
11813                    cx,
11814                );
11815                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
11816                state.undo(&Undo, window, cx);
11817                state.backspace(&Backspace, window, cx);
11818            });
11819        });
11820        assert_cursors(&mut cx, &view.input, "/|*/");
11821    }
11822
11823    #[gpui::test]
11824    fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
11825        use crate::input::{AutoClosingPair, SyntaxContext};
11826        struct CommentScope;
11827        impl crate::input::SyntaxContextProvider for CommentScope {
11828            fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
11829                if text
11830                    .to_string()
11831                    .find("*/")
11832                    .is_some_and(|end| offset < end + 2)
11833                {
11834                    SyntaxContext::Comment
11835                } else {
11836                    SyntaxContext::Code
11837                }
11838            }
11839        }
11840        let view = InputView::<EditorMode>::new(cx);
11841        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11842        setup_cursors(&mut cx, &view.input, "|");
11843        cx.update(|window, cx| {
11844            view.input.update(cx, |state, cx| {
11845                set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
11846                crate::input::set_language_config(
11847                    state.language_name(),
11848                    LanguageConfig::default().auto_closing_pairs([
11849                        AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
11850                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
11851                    ]),
11852                    cx,
11853                );
11854                state.replace_text_in_range(None, "/", window, cx);
11855                state.replace_text_in_range(None, "*", window, cx);
11856                state.set_selected_range(4..4, cx);
11857                state.replace_text_in_range(None, "(", window, cx);
11858                state.set_selected_range(2..2, cx);
11859                state.replace_text_in_range(None, "*", window, cx);
11860                state.replace_text_in_range(None, "/", window, cx);
11861            });
11862        });
11863        assert_cursors(&mut cx, &view.input, "/**/|()");
11864        cx.update(|window, cx| {
11865            view.input.update(cx, |state, cx| {
11866                state.set_selected_range(2..2, cx);
11867                state.backspace(&Backspace, window, cx);
11868                state.undo(&Undo, window, cx);
11869                state.redo(&Redo, window, cx);
11870            });
11871        });
11872        assert_cursors(&mut cx, &view.input, "|()");
11873    }
11874
11875    #[gpui::test]
11876    fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
11877        use crate::input::{AutoClosingPair, SyntaxContext};
11878        let view = InputView::<EditorMode>::new(cx);
11879        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11880        setup_cursors(&mut cx, &view.input, "|");
11881        cx.update(|window, cx| {
11882            view.input.update(cx, |state, cx| {
11883                crate::input::set_language_config(
11884                    state.language_name(),
11885                    LanguageConfig::default()
11886                        .auto_closing_pairs([
11887                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11888                        ]),
11889                    cx,
11890                );
11891                state.replace_text_in_range(None, "/", window, cx);
11892                state.replace_text_in_range(None, "*", window, cx);
11893                state.replace_text_in_range(Some(0..2), "//", window, cx);
11894                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11895                state.replace_text_in_range(None, "*", window, cx);
11896            });
11897        });
11898        assert_cursors(&mut cx, &view.input, "//*|*/");
11899    }
11900
11901    #[gpui::test]
11902    fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
11903        use crate::input::IndentationRules;
11904        let view = InputView::<EditorMode>::new(cx);
11905        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11906        setup_cursors(&mut cx, &view.input, "BEGIN|");
11907        cx.update(|window, cx| {
11908            view.input.update(cx, |state, cx| {
11909                let rules = |insensitive| {
11910                    LanguageConfig::default().indentation_rules(IndentationRules::new(
11911                        regex::RegexBuilder::new("begin$")
11912                            .case_insensitive(insensitive)
11913                            .build()
11914                            .unwrap(),
11915                        regex::Regex::new("^end").unwrap(),
11916                    ))
11917                };
11918                crate::input::set_language_config(state.language_name(), rules(false), cx);
11919                crate::input::set_language_config(state.language_name(), rules(true), cx);
11920                state.enter(
11921                    &Enter {
11922                        secondary: false,
11923                        shift: false,
11924                    },
11925                    window,
11926                    cx,
11927                );
11928            });
11929        });
11930        assert_cursors(&mut cx, &view.input, "BEGIN\n  |");
11931    }
11932
11933    #[gpui::test]
11934    fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
11935        use crate::input::IndentationRules;
11936        let view = InputView::<EditorMode>::new(cx);
11937        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11938        let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
11939            regex::Regex::new(r"\bbegin\s*$").unwrap(),
11940            regex::Regex::new(r"^\s*end\b").unwrap(),
11941        ));
11942        for (before, expected) in [("begin|", "begin\n  |"), ("  |end", "  \n|end")] {
11943            setup_cursors(&mut cx, &view.input, before);
11944            cx.update(|window, cx| {
11945                view.input.update(cx, |state, cx| {
11946                    crate::input::set_language_config(state.language_name(), rules.clone(), cx);
11947                    state.enter(
11948                        &Enter {
11949                            secondary: false,
11950                            shift: false,
11951                        },
11952                        window,
11953                        cx,
11954                    );
11955                });
11956            });
11957            assert_cursors(&mut cx, &view.input, expected);
11958        }
11959    }
11960
11961    #[gpui::test]
11962    fn test_custom_language_config(cx: &mut TestAppContext) {
11963        let view = InputView::<EditorMode>::new(cx);
11964        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11965        cx.update(|_window, cx| {
11966            view.input.update(cx, |state, cx| {
11967                crate::input::set_language_config(
11968                    state.language_name(),
11969                    crate::input::language_config::LanguageConfig::default()
11970                        .brackets([crate::input::BracketPair::new("«", "»")])
11971                        .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
11972                    cx,
11973                );
11974            });
11975        });
11976        // Custom pair closes.
11977        setup_cursors(&mut cx, &view.input, "|");
11978        cx.update(|window, cx| {
11979            view.input.update(cx, |state, cx| {
11980                state.replace_text_in_range(None, "«", window, cx);
11981            });
11982        });
11983        assert_cursors(&mut cx, &view.input, "«|»");
11984        // Default `(` no longer pairs under custom rules.
11985        cx.update(|window, cx| {
11986            view.input.update(cx, |state, cx| {
11987                state.set_value("\n", window, cx);
11988                state.set_selected_range(0..0, cx);
11989                state.replace_text_in_range(None, "(", window, cx);
11990            });
11991        });
11992        assert_cursors(&mut cx, &view.input, "(|");
11993    }
11994
11995    #[gpui::test]
11996    fn test_skip_records_no_history(cx: &mut TestAppContext) {
11997        let view = InputView::<EditorMode>::new(cx);
11998        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11999        setup_cursors(&mut cx, &view.input, "(a|)");
12000        cx.update(|window, cx| {
12001            view.input.update(cx, |state, cx| {
12002                // Type a normal char (recorded), then skip over `)`.
12003                state.replace_text_in_range(None, "b", window, cx);
12004            });
12005        });
12006        assert_cursors(&mut cx, &view.input, "(ab|)");
12007        cx.update(|window, cx| {
12008            view.input.update(cx, |state, cx| {
12009                state.replace_text_in_range(None, ")", window, cx);
12010            });
12011        });
12012        // Skip is a pure cursor move: no history entry of its own.
12013        assert_cursors(&mut cx, &view.input, "(ab)|");
12014        // Undo removes `b`, never exposing a transient `())`.
12015        cx.update(|window, cx| {
12016            view.input
12017                .update(cx, |state, cx| state.undo(&Undo, window, cx));
12018        });
12019        assert_cursors(&mut cx, &view.input, "(a|)");
12020    }
12021
12022    #[gpui::test]
12023    fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
12024        let view = InputView::<EditorMode>::new(cx);
12025        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12026        setup_cursors(&mut cx, &view.input, "|");
12027        cx.update(|window, cx| {
12028            view.input.update(cx, |state, cx| {
12029                state.replace_text_in_range(None, "(", window, cx);
12030            });
12031        });
12032        assert_cursors(&mut cx, &view.input, "(|)");
12033        // One undo removes the whole pair (typing coalescing).
12034        cx.update(|window, cx| {
12035            view.input
12036                .update(cx, |state, cx| state.undo(&Undo, window, cx));
12037        });
12038        assert_cursors(&mut cx, &view.input, "|");
12039    }
12040
12041    #[gpui::test]
12042    fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
12043        let view = InputView::<EditorMode>::new(cx);
12044        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12045        // Odd backslashes: the typed quote is escaped, insert literally.
12046        setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
12047        cx.update(|window, cx| {
12048            view.input.update(cx, |state, cx| {
12049                state.replace_text_in_range(None, "\"", window, cx);
12050            });
12051        });
12052        assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
12053    }
12054
12055    #[gpui::test]
12056    fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
12057        let view = InputView::<EditorMode>::new(cx);
12058        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12059        // Even backslashes: quote is not escaped, skip over the terminator.
12060        setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
12061        cx.update(|window, cx| {
12062            view.input.update(cx, |state, cx| {
12063                state.replace_text_in_range(None, "\"", window, cx);
12064            });
12065        });
12066        assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
12067    }
12068
12069    #[gpui::test]
12070    fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
12071        use crate::input::{BracketPair, LanguageConfig};
12072
12073        let view = InputView::<EditorMode>::new(cx);
12074        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12075        cx.update(|window, cx| {
12076            view.input.update(cx, |state, cx| {
12077                // Language changes update rules without changing editor preferences.
12078                state.set_smart_indent(false, window, cx);
12079                crate::input::set_language_config(
12080                    state.language_name(),
12081                    LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
12082                    cx,
12083                );
12084            });
12085        });
12086        view.input.read_with(&cx, |state, _| {
12087            assert!(!state.mode.is_smart_indent(), "editor option preserved");
12088            assert!(state.mode.is_auto_close());
12089            let pairs = &state.mode.language_config().unwrap().brackets;
12090            assert_eq!(pairs.len(), 1, "pairs follow configuration");
12091            assert_eq!(pairs[0].open.as_ref(), "«");
12092        });
12093    }
12094
12095    struct CommentAllProvider;
12096    impl crate::input::SyntaxContextProvider for CommentAllProvider {
12097        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12098            crate::input::SyntaxContext::Comment
12099        }
12100    }
12101
12102    struct StringAllProvider;
12103    impl crate::input::SyntaxContextProvider for StringAllProvider {
12104        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12105            crate::input::SyntaxContext::String
12106        }
12107    }
12108
12109    #[gpui::test]
12110    fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
12111        use std::rc::Rc;
12112
12113        let view = InputView::<EditorMode>::new(cx);
12114        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12115        cx.update(|_window, cx| {
12116            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12117        });
12118        // Trigger `{` inside a string: no extra level, base indent only.
12119        setup_cursors(&mut cx, &view.input, "  x = {|");
12120        cx.update(|window, cx| {
12121            view.input.update(cx, |state, cx| {
12122                state.enter(
12123                    &Enter {
12124                        secondary: false,
12125                        shift: false,
12126                    },
12127                    window,
12128                    cx,
12129                );
12130            });
12131        });
12132        assert_cursors(&mut cx, &view.input, "  x = {\n  |");
12133    }
12134
12135    #[gpui::test]
12136    fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
12137        use std::rc::Rc;
12138
12139        let view = InputView::<EditorMode>::new(cx);
12140        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12141        cx.update(|_window, cx| {
12142            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12143        });
12144        // No three-way split inside strings: plain newline instead.
12145        setup_cursors(&mut cx, &view.input, "{|}");
12146        cx.update(|window, cx| {
12147            view.input.update(cx, |state, cx| {
12148                state.enter(
12149                    &Enter {
12150                        secondary: false,
12151                        shift: false,
12152                    },
12153                    window,
12154                    cx,
12155                );
12156            });
12157        });
12158        assert_cursors(&mut cx, &view.input, "{\n|}");
12159    }
12160
12161    #[gpui::test]
12162    fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
12163        use std::rc::Rc;
12164
12165        let view = InputView::<EditorMode>::new(cx);
12166        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12167        cx.update(|_window, cx| {
12168            set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
12169        });
12170        setup_cursors(&mut cx, &view.input, "|");
12171        cx.update(|window, cx| {
12172            view.input.update(cx, |state, cx| {
12173                state.replace_text_in_range(None, "(", window, cx);
12174            });
12175        });
12176        // In comments every character is literal.
12177        assert_cursors(&mut cx, &view.input, "(|");
12178    }
12179
12180    #[gpui::test]
12181    fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
12182        let view = InputView::<EditorMode>::new(cx);
12183        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12184        setup_cursors(&mut cx, &view.input, "{|}");
12185        cx.update(|window, cx| {
12186            view.input
12187                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12188        });
12189        assert_cursors(&mut cx, &view.input, "|");
12190    }
12191
12192    #[gpui::test]
12193    fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
12194        let view = InputView::<EditorMode>::new(cx);
12195        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12196        setup_cursors(&mut cx, &view.input, "{d|}");
12197        cx.update(|window, cx| {
12198            view.input
12199                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12200        });
12201        // Only `d` is deleted, the closing brace stays.
12202        assert_cursors(&mut cx, &view.input, "{|}");
12203    }
12204
12205    #[gpui::test]
12206    fn test_enter_splits_brackets(cx: &mut TestAppContext) {
12207        let view = InputView::<EditorMode>::new(cx);
12208        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12209        setup_cursors(&mut cx, &view.input, "{|}");
12210        cx.update(|window, cx| {
12211            view.input.update(cx, |state, cx| {
12212                state.enter(
12213                    &Enter {
12214                        secondary: false,
12215                        shift: false,
12216                    },
12217                    window,
12218                    cx,
12219                );
12220            });
12221        });
12222        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
12223        // Selection must be collapsed: typing next must insert, not replace.
12224        view.input.read_with(&cx, |state, _| {
12225            assert!(state.active_selection().is_empty());
12226        });
12227        cx.update(|window, cx| {
12228            view.input.update(cx, |state, cx| {
12229                state.replace_text_in_range(None, "x", window, cx);
12230            });
12231        });
12232        assert_cursors(&mut cx, &view.input, "{\n  x|\n}");
12233    }
12234
12235    #[gpui::test]
12236    fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
12237        let view = InputView::<EditorMode>::new(cx);
12238        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12239        setup_cursors(&mut cx, &view.input, "fn main() {|");
12240        cx.update(|window, cx| {
12241            view.input.update(cx, |state, cx| {
12242                state.enter(
12243                    &Enter {
12244                        secondary: false,
12245                        shift: false,
12246                    },
12247                    window,
12248                    cx,
12249                );
12250            });
12251        });
12252        assert_cursors(&mut cx, &view.input, "fn main() {\n  |");
12253    }
12254
12255    #[gpui::test]
12256    fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
12257        let view = multi_line(cx);
12258        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12259        setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12260        cx.update(|window, cx| {
12261            view.input
12262                .update(cx, |state, cx| state.indent(true, window, cx));
12263        });
12264        assert_cursors(&mut cx, &view.input, "  |ab\n  |cd\n  |ef");
12265        cx.update(|window, cx| {
12266            view.input
12267                .update(cx, |state, cx| state.outdent(true, window, cx));
12268        });
12269        assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12270    }
12271
12272    #[gpui::test]
12273    fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
12274        let view = multi_line(cx);
12275        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12276        setup_cursors(&mut cx, &view.input, "ab\n | cd");
12277        cx.update(|window, cx| {
12278            view.input
12279                .update(cx, |state, cx| state.outdent(true, window, cx));
12280        });
12281        assert_cursors(&mut cx, &view.input, "ab\n|cd");
12282    }
12283
12284    #[gpui::test]
12285    fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
12286        let view = InputView::build(cx, |state| state);
12287        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12288        cx.update(|window, cx| {
12289            view.input.update(cx, |state, cx| {
12290                state.set_value("abc", window, cx);
12291                state.set_selected_range(1..2, cx);
12292                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
12293                state.replace_text_in_range(None, "你", window, cx);
12294                state.undo(&Undo, window, cx);
12295                assert_eq!(state.value(), "abc");
12296                assert_eq!(state.selected_range(), 1..2);
12297                state.redo(&Redo, window, cx);
12298                assert_eq!(state.selected_range(), 4..4);
12299            });
12300        });
12301    }
12302
12303    #[gpui::test]
12304    fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
12305        let view = multi_line(cx);
12306        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12307        cx.update(|window, cx| {
12308            view.input.update(cx, |state, cx| {
12309                state.set_value("abc", window, cx);
12310                state.set_selected_range(1..1, cx);
12311                state.replace_text_in_range(None, "X", window, cx);
12312                state.set_selected_range(0..0, cx);
12313                state.replace_text_in_range(None, "", window, cx);
12314                state.undo(&Undo, window, cx);
12315                state.redo(&Redo, window, cx);
12316                assert_eq!(state.value(), "aXbc");
12317                assert_eq!(state.selected_range(), 2..2);
12318            });
12319        });
12320    }
12321
12322    #[gpui::test]
12323    fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
12324        let view = multi_line(cx);
12325        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12326        let input = view.input;
12327
12328        setup_cursors(&mut cx, &input, "|hello |world|");
12329        cx.update(|window, cx| {
12330            input.update(cx, |state, cx| {
12331                state.replace_text_in_range(None, ">>>", window, cx);
12332            });
12333        });
12334        assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
12335    }
12336
12337    #[gpui::test]
12338    fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
12339        let view = multi_line(cx);
12340        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12341        let input = view.input;
12342
12343        setup_cursors(&mut cx, &input, "|islands| cars|");
12344        cx.update(|window, cx| {
12345            input.update(cx, |state, cx| {
12346                state.backspace(&Backspace, window, cx);
12347            });
12348        });
12349        // The first cursor has nothing to delete. The others delete an `s`.
12350        assert_cursors(&mut cx, &input, "|island| car|");
12351    }
12352
12353    #[gpui::test]
12354    fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
12355        let view = multi_line(cx);
12356        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12357        let input = view.input;
12358
12359        setup_cursors(&mut cx, &input, "hello| |world");
12360        cx.update(|window, cx| {
12361            input.update(cx, |state, cx| {
12362                state.delete(&Delete, window, cx);
12363            });
12364        });
12365        // Adjacent deletions merge into a single cursor.
12366        assert_cursors(&mut cx, &input, "hello|orld");
12367    }
12368
12369    #[gpui::test]
12370    fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
12371        let view = multi_line(cx);
12372        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12373        let input = view.input;
12374
12375        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12376        cx.update(|window, cx| {
12377            input.update(cx, |state, cx| {
12378                state.replace_text_in_range(None, "a", window, cx);
12379            });
12380        });
12381        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12382
12383        // The whole multi-edit insert is a single undo transaction.
12384        input.read_with(&cx, |state, _| {
12385            assert_eq!(state.undo_manager.undo_count(), 1);
12386        });
12387
12388        cx.update(|window, cx| {
12389            input.update(cx, |state, cx| {
12390                state.backspace(&Backspace, window, cx);
12391            });
12392        });
12393        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12394    }
12395
12396    #[gpui::test]
12397    fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
12398        let view = multi_line(cx);
12399        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12400        let input = view.input;
12401
12402        setup_cursors(&mut cx, &input, "ab|cd\nabcd");
12403        cx.update(|window, cx| {
12404            input.update(cx, |state, cx| {
12405                state.add_cursor_below(&AddCursorBelow, window, cx);
12406            });
12407        });
12408        assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
12409    }
12410
12411    #[gpui::test]
12412    fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
12413        let view = multi_line(cx);
12414        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12415        let input = view.input;
12416
12417        setup_cursors(&mut cx, &input, "he|llo");
12418        cx.update(|_, cx| {
12419            input.update(cx, |state, cx| {
12420                // Duplicate of the existing cursor is rejected.
12421                state.add_cursor_at(2, cx);
12422                assert_eq!(state.selections.len(), 1);
12423                // A distinct offset adds a cursor.
12424                state.add_cursor_at(4, cx);
12425                assert_eq!(state.selections.len(), 2);
12426            });
12427        });
12428    }
12429
12430    #[gpui::test]
12431    fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
12432        let view = multi_line(cx);
12433        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12434        let input = view.input;
12435
12436        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12437        cx.update(|window, cx| {
12438            input.update(cx, |state, cx| {
12439                state.replace_text_in_range(None, "a", window, cx);
12440            });
12441        });
12442        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12443
12444        cx.update(|window, cx| {
12445            input.update(cx, |state, cx| {
12446                state.undo(&Undo, window, cx);
12447            });
12448        });
12449        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12450
12451        cx.update(|window, cx| {
12452            input.update(cx, |state, cx| {
12453                state.redo(&Redo, window, cx);
12454            });
12455        });
12456        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12457    }
12458
12459    #[gpui::test]
12460    fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
12461        let view = multi_line(cx);
12462        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12463        let input = view.input;
12464
12465        setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12466        cx.update(|window, cx| {
12467            input.update(cx, |state, cx| {
12468                state.replace_text_in_range(None, "a", window, cx);
12469            });
12470        });
12471        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12472
12473        cx.update(|window, cx| {
12474            input.update(cx, |state, cx| {
12475                state.undo(&Undo, window, cx);
12476            });
12477        });
12478        assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12479
12480        cx.update(|window, cx| {
12481            input.update(cx, |state, cx| {
12482                state.redo(&Redo, window, cx);
12483            });
12484        });
12485        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12486    }
12487
12488    #[gpui::test]
12489    fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
12490        let view = multi_line(cx);
12491        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12492        let input = view.input;
12493
12494        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12495        for ch in ['a', 'b', 'c'] {
12496            cx.update(|window, cx| {
12497                input.update(cx, |state, cx| {
12498                    state.replace_text_in_range(None, &ch.to_string(), window, cx);
12499                });
12500            });
12501        }
12502        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12503
12504        // The repeated keystrokes form one typing gesture.
12505        cx.update(|window, cx| {
12506            input.update(cx, |state, cx| {
12507                assert_eq!(state.undo_manager.undo_count(), 1);
12508                state.undo(&Undo, window, cx);
12509            });
12510        });
12511        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12512
12513        cx.update(|window, cx| {
12514            input.update(cx, |state, cx| {
12515                state.redo(&Redo, window, cx);
12516            });
12517        });
12518        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12519    }
12520
12521    #[gpui::test]
12522    fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
12523        let view = multi_line(cx);
12524        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12525        let input = view.input;
12526
12527        setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12528        for _ in 0..3 {
12529            cx.update(|window, cx| {
12530                input.update(cx, |state, cx| {
12531                    state.backspace(&Backspace, window, cx);
12532                });
12533            });
12534        }
12535        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12536
12537        cx.update(|window, cx| {
12538            input.update(cx, |state, cx| {
12539                assert_eq!(state.undo_manager.undo_count(), 1);
12540                state.undo(&Undo, window, cx);
12541            });
12542        });
12543        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12544    }
12545
12546    #[gpui::test]
12547    fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
12548        let view = multi_line(cx);
12549        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12550        let input = view.input;
12551
12552        setup_cursors(&mut cx, &input, "|1\n2\n3");
12553        cx.update(|window, cx| {
12554            input.update(cx, |state, cx| {
12555                state.replace_text_in_range(None, "a", window, cx);
12556                state.add_cursor_below(&AddCursorBelow, window, cx);
12557                state.replace_text_in_range(None, "b", window, cx);
12558            });
12559        });
12560        assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
12561
12562        // The keystroke after the cursor was added is its own undo entry.
12563        cx.update(|window, cx| {
12564            input.update(cx, |state, cx| {
12565                state.undo(&Undo, window, cx);
12566            });
12567        });
12568        assert_cursors(&mut cx, &input, "a|1\n2|\n3");
12569    }
12570
12571    #[gpui::test]
12572    fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
12573        let view = multi_line(cx);
12574        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12575        let input = view.input;
12576
12577        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12578        cx.update(|window, cx| {
12579            input.update(cx, |state, cx| {
12580                state.indent(false, window, cx);
12581                assert_eq!(state.undo_manager.undo_count(), 1);
12582                state.undo(&Undo, window, cx);
12583            });
12584        });
12585        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12586    }
12587
12588    #[gpui::test]
12589    fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
12590        let view = multi_line(cx);
12591        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12592        let input = view.input;
12593
12594        // Cursors at line starts.
12595        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12596        cx.update(|window, cx| {
12597            input.update(cx, |state, cx| {
12598                state.indent(false, window, cx);
12599            });
12600        });
12601        assert_cursors(&mut cx, &input, "  |1\n  |2\n  |3");
12602
12603        cx.update(|window, cx| {
12604            input.update(cx, |state, cx| {
12605                state.outdent(false, window, cx);
12606            });
12607        });
12608        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12609    }
12610
12611    #[gpui::test]
12612    fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
12613        let view = multi_line(cx);
12614        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12615        let input = view.input;
12616
12617        // A mid-line indent lands at the cursor, and the outdent does not
12618        // take it back: it only ever removes leading line indentation.
12619        setup_cursors(&mut cx, &input, "1|2\n1|2");
12620        cx.update(|window, cx| {
12621            input.update(cx, |state, cx| {
12622                state.indent(false, window, cx);
12623            });
12624        });
12625        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
12626
12627        cx.update(|window, cx| {
12628            input.update(cx, |state, cx| {
12629                state.outdent(false, window, cx);
12630            });
12631        });
12632        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
12633
12634        // A line with leading indentation loses that, wherever the cursor is.
12635        setup_cursors(&mut cx, &input, "  1|2\n  1|2");
12636        cx.update(|window, cx| {
12637            input.update(cx, |state, cx| {
12638                state.outdent(false, window, cx);
12639            });
12640        });
12641        assert_cursors(&mut cx, &input, "1|2\n1|2");
12642    }
12643
12644    #[gpui::test]
12645    fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
12646        let view = multi_line(cx);
12647        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12648        let input = view.input;
12649
12650        setup_cursors(&mut cx, &input, "a|b\nc|d");
12651        cx.update(|window, cx| {
12652            input.update(cx, |state, cx| {
12653                let before: Vec<_> = state.selections.iter().copied().collect();
12654                state.set_readonly(true, cx);
12655                state.backspace(&Backspace, window, cx);
12656                state.indent(false, window, cx);
12657
12658                assert_eq!(state.value(), "ab\ncd\n");
12659                assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
12660            });
12661        });
12662    }
12663
12664    #[gpui::test]
12665    fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
12666        let view = multi_line(cx);
12667        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12668        let input = view.input;
12669
12670        setup_cursors(&mut cx, &input, "x|\n|y");
12671        cx.update(|window, cx| {
12672            input.update(cx, |state, cx| {
12673                let mut selections: Vec<_> = state.selections.iter().copied().collect();
12674                selections.swap(0, 1);
12675                state.selections.replace_all(selections);
12676                let active_id = state.active_selection().id;
12677                state.replace_text_in_range(None, "!", window, cx);
12678                assert_eq!(state.active_selection().id, active_id);
12679            });
12680        });
12681    }
12682
12683    #[gpui::test]
12684    fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
12685        let view = multi_line(cx);
12686        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12687        let input = view.input;
12688
12689        cx.update(|window, cx| {
12690            input.update(cx, |state, cx| {
12691                state.set_value("line1\nline2\nline3", window, cx);
12692                let id = state.selections.generate_id();
12693                state
12694                    .selections
12695                    .replace_all(vec![CursorSelection::new(id, 0, 17)]);
12696                cx.notify();
12697            });
12698        });
12699
12700        cx.update(|window, cx| {
12701            input.update(cx, |state, cx| {
12702                state.indent(true, window, cx);
12703            });
12704        });
12705        input.read_with(&cx, |state, _| {
12706            assert_eq!(state.text.to_string(), "  line1\n  line2\n  line3");
12707        });
12708
12709        cx.update(|window, cx| {
12710            input.update(cx, |state, cx| {
12711                state.outdent(true, window, cx);
12712            });
12713        });
12714        input.read_with(&cx, |state, _| {
12715            assert_eq!(state.text.to_string(), "line1\nline2\nline3");
12716        });
12717    }
12718
12719    #[gpui::test]
12720    fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
12721        let view = multi_line(cx);
12722        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12723        let input = view.input;
12724
12725        setup_cursors(
12726            &mut cx,
12727            &input,
12728            "on|e two three\none t|wo three\non|e two three",
12729        );
12730
12731        cx.update(|window, cx| {
12732            input.update(cx, |state, cx| {
12733                state.move_to_next_word(&MoveToNextWord, window, cx);
12734            });
12735        });
12736        assert_cursors(
12737            &mut cx,
12738            &input,
12739            "one| two three\none two| three\none| two three",
12740        );
12741
12742        cx.update(|window, cx| {
12743            input.update(cx, |state, cx| {
12744                state.move_to_previous_word(&MoveToPreviousWord, window, cx);
12745            });
12746        });
12747        assert_cursors(
12748            &mut cx,
12749            &input,
12750            "|one two three\none |two three\n|one two three",
12751        );
12752
12753        // Move to end/start of document collapses to a single cursor.
12754        cx.update(|window, cx| {
12755            input.update(cx, |state, cx| {
12756                state.move_to_end(&MoveToEnd, window, cx);
12757            });
12758        });
12759        input.read_with(&cx, |state, _| {
12760            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12761            assert_eq!(cursors, vec![state.text.len()]);
12762        });
12763
12764        cx.update(|window, cx| {
12765            input.update(cx, |state, cx| {
12766                state.move_to_start(&MoveToStart, window, cx);
12767            });
12768        });
12769        input.read_with(&cx, |state, _| {
12770            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12771            assert_eq!(cursors, vec![0]);
12772        });
12773    }
12774
12775    #[gpui::test]
12776    fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
12777        let view = multi_line(cx);
12778        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12779        let input = view.input;
12780
12781        setup_cursors(
12782            &mut cx,
12783            &input,
12784            "on|e two three\none t|wo three\non|e two three",
12785        );
12786        cx.update(|window, cx| {
12787            input.update(cx, |state, cx| {
12788                state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
12789            });
12790        });
12791        assert_cursors(
12792            &mut cx,
12793            &input,
12794            "|one two three\n|one two three\n|one two three",
12795        );
12796
12797        // Select to document start collapses to the active cursor only.
12798        setup_cursors(
12799            &mut cx,
12800            &input,
12801            "on|e two three\none t|wo three\non|e two three",
12802        );
12803        cx.update(|window, cx| {
12804            input.update(cx, |state, cx| {
12805                state.select_to_start(&SelectToStart, window, cx);
12806            });
12807        });
12808        input.read_with(&cx, |state, _| {
12809            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12810            assert_eq!(cursors, vec![0]);
12811        });
12812    }
12813
12814    #[gpui::test]
12815    fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
12816        let view = multi_line(cx);
12817        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12818        let input = view.input;
12819
12820        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
12821        cx.update(|window, cx| {
12822            input.update(cx, |state, cx| {
12823                state.select_right(&SelectRight, window, cx);
12824            });
12825        });
12826        input.read_with(&cx, |state, _| {
12827            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12828            assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
12829        });
12830
12831        cx.update(|window, cx| {
12832            input.update(cx, |state, cx| {
12833                state.replace_text_in_range(None, "x", window, cx);
12834            });
12835        });
12836        assert_cursors(&mut cx, &input, "x|\nx|\nx|");
12837    }
12838
12839    #[gpui::test]
12840    fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
12841        let view = multi_line(cx);
12842        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12843        let input = view.input;
12844
12845        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
12846        cx.update(|window, cx| {
12847            input.update(cx, |state, cx| {
12848                state.escape(&Escape, window, cx);
12849            });
12850        });
12851        input.read_with(&cx, |state, _| {
12852            assert_eq!(state.selections.len(), 1);
12853        });
12854    }
12855
12856    #[gpui::test]
12857    fn test_build_columnar_selection(cx: &mut TestAppContext) {
12858        let view = multi_line(cx);
12859        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12860        let input = view.input;
12861
12862        setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
12863        cx.update(|_, cx| {
12864            input.update(cx, |state, cx| {
12865                // From row 0 col 1 to row 2 col 3.
12866                state.build_columnar_selection(
12867                    ColumnarPoint::new(1, 0),
12868                    ColumnarPoint::new(13, 0),
12869                    cx,
12870                );
12871                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12872                assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
12873            });
12874        });
12875    }
12876
12877    #[gpui::test]
12878    fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
12879        let view = multi_line(cx);
12880        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12881        let input = view.input;
12882
12883        setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
12884        cx.update(|_, cx| {
12885            input.update(cx, |state, cx| {
12886                // Ends on the short row, 3 columns past its end: the block still spans
12887                // columns 1..5, and only that row is clipped to what it has.
12888                state.build_columnar_selection(
12889                    ColumnarPoint::new(1, 0),
12890                    ColumnarPoint::new(9, 3),
12891                    cx,
12892                );
12893                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12894                assert_eq!(ranges, vec![(1, 5), (8, 9)]);
12895            });
12896        });
12897    }
12898
12899    #[gpui::test]
12900    fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
12901        let view = multi_line(cx);
12902        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12903        let input = view.input;
12904
12905        for (clipboard, expected) in [
12906            ("x\ny\nz", "x|1\ny|2\nz|3"),
12907            ("x\r\ny\r\nz", "x|1\ny|2\nz|3"),
12908            ("x\ny\nz\r", "x|1\ny|2\nz\r|3"),
12909            ("x\ny\n", "x|1\ny|2\n|3"),
12910            ("x\r\ny\r\n", "x|1\ny|2\n|3"),
12911        ] {
12912            setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12913            cx.update(|window, cx| {
12914                cx.write_to_clipboard(ClipboardItem::new_string(clipboard.to_string()));
12915                input.update(cx, |state, cx| state.paste(&Paste, window, cx));
12916            });
12917            // Line separators are not inserted into the destination lines.
12918            assert_cursors(&mut cx, &input, expected);
12919            cx.update(|window, cx| {
12920                input.update(cx, |state, cx| state.undo(&Undo, window, cx));
12921            });
12922            assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12923            cx.update(|window, cx| {
12924                input.update(cx, |state, cx| state.redo(&Redo, window, cx));
12925            });
12926            assert_cursors(&mut cx, &input, expected);
12927        }
12928    }
12929
12930    #[gpui::test]
12931    fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
12932        use gpui::{ClipboardEntry, Image, ImageFormat};
12933
12934        let input_view = InputView::build(cx, |state| state);
12935        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
12936        let input = input_view.input;
12937
12938        cx.update(|window, cx| {
12939            input.update(cx, |state, cx| {
12940                state.set_value("hello world", window, cx);
12941                state.select_all(window, cx);
12942                cx.write_to_clipboard(ClipboardItem {
12943                    entries: vec![ClipboardEntry::Image(Image::from_bytes(
12944                        ImageFormat::Png,
12945                        vec![0x89, b'P', b'N', b'G'],
12946                    ))],
12947                });
12948
12949                // An image-only clipboard must not replace the selection
12950                // with nothing.
12951                state.paste(&Paste, window, cx);
12952                assert_eq!(state.value(), "hello world");
12953                assert_eq!(state.selected_range(), 0..11);
12954            });
12955        });
12956    }
12957
12958    #[gpui::test]
12959    fn test_paste_target_tracks_edits_and_selections(cx: &mut TestAppContext) {
12960        let view = multi_line(cx);
12961        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12962        let input = view.input;
12963
12964        setup_cursors(&mut cx, &input, "ab|c");
12965        let target = input.read_with(&cx, |state, _| state.paste_target());
12966        // Nothing happened: a paste asked for then still applies.
12967        assert_eq!(
12968            input.read_with(&cx, |state, _| state.paste_target()),
12969            target
12970        );
12971
12972        // Moving the caret changes where the paste would go.
12973        cx.update(|_, cx| {
12974            input.update(cx, |state, cx| {
12975                let id = state.selections.generate_id();
12976                state
12977                    .selections
12978                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
12979                cx.notify();
12980            });
12981        });
12982        let moved = input.read_with(&cx, |state, _| state.paste_target());
12983        assert_ne!(moved, target);
12984
12985        // Editing the text changes it too, even with the caret put back.
12986        cx.update(|window, cx| {
12987            input.update(cx, |state, cx| {
12988                state.replace_text_in_range_silent(None, "x", window, cx);
12989                let id = state.selections.generate_id();
12990                state
12991                    .selections
12992                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
12993            });
12994        });
12995        assert_ne!(input.read_with(&cx, |state, _| state.paste_target()), moved);
12996    }
12997
12998    #[gpui::test]
12999    fn native_input_point_lookup_follows_multiline_layout_and_scroll(cx: &mut TestAppContext) {
13000        let value = format!(
13001            "Heading🙂\n{}\nLast line",
13002            "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau upsilon phi chi psi omega ".repeat(20)
13003        );
13004        let second_line = value.find("beta").unwrap();
13005        let wrapped_line = value.find("iota").unwrap();
13006        let scrolled_line = value.rfind("iota").unwrap();
13007        let view = InputView::build_textarea(cx, move |state| state.rows(6).default_value(value));
13008        cx.simulate_window_resize(view.window_handle.into(), size(px(240.), px(120.)));
13009        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13010        cx.update(|window, cx| window.draw(cx).clear(cx));
13011
13012        let lookup = |offset: usize, cx: &mut VisualTestContext| {
13013            cx.update(|window, cx| {
13014                view.input.update(cx, |state, cx| {
13015                    let text = state.value();
13016                    let utf16 = text[..offset].encode_utf16().count();
13017                    let bounds = state
13018                        .bounds_for_range(
13019                            utf16..utf16 + 1,
13020                            state.text_bounds().unwrap(),
13021                            window,
13022                            cx,
13023                        )
13024                        .unwrap();
13025                    let point = bounds.center();
13026                    assert!(
13027                        state.input_bounds().contains(&point),
13028                        "probe must be visible"
13029                    );
13030                    assert_eq!(
13031                        state.character_index_for_point(point, window, cx),
13032                        Some(utf16)
13033                    );
13034                    bounds.top()
13035                })
13036            })
13037        };
13038        let second_top = lookup(second_line, &mut cx);
13039        let wrapped_top = lookup(wrapped_line, &mut cx);
13040        assert!(wrapped_top > second_top, "the second probe must be wrapped");
13041
13042        cx.update(|window, cx| {
13043            view.input.update(cx, |state, cx| {
13044                let text = state.value();
13045                let utf16 = text[..scrolled_line].encode_utf16().count();
13046                state.set_selected_text_range(utf16..utf16, window, cx);
13047            });
13048            window.draw(cx).clear(cx);
13049        });
13050        view.input.read_with(&cx, |state, _| {
13051            assert!(state.scroll_offset().y < -state.input_bounds().size.height);
13052        });
13053        lookup(scrolled_line, &mut cx);
13054    }
13055
13056    #[gpui::test]
13057    fn test_ime_candidate_bounds_fallback_before_repaint(cx: &mut TestAppContext) {
13058        let input_view = InputView::build_textarea(cx, |state| {
13059            state.default_value("这是一段已经输入的中文文字")
13060        });
13061        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13062        visual.update(|window, cx| window.draw(cx).clear(cx));
13063
13064        visual.update(|window, cx| {
13065            input_view.input.update(cx, |state, cx| {
13066                state.focus(window, cx);
13067                let len = state.text.len();
13068                state.set_cursor_to(len);
13069            });
13070        });
13071        visual.update(|window, cx| window.draw(cx).clear(cx));
13072
13073        visual.update(|window, cx| {
13074            input_view.input.update(cx, |state, cx| {
13075                let bounds = state.text_bounds().unwrap_or_default();
13076                let before = state.selected_text_range(false, window, cx).unwrap().range;
13077                let previous = state
13078                    .bounds_for_range(before.end..before.end, bounds, window, cx)
13079                    .unwrap();
13080
13081                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
13082
13083                let after = state.selected_text_range(false, window, cx).unwrap().range;
13084                let pending = state
13085                    .bounds_for_range(after.end..after.end, bounds, window, cx)
13086                    .unwrap();
13087
13088                assert!(
13089                    (pending.origin.x - previous.origin.x).abs() < px(40.0),
13090                    "pending origin.x {:?} must remain close to previous origin.x {:?}",
13091                    pending.origin.x,
13092                    previous.origin.x
13093                );
13094
13095                let range_bounds = state
13096                    .bounds_for_range(before.end..after.end, bounds, window, cx)
13097                    .unwrap();
13098                assert!(
13099                    (range_bounds.origin.x - previous.origin.x).abs() < px(40.0),
13100                    "range_bounds origin.x {:?} must remain close to previous origin.x {:?}",
13101                    range_bounds.origin.x,
13102                    previous.origin.x
13103                );
13104                assert!(range_bounds.size.width >= px(0.0));
13105            });
13106        });
13107    }
13108
13109    #[gpui::test]
13110    fn test_ime_candidate_bounds_multiline_line_end(cx: &mut TestAppContext) {
13111        let input_view =
13112            InputView::build_textarea(cx, |state| state.default_value("First line\nSecond line"));
13113        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13114        visual.update(|window, cx| window.draw(cx).clear(cx));
13115
13116        visual.update(|window, cx| {
13117            input_view.input.update(cx, |state, cx| {
13118                state.focus(window, cx);
13119                // Position at end of first line ("First line".len() == 10)
13120                state.set_cursor_to(10);
13121            });
13122        });
13123        visual.update(|window, cx| window.draw(cx).clear(cx));
13124
13125        visual.update(|window, cx| {
13126            input_view.input.update(cx, |state, cx| {
13127                let bounds = state.text_bounds().unwrap_or_default();
13128                let candidate_bounds = state.bounds_for_range(10..10, bounds, window, cx).unwrap();
13129
13130                // Candidate bounds for end of line 0 must be positioned at the end of line 0,
13131                // and must not jump to the start of the next line (column 0).
13132                let line_number_width = state
13133                    .last_layout
13134                    .as_ref()
13135                    .map(|l| l.line_number_width)
13136                    .unwrap_or_default();
13137                assert!(
13138                    candidate_bounds.origin.x > bounds.origin.x + line_number_width,
13139                    "candidate bounds at line end must be past the line start, got {:?}",
13140                    candidate_bounds.origin.x
13141                );
13142
13143                let (line_idx, sub_line, pos) = state.line_and_position_for_offset(10);
13144                assert_eq!(line_idx, 0);
13145                assert_eq!(sub_line, 0);
13146                assert!(pos.is_some());
13147                assert!(pos.unwrap().x > line_number_width);
13148            });
13149        });
13150    }
13151}
13152
13153/// Methods that only a single-line input offers.
13154impl InputBaseState<crate::input::InputMode> {
13155    /// Create a single-line text input state.
13156    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13157        Self::new_in_mode(window, cx)
13158    }
13159
13160    /// Set with password masked state.
13161    pub fn masked(mut self, masked: bool) -> Self {
13162        self.masked = masked;
13163        self
13164    }
13165
13166    /// Set the password masked state of the input field.
13167    pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
13168        self.masked = masked;
13169        cx.notify();
13170    }
13171
13172    /// Set the regular expression pattern of the input field.
13173    pub fn pattern(mut self, pattern: regex::Regex) -> Self {
13174        self.pattern = Some(pattern);
13175        self
13176    }
13177
13178    /// Set the regular expression pattern of the input field with reference.
13179    pub fn set_pattern(
13180        &mut self,
13181        pattern: regex::Regex,
13182        _window: &mut Window,
13183        _cx: &mut Context<Self>,
13184    ) {
13185        self.pattern = Some(pattern);
13186    }
13187
13188    /// Set the validation function of the input field.
13189    pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
13190        self.validate = Some(Box::new(f));
13191        self
13192    }
13193
13194    pub fn set_validator(
13195        &mut self,
13196        validate: impl Fn(&str, &mut App) -> bool + 'static,
13197        _cx: &mut Context<Self>,
13198    ) {
13199        self.validate = Some(Box::new(validate));
13200    }
13201
13202    /// Set the minimum numeric value, clamped on blur when the input uses a
13203    /// numeric mask and the clamped value passes its validation rules.
13204    pub fn min(mut self, min: f64) -> Self {
13205        self.number_min = Some(min);
13206        self
13207    }
13208
13209    /// Set the maximum numeric value, clamped on blur when the input uses a
13210    /// numeric mask and the clamped value passes its validation rules.
13211    pub fn max(mut self, max: f64) -> Self {
13212        self.number_max = Some(max);
13213        self
13214    }
13215
13216    /// Update the minimum value after construction. See [`Self::min`].
13217    pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13218        self.number_min = min;
13219    }
13220
13221    /// Update the maximum value after construction. See [`Self::max`].
13222    pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13223        self.number_max = max;
13224    }
13225
13226    /// Set true to show spinner at the input right.
13227    pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
13228        self.loading = loading;
13229        cx.notify();
13230    }
13231}
13232
13233/// Methods shared by the two multi-line modes, and reachable on neither a
13234/// single-line input nor anything else.
13235impl<M: crate::input::MultiLineMode> InputBaseState<M> {
13236    /// Set whether text taller than the input stretches past its top and
13237    /// bottom and springs back when precise trackpad or Magic Mouse scrolling
13238    /// or its momentum runs into an end. Ordinary line-wheel scrolling does
13239    /// not bounce. The default follows
13240    /// [`crate::ScrollBounce::enabled_by_default`]: on on iOS, Android and
13241    /// macOS, off elsewhere. Under reduced motion the text stops at its ends
13242    /// without stretching.
13243    pub fn scroll_bounce(mut self, scroll_bounce: bool) -> Self {
13244        self.scroll_bounce = scroll_bounce;
13245        self
13246    }
13247
13248    /// Update whether the text stretches past its ends, see
13249    /// [`InputBaseState::scroll_bounce`]. Turning it off drops a stretch in
13250    /// progress.
13251    pub fn set_scroll_bounce(&mut self, scroll_bounce: bool, cx: &mut Context<Self>) {
13252        if self.scroll_bounce != scroll_bounce {
13253            self.scroll_bounce = scroll_bounce;
13254            self.overscroll.reset();
13255            cx.notify();
13256        }
13257    }
13258
13259    /// Whether the built-in search panel and its shortcut are enabled. Off by
13260    /// default, on for the code editor.
13261    ///
13262    /// This only concerns the panel. An input that is not searchable still
13263    /// answers [`InputBaseState::set_search_query`] and the other search
13264    /// methods, and lets `Ctrl-F` / `Cmd-F` bubble up to its ancestors, so an
13265    /// application can put its own search UI on top of the same engine.
13266    pub fn searchable(mut self, searchable: bool) -> Self {
13267        self.searchable = searchable;
13268        self
13269    }
13270
13271    /// See [`InputBaseState::searchable`].
13272    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
13273        self.searchable = searchable;
13274        cx.notify();
13275    }
13276
13277    /// Set the soft wrap mode, default is true.
13278    #[doc(hidden)]
13279    pub fn soft_wrap(mut self, wrap: bool) -> Self {
13280        self.soft_wrap = wrap;
13281        self
13282    }
13283
13284    /// Update the soft wrap mode, default is true.
13285    pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
13286        self.soft_wrap = wrap;
13287        if wrap {
13288            let wrap_width = self
13289                .last_layout
13290                .as_ref()
13291                .and_then(|b| b.wrap_width)
13292                .unwrap_or(self.input_bounds.size.width);
13293
13294            self.display_map.on_layout_changed(Some(wrap_width), cx);
13295
13296            // Reset scroll to left 0
13297            let mut offset = self.scroll_handle.offset();
13298            offset.x = px(0.);
13299            self.scroll_handle.set_offset(offset);
13300        } else {
13301            self.display_map.on_layout_changed(None, cx);
13302        }
13303        cx.notify();
13304    }
13305
13306    /// Set how soft-wrapped continuation lines are indented, default is [`WrappingIndent::Same`]
13307    #[doc(hidden)]
13308    pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
13309        self.wrapping_indent = wrapping_indent;
13310        self
13311    }
13312
13313    /// Update how soft-wrapped continuation lines are indented.
13314    pub fn set_wrapping_indent(
13315        &mut self,
13316        wrapping_indent: WrappingIndent,
13317        _: &mut Window,
13318        cx: &mut Context<Self>,
13319    ) {
13320        self.wrapping_indent = wrapping_indent;
13321        self.display_map.set_wrapping_indent(wrapping_indent, cx);
13322        cx.notify();
13323    }
13324}
13325
13326/// Methods that only ordinary multi-line text offers.
13327impl InputBaseState<crate::input::TextareaMode> {
13328    /// Create a multi-line text state.
13329    ///
13330    /// Being multi-line is carried by the mode, not by the layout, so the
13331    /// default plain-text layout needs no adjustment here.
13332    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13333        Self::new_in_mode(window, cx)
13334    }
13335
13336    pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
13337        self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
13338        self.mode.update_auto_grow(&self.display_map);
13339        cx.notify();
13340    }
13341
13342    /// Set the number of rows for the multi-line Textarea.
13343    ///
13344    /// This is only used when `multi_line` is set to true. The input is at least
13345    /// this many lines tall.
13346    ///
13347    /// default: 1
13348    #[doc(hidden)]
13349    pub fn rows(mut self, rows: usize) -> Self {
13350        match &mut self.mode {
13351            LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
13352                *r = rows
13353            }
13354            LayoutMode::AutoGrow {
13355                max_rows: max_r,
13356                rows: r,
13357                ..
13358            } => {
13359                *r = rows;
13360                *max_r = rows;
13361            }
13362        }
13363        self
13364    }
13365
13366    pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
13367        match &mut self.mode {
13368            LayoutMode::PlainText { rows: value, .. }
13369            | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
13370            LayoutMode::AutoGrow {
13371                rows: value,
13372                max_rows,
13373                ..
13374            } => {
13375                *value = rows;
13376                *max_rows = rows;
13377            }
13378        }
13379        cx.notify();
13380    }
13381
13382    /// Grow with the content from `min_rows` through `max_rows`.
13383    pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
13384        self.mode = LayoutMode::auto_grow(min_rows, max_rows);
13385        self
13386    }
13387}
13388
13389/// Methods that only a source-code editor offers.
13390impl InputBaseState<crate::input::EditorMode> {
13391    /// Create a source-code editor state.
13392    ///
13393    /// Default options: line numbers on, tab size 2 with soft tabs, indent
13394    /// guides on, multi-line, and search enabled. Set the language for syntax
13395    /// highlighting with [`Self::language`]; without one the text is shown
13396    /// unhighlighted.
13397    ///
13398    /// The editor aims at simple code editing or display, not at being a
13399    /// full-featured code editor. It offers syntax highlighting, auto indent,
13400    /// line numbers, and handles large text up to about 50K lines.
13401    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13402        let mut state = Self::new_in_mode(window, cx);
13403        state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
13404        state.searchable = true;
13405        state
13406    }
13407
13408    /// Set the language to highlight, e.g. `"rust"`.
13409    ///
13410    /// See [`Self::set_highlighter`] to change it after construction.
13411    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
13412        if let LayoutMode::CodeEditor {
13413            language: l,
13414            highlighter,
13415            ..
13416        } = &mut self.mode
13417        {
13418            l.set_name(language.into());
13419            *highlighter.borrow_mut() = None;
13420        }
13421        self
13422    }
13423
13424    /// The current language name, e.g. `"rust"`.
13425    pub fn language_name(&self) -> SharedString {
13426        match &self.mode {
13427            LayoutMode::CodeEditor { language, .. } => language.name(),
13428            _ => SharedString::default(),
13429        }
13430    }
13431
13432    /// Set enable/disable code folding.
13433    ///
13434    /// Default: true
13435    #[doc(hidden)]
13436    pub fn folding(mut self, folding: bool) -> Self {
13437        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13438            *f = folding;
13439        }
13440        self
13441    }
13442
13443    /// Set code folding at runtime.
13444    ///
13445    /// When disabling, all existing folds are cleared.
13446    pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
13447        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13448            *f = folding;
13449        }
13450        if !folding {
13451            self.display_map.clear_folds();
13452        }
13453        cx.notify();
13454    }
13455
13456    /// Unfold any folded ranges that hide the given position.
13457    ///
13458    /// Use this to reveal a position before acting on it (e.g. before
13459    /// [`Self::set_cursor_position`], which stops at a fold boundary),
13460    /// without touching folds elsewhere in the buffer. Fold candidates are
13461    /// kept, so the opened ranges can be folded again from the gutter.
13462    ///
13463    /// A fold keeps its own first and last line visible, so a position on
13464    /// either of them opens nothing. Nested folds all open, since opening
13465    /// only the outermost would leave the position hidden.
13466    ///
13467    /// Returns whether any fold was opened.
13468    pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
13469        let offset = self.text.position_to_offset(&position.into());
13470        let line = self.text.offset_to_point(offset).row;
13471        // A fold hides start_line + 1 ..= end_line - 1, so a line is hidden
13472        // exactly when some folded range strictly contains it.
13473        let covering: Vec<usize> = self
13474            .display_map
13475            .folded_ranges()
13476            .iter()
13477            .filter(|fold| line > fold.start_line && line < fold.end_line)
13478            .map(|fold| fold.start_line)
13479            .collect();
13480        if covering.is_empty() {
13481            return false;
13482        }
13483
13484        for start_line in covering {
13485            self.display_map.set_folded(start_line, false);
13486        }
13487        cx.notify();
13488        true
13489    }
13490
13491    /// Set enable/disable line number.
13492    #[doc(hidden)]
13493    pub fn line_number(mut self, line_number: bool) -> Self {
13494        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
13495            *l = line_number;
13496        }
13497        self
13498    }
13499
13500    /// Set line number.
13501    pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
13502        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
13503            if *l == line_number {
13504                return;
13505            }
13506            *l = line_number;
13507        }
13508        cx.notify();
13509    }
13510
13511    /// Set enable/disable automatic closing brackets and quotes.
13512    ///
13513    /// When enabled, typing an opener from [`LanguageConfig::auto_closing_pairs`](crate::input::language_config::LanguageConfig::auto_closing_pairs) inserts the
13514    /// matching closer and places the cursor inside. Typing a closer that is
13515    /// already present just moves past it. Default: true
13516    #[doc(hidden)]
13517    pub fn auto_close(mut self, auto_close: bool) -> Self {
13518        self.mode.set_auto_close(auto_close);
13519        self
13520    }
13521
13522    /// Set automatic closing brackets and quotes at runtime.
13523    pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
13524        self.mode.set_auto_close(auto_close);
13525        cx.notify();
13526    }
13527
13528    /// Set enable/disable smart indent on Enter.
13529    ///
13530    /// When enabled, Enter uses structural brackets and
13531    /// [`LanguageConfig::indentation_rules`](crate::input::language_config::LanguageConfig::indentation_rules) to choose indentation.
13532    /// Default: true
13533    #[doc(hidden)]
13534    pub fn smart_indent(mut self, smart_indent: bool) -> Self {
13535        self.mode.set_smart_indent(smart_indent);
13536        self
13537    }
13538
13539    /// Set smart indent on Enter at runtime.
13540    pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
13541        self.mode.set_smart_indent(smart_indent);
13542        cx.notify();
13543    }
13544}