Skip to main content

gpui_base/input/base/
state.rs

1//! A text input field that allows the user to enter text.
2//!
3//! Based on the `Input` example from the `gpui` crate.
4//! https://github.com/zed-industries/zed/blob/main/crates/gpui/examples/input.rs
5use gpui::TextAlign;
6use gpui::{
7    Action, App, AppContext, Bounds, ClipboardItem, Context, Edges, Entity, EntityInputHandler,
8    EventEmitter, FocusHandle, Focusable, Hsla, InteractiveElement as _, IntoElement, KeyBinding,
9    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point,
10    Render, ScrollEvent, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _,
11    Subscription, UTF16Selection, WeakFocusHandle, Window, actions, div, point,
12    prelude::FluentBuilder as _, px,
13};
14use gpui::{Autocapitalize, TextInputAction, TextInputConfiguration};
15use ropey::{Rope, RopeSlice};
16use serde::Deserialize;
17use std::borrow::Cow;
18use std::cell::Cell;
19use std::ops::Range;
20use std::rc::Rc;
21use sum_tree::Bias;
22use unicode_segmentation::*;
23
24use super::{
25    DiagnosticSet, DisplayMap, FoldPlaceholderRenderer, InputContextMenuCapabilities,
26    InputEditorStyle, InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep,
27    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, StepAction, 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/// Stashed during prepaint so caret-anchored popups can position themselves
377/// from the current frame's geometry in their deferred prepaint.
378#[derive(Clone, Copy, Debug)]
379#[doc(hidden)]
380pub struct PrepaintCaretGeometry {
381    cursor_bounds: Bounds<Pixels>,
382    line_height: Pixels,
383    input_bounds: Bounds<Pixels>,
384    scroll_offset: Point<Pixels>,
385    /// A resize owns visibility while its requested repaint settles.
386    pub(super) resize_reveal_owned: bool,
387}
388
389impl PrepaintCaretGeometry {
390    pub(super) fn new(
391        cursor_bounds: Bounds<Pixels>,
392        line_height: Pixels,
393        input_bounds: Bounds<Pixels>,
394        scroll_offset: Point<Pixels>,
395    ) -> Self {
396        Self {
397            cursor_bounds,
398            line_height,
399            input_bounds,
400            scroll_offset,
401            resize_reveal_owned: false,
402        }
403    }
404
405    /// The active caret's bounds from the fresh prepaint layout.
406    pub fn cursor_bounds(&self) -> Bounds<Pixels> {
407        self.cursor_bounds
408    }
409
410    /// Line height from the fresh prepaint layout.
411    pub fn line_height(&self) -> Pixels {
412        self.line_height
413    }
414
415    /// The input container bounds from the fresh prepaint.
416    pub fn input_bounds(&self) -> Bounds<Pixels> {
417        self.input_bounds
418    }
419
420    /// The scroll offset that will be in effect after paint, clamped like
421    /// `InputBaseState::update_scroll_offset` clamps it.
422    pub fn scroll_offset(&self) -> Point<Pixels> {
423        self.scroll_offset
424    }
425}
426
427/// The shared text-editing engine behind [`crate::input::InputState`],
428/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
429///
430/// `M` is the mode marker: it carries no data and only decides which methods
431/// exist, so an ordinary input cannot reach the editor's language features.
432///
433/// The three states are type aliases of this one, which is why this name is
434/// public: an alias is only as usable as the type behind it, so hiding this
435/// would leave `InputState` unable to do anything. Prefer naming the aliases
436/// — write `InputState`, not `InputBaseState<InputMode>`.
437pub struct InputBaseState<M: InputModeKind> {
438    /// State only this mode needs. See [`InputModeKind::Extras`].
439    pub(crate) extras: M::Extras,
440    pub(super) focus_handle: FocusHandle,
441    selection_focus: Option<WeakFocusHandle>,
442    pub(super) mode: LayoutMode,
443    pub(super) text: Rope,
444    pub(super) display_map: DisplayMap,
445    pub(super) undo_manager: UndoManager,
446    pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
447    pub(super) pending_token: Option<super::InlineToken>,
448    pub(super) replaying_history: bool,
449    pub(super) validated_token_edit: bool,
450    pub(super) document_revision: u64,
451    pub(super) token_presentation: super::InlineTokenPresentation,
452    pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
453    /// Real per-frame bounds of the placed token elements, keyed by token
454    /// start offset; used for hover payloads and stale-hover reconciliation.
455    pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
456    /// The currently hovered token: its entered span, last measured bounds,
457    /// and UTF-16 range as of entry. Retained so hover exit can still be
458    /// delivered when the token is removed, replaced, scrolled out, or
459    /// disabled.
460    pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
461    pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
462    /// The start offset of a pressed token, with the document revision and
463    /// pointer position at the press.
464    pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
465    pub(super) search_session: super::SearchSession,
466    /// Advances every time search is explicitly invoked. See
467    /// [`InputBaseState::search_activation_revision`].
468    pub(super) search_activation_revision: u64,
469    pub(super) searchable: bool,
470    pub(super) replaceable: bool,
471    pub(super) soft_wrap: bool,
472    pub(super) wrapping_indent: WrappingIndent,
473    pub(super) scroll_beyond_last_line: Option<usize>,
474    pub(super) cursor_surrounding_lines: Option<usize>,
475    pub(super) blink_cursor: Entity<BlinkCursor>,
476    pub(super) loading: bool,
477    /// The cursors and selections.
478    ///
479    /// Always contains at least one selection where index 0 is the active cursor.
480    pub(super) selections: Selections,
481    /// Range for save the selected word, use to keep word range when drag move.
482    pub(super) selected_word_range: Option<CursorSelection>,
483    /// The marked range is the temporary insert text on IME typing.
484    pub(super) ime_marked_range: Option<CursorSelection>,
485    /// Text before an unannounced IME composition, until the next change.
486    ime_original_text: Option<Rope>,
487    pub(super) last_layout: Option<LastLayout>,
488    /// Fresh caret geometry stashed during prepaint for caret-anchored popups.
489    ///
490    /// Popups are positioned in their deferred prepaint, which runs after the
491    /// input's prepaint but before its paint.
492    pub(crate) prepaint_caret_geometry: Option<PrepaintCaretGeometry>,
493    pub(super) last_cursor: Option<usize>,
494    /// Where the platform was last told the caret is, for its IME panel.
495    pub(super) ime_anchor: Option<(Point<Pixels>, Option<Bounds<Pixels>>)>,
496    /// The input container bounds
497    pub(super) input_bounds: Bounds<Pixels>,
498    /// The text bounds
499    pub(super) last_bounds: Option<Bounds<Pixels>>,
500    /// The fully visible part of the window this input last asked its scroll
501    /// containers to reveal it in, while focused. `None` while unfocused.
502    pub(super) revealed_viewport: Option<Bounds<Pixels>>,
503    pub(super) last_selected_range: Option<CursorSelection>,
504    /// The current edit batch, copied into an event when a change is emitted.
505    pub(super) last_input_edits: Vec<(InputEdit, Rope)>,
506    pub(super) selecting: bool,
507    /// Anchor point of an in-progress columnar (block) selection.
508    pub(super) column_select_start: Option<ColumnarPoint>,
509    /// The selection a long press made, with its handles and edit menu.
510    pub(super) touch_selection: super::touch::TouchSelection,
511    pub(crate) disabled: bool,
512    pub(crate) readonly: bool,
513    pub(crate) text_align: TextAlign,
514    pub(super) masked: bool,
515    pub(super) clean_on_escape: bool,
516    pub(super) submit_on_enter: bool,
517    /// Overrides for [`Self::text_input_configuration`].
518    pub(super) input_action: Option<TextInputAction>,
519    pub(super) autocorrect: Option<bool>,
520    pub(super) autocapitalize: Option<Autocapitalize>,
521    pub(super) show_whitespaces: bool,
522    /// This flag tells the renderer to prefer the end of the current visual line.
523    pub(crate) cursor_line_end_affinity: bool,
524    pub(super) pattern: Option<regex::Regex>,
525    pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
526    /// The step strategy for [`super::NumberInput`] to increment/decrement.
527    /// See [`Self::step`] and [`Self::step_by`].
528    pub(crate) number_step: Option<NumberStep>,
529    /// The minimum value for [`super::NumberInput`]. See [`Self::min`].
530    pub(crate) number_min: Option<f64>,
531    /// The maximum value for [`super::NumberInput`]. 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) fold_placeholder_renderer: Option<FoldPlaceholderRenderer>,
559    pub(super) fold_background: Option<Hsla>,
560    pub(super) accessibility: Option<InputAccessibility>,
561    /// What paints in place of Base's editor scrollbar, when a consumer
562    /// supplies its own.
563    pub(super) scrollbar_renderer: Option<crate::input::EditorScrollbarRenderer>,
564
565    /// The mask pattern for formatting the input text
566    pub(crate) mask_pattern: MaskPattern,
567    /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`]
568    /// or [`Self::set_mask_pattern`]), to let [`super::NumberInput`] only apply
569    /// its default mask when the user has not made an explicit choice.
570    pub(super) mask_pattern_set: bool,
571    pub(super) placeholder: SharedString,
572
573    /// Diagnostic currently requested by pointer hover; applications render it.
574    pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
575
576    context_menu_handler: Option<
577        Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
578    >,
579    pending_context_menu: Option<(Point<Pixels>, usize)>,
580    context_menu_offset: Option<usize>,
581
582    /// Whether the context menu that shows on right-click is enabled.
583    ///
584    pub(super) enable_context_menu: bool,
585
586    /// A flag to indicate if we are currently inserting a completion item.
587    pub(super) completion_inserting: bool,
588    pub(super) overlay_action_handler: Option<
589        Rc<
590            dyn Fn(
591                super::InputOverlayKind,
592                Box<dyn Action>,
593                &mut Window,
594                &mut Context<InputBaseState<M>>,
595            ) -> bool,
596        >,
597    >,
598
599    /// A flag to indicate if we have a pending update to the text.
600    ///
601    /// If true, will call some update (for example LSP, Syntax Highlight) before render.
602    _pending_update: bool,
603    /// A flag to indicate if we should ignore the next completion event.
604    pub(super) silent_replace_text: bool,
605    /// A flag to indicate if we should emit InputEvents.
606    pub(super) emit_events: bool,
607
608    _subscriptions: Vec<Subscription>,
609
610    pub(super) auto_scroll: AutoScroll,
611}
612
613/// Accessibility presentation for the editor's existing keyboard-focus boundary.
614///
615/// Frames and their addon controls keep their own identities. This projection
616/// does not create a focus handle or register another text Tab stop. The engine
617/// supplies the live value and guards accessibility actions against its current
618/// disabled, read-only and masked state.
619#[derive(Clone, Debug)]
620pub struct InputAccessibility {
621    role: Option<gpui::Role>,
622    label: Option<SharedString>,
623    placeholder: Option<SharedString>,
624    accessibility_id: Option<SharedString>,
625    value_exposed: bool,
626}
627
628impl InputAccessibility {
629    pub fn new(role: Option<gpui::Role>) -> Self {
630        Self {
631            role,
632            label: None,
633            placeholder: None,
634            accessibility_id: None,
635            value_exposed: true,
636        }
637    }
638
639    pub fn with_label(mut self, label: Option<SharedString>) -> Self {
640        self.label = label;
641        self
642    }
643
644    pub fn with_placeholder(mut self, placeholder: Option<SharedString>) -> Self {
645        self.placeholder = placeholder;
646        self
647    }
648
649    pub fn with_accessibility_id(mut self, id: Option<SharedString>) -> Self {
650        self.accessibility_id = id;
651        self
652    }
653
654    /// Suppress values for secret content even when the mask is revealed.
655    pub fn with_value_exposed(mut self, exposed: bool) -> Self {
656        self.value_exposed = exposed;
657        self
658    }
659
660    pub fn role(&self) -> Option<gpui::Role> {
661        self.role
662    }
663
664    pub fn label(&self) -> Option<&SharedString> {
665        self.label.as_ref()
666    }
667
668    pub fn placeholder(&self) -> Option<&SharedString> {
669        self.placeholder.as_ref()
670    }
671
672    pub fn accessibility_id(&self) -> Option<&SharedString> {
673        self.accessibility_id.as_ref()
674    }
675
676    pub fn value_exposed(&self) -> bool {
677        self.value_exposed
678    }
679}
680
681/// Read-only styling data exposed to presentation facades.
682///
683/// The fields are private and read through the methods below, so that a new
684/// one can be added without breaking the facades.
685#[derive(Clone)]
686pub struct InputPresentation {
687    focus_handle: FocusHandle,
688    disabled: bool,
689    readonly: bool,
690    loading: bool,
691    masked: bool,
692    multi_line: bool,
693    code_editor: bool,
694    text_align: TextAlign,
695    placeholder: SharedString,
696    mask_placeholder: Option<String>,
697}
698
699impl InputPresentation {
700    pub fn focus_handle(&self) -> &FocusHandle {
701        &self.focus_handle
702    }
703
704    pub fn is_disabled(&self) -> bool {
705        self.disabled
706    }
707
708    pub fn is_readonly(&self) -> bool {
709        self.readonly
710    }
711
712    /// Returns true if the user is allowed to change the text.
713    ///
714    /// See also: [`InputBaseState::is_editable`].
715    pub fn is_editable(&self) -> bool {
716        !self.disabled && !self.readonly
717    }
718
719    pub fn is_loading(&self) -> bool {
720        self.loading
721    }
722
723    pub fn is_masked(&self) -> bool {
724        self.masked
725    }
726
727    pub fn is_multi_line(&self) -> bool {
728        self.multi_line
729    }
730
731    pub fn is_code_editor(&self) -> bool {
732        self.code_editor
733    }
734
735    pub fn text_align(&self) -> TextAlign {
736        self.text_align
737    }
738
739    pub fn placeholder(&self) -> &SharedString {
740        &self.placeholder
741    }
742
743    /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
744    pub fn mask_placeholder(&self) -> Option<&str> {
745        self.mask_placeholder.as_deref()
746    }
747}
748
749impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
750impl<M: InputModeKind> EventEmitter<InputEditsEvent> for InputBaseState<M> {}
751
752impl<M: InputModeKind> InputBaseState<M> {
753    #[doc(hidden)]
754    pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
755        let layout = self.last_layout.as_ref()?;
756        Some((layout.cursor_bounds?, layout.line_height))
757    }
758
759    /// Caret geometry from the latest prepaint, for caret-anchored popups.
760    ///
761    /// Popups positioned in their deferred prepaint read this to anchor to
762    /// the current frame's caret instead of the previous frame's paint.
763    #[doc(hidden)]
764    pub fn prepaint_caret_geometry(&self) -> Option<PrepaintCaretGeometry> {
765        self.prepaint_caret_geometry
766    }
767
768    pub fn input_bounds(&self) -> Bounds<Pixels> {
769        self.input_bounds
770    }
771
772    pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
773        self.last_bounds
774    }
775
776    /// The cached display map for querying wrapped rows and display positions.
777    ///
778    /// Reading this does not prepare text or force layout. Before the first
779    /// layout, [`DisplayMap::wrap_row_count`] can be zero; prepared empty text
780    /// has one row. The count describes content, independent of minimum rows,
781    /// auto-grow limits and viewport height.
782    ///
783    /// Text edits use the cached wrapping parameters. Layout refreshes the
784    /// cache after width or font changes; consume that count on a subsequent
785    /// render, or use [`Self::prewrap`] to prepare it before the first layout.
786    pub fn display_map(&self) -> &DisplayMap {
787        &self.display_map
788    }
789
790    /// Wrap the text for `font`, `font_size` and `width` before the first
791    /// layout, so that [`DisplayMap::wrap_row_count`] is known on the first frame.
792    ///
793    /// Call it after setting the value and the wrapping indent. `width` is the
794    /// width of the input's text area: its width less its padding, and less
795    /// the line-number gutter for an editor with line numbers. It wraps as
796    /// layout does, a little short of that width and with the state's wrapping
797    /// indent. Once the input has been laid out this does nothing, and layout
798    /// keeps the wrap up to date. The font and font size must match the input's
799    /// actual text style.
800    pub fn prewrap(
801        &mut self,
802        font: gpui::Font,
803        font_size: Pixels,
804        width: Pixels,
805        cx: &mut Context<Self>,
806    ) {
807        if self.last_layout.is_some() {
808            return;
809        }
810        let wrap_width = (width - RIGHT_MARGIN).max(px(1.));
811        self.display_map.set_font(font, font_size, cx);
812        self.display_map
813            .set_tab_size(self.mode.tab_size().tab_size, cx);
814        self.display_map
815            .on_layout_changed(self.soft_wrap.then_some(wrap_width), cx);
816        self.display_map
817            .set_wrapping_indent(self.wrapping_indent, cx);
818        self.display_map.ensure_text_prepared(&self.text, cx);
819    }
820
821    pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
822        self.diagnostic_popover.clone()
823    }
824
825    pub fn presentation(&self) -> InputPresentation {
826        InputPresentation {
827            focus_handle: self.focus_handle.clone(),
828            disabled: self.disabled,
829            readonly: self.readonly,
830            loading: self.loading,
831            masked: self.masked,
832            multi_line: self.is_multi_line(),
833            code_editor: self.is_code_editor(),
834            text_align: self.text_align,
835            placeholder: self.placeholder.clone(),
836            mask_placeholder: self.mask_pattern.placeholder(),
837        }
838    }
839
840    /// Whether this input spans more than one line.
841    ///
842    /// Answered by the mode marker, which is fixed when the state is built.
843    /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
844    #[inline]
845    /// Whether this input paints scrollbars.
846    ///
847    /// Only a multi-line input can scroll: a single-line input keeps its
848    /// caret in view by moving its own offset, and never has a viewport a
849    /// user could drag. Adding the editor scrollbar to every input put a
850    /// thumb inside every text field, which is a control the field does not
851    /// have.
852    pub(crate) fn shows_scrollbar(&self) -> bool {
853        self.is_multi_line()
854    }
855
856    pub fn is_multi_line(&self) -> bool {
857        M::MULTI_LINE
858    }
859
860    /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
861    #[inline]
862    pub fn is_single_line(&self) -> bool {
863        !M::MULTI_LINE
864    }
865
866    /// Whether this input is a source-code editor.
867    #[inline]
868    pub fn is_code_editor(&self) -> bool {
869        M::CODE_EDITOR
870    }
871
872    /// Whether the user is allowed to copy the selection out.
873    ///
874    /// A masked input keeps its value out of the clipboard.
875    pub fn is_copyable(&self) -> bool {
876        self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
877    }
878
879    pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
880        let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
881        InputContextMenuCapabilities::new()
882            .disabled(self.disabled)
883            .readonly(self.readonly)
884            .code_editor(self.is_code_editor())
885            .selection(!self.active_selection().is_empty())
886            .masked(self.masked)
887            .go_to_definition(go_to_definition)
888            .code_actions(code_actions)
889    }
890
891    pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
892        if !self.is_single_line() || self.text_align == text_align {
893            return;
894        }
895
896        self.text_align = text_align;
897        cx.notify();
898    }
899
900    /// Flip the password mask.
901    ///
902    /// Setting the mask is a single-line method, but flipping it stays here:
903    /// the reveal button is rendered from the generic path, and it can only be
904    /// switched on through [`crate::input::InputState`] anyway.
905    pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
906        self.masked = !self.masked;
907        cx.notify();
908    }
909
910    pub fn on_context_menu(
911        &mut self,
912        handler: Rc<
913            dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
914        >,
915    ) {
916        self.context_menu_handler = Some(handler);
917    }
918
919    /// Keeps the selection highlighted while this popup or one of its children has focus.
920    ///
921    /// This does not transfer keyboard focus or keep the caret visible. The
922    /// association holds only a weak focus handle. Pass `None` to clear it.
923    pub fn set_selection_focus(&mut self, focus: Option<FocusHandle>, cx: &mut Context<Self>) {
924        self.selection_focus = focus.as_ref().map(FocusHandle::downgrade);
925        cx.notify();
926    }
927
928    /// Whether the input or its associated selection popup has focus.
929    pub fn has_selection_focus(&self, window: &Window, cx: &App) -> bool {
930        self.focus_handle.is_focused(window)
931            || self
932                .selection_focus
933                .as_ref()
934                .and_then(WeakFocusHandle::upgrade)
935                .is_some_and(|focus| focus.is_focused(window) || focus.contains_focused(window, cx))
936    }
937
938    /// Build the engine. Each mode's own `new` sets its layout on top of this.
939    fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
940        let focus_handle = cx.focus_handle().tab_stop(true);
941        let blink_cursor = cx.new(BlinkCursor::new);
942        let undo_manager = UndoManager::new();
943
944        let _subscriptions = vec![
945            // Key bindings can consume events before on_key_down. Observe input
946            // before action dispatch so every keystroke resets the blink delay.
947            cx.intercept_keystrokes({
948                let focus_handle = focus_handle.clone();
949                let blink_cursor = blink_cursor.downgrade();
950                move |_, window, cx| {
951                    if focus_handle.is_focused(window) {
952                        _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
953                    }
954                }
955            }),
956            // Observe the blink cursor to repaint the view when it changes.
957            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
958            // Blink the cursor when the window is active, pause when it's not.
959            cx.observe_window_activation(window, |input, window, cx| {
960                if !window.is_window_active() {
961                    input.cancel_mouse_gesture(cx);
962                }
963                if window.is_window_active() {
964                    let focus_handle = input.focus_handle.clone();
965                    if focus_handle.is_focused(window) {
966                        input.blink_cursor.update(cx, |blink_cursor, cx| {
967                            blink_cursor.start(cx);
968                        });
969                    }
970                }
971            }),
972            cx.observe_window_bounds(window, |input, _, cx| input.cancel_mouse_gesture(cx)),
973            cx.on_focus(&focus_handle, window, Self::on_focus),
974            cx.on_blur(&focus_handle, window, Self::on_blur),
975        ];
976
977        let text_style = window.text_style();
978
979        Self {
980            extras: M::Extras::default(),
981            focus_handle: focus_handle.clone(),
982            selection_focus: None,
983            text: "".into(),
984            display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
985            search_session: super::SearchSession::default(),
986            search_activation_revision: 0,
987            searchable: false,
988            replaceable: true,
989            soft_wrap: true,
990            wrapping_indent: WrappingIndent::default(),
991            scroll_beyond_last_line: None,
992            cursor_surrounding_lines: None,
993            blink_cursor,
994            undo_manager,
995            inline_tokens: None,
996            pending_token: None,
997            replaying_history: false,
998            validated_token_edit: false,
999            document_revision: 0,
1000            token_presentation: Default::default(),
1001            token_bounds: Default::default(),
1002            hovered_token: None,
1003            pending_token_hover_exits: Vec::new(),
1004            token_layout_cache: None,
1005            pressed_token: None,
1006            selections: Selections::default(),
1007            selected_word_range: None,
1008            ime_marked_range: None,
1009            ime_original_text: None,
1010            input_bounds: Bounds::default(),
1011            selecting: false,
1012            touch_selection: Default::default(),
1013            disabled: false,
1014            readonly: false,
1015            text_align: TextAlign::Left,
1016            masked: false,
1017            clean_on_escape: false,
1018            submit_on_enter: false,
1019            input_action: None,
1020            autocorrect: None,
1021            autocapitalize: None,
1022            show_whitespaces: false,
1023            loading: false,
1024            pattern: None,
1025            validate: None,
1026            number_step: Some(NumberStep::Fixed(1.)),
1027            number_min: None,
1028            number_max: None,
1029            mode: LayoutMode::default(),
1030            last_layout: None,
1031            prepaint_caret_geometry: None,
1032            last_bounds: None,
1033            revealed_viewport: None,
1034            last_selected_range: None,
1035            last_input_edits: Vec::new(),
1036            column_select_start: None,
1037            last_cursor: None,
1038            ime_anchor: None,
1039            scroll_handle: ScrollHandle::new(),
1040            scroll_bounce: crate::ScrollBounce::enabled_by_default(),
1041            overscroll: Overscroll::default(),
1042            scroll_size: gpui::size(px(0.), px(0.)),
1043            editor_scrollbar_snapshot: Cell::new(None),
1044            overview_ruler_rows: Default::default(),
1045            longest_line_width: Cell::new(None),
1046            editor_paddings: Edges::default(),
1047            deferred_scroll_offset: None,
1048            placeholder: SharedString::default(),
1049            mask_pattern: MaskPattern::default(),
1050            mask_pattern_set: false,
1051            editor_style: InputEditorStyle::default(),
1052            projected_editor_style: InputEditorStyle::default(),
1053            fold_placeholder_renderer: None,
1054            fold_background: None,
1055            accessibility: None,
1056            scrollbar_renderer: None,
1057            diagnostic_popover: None,
1058            context_menu_handler: None,
1059            pending_context_menu: None,
1060            context_menu_offset: None,
1061            enable_context_menu: true,
1062            completion_inserting: false,
1063            overlay_action_handler: None,
1064            silent_replace_text: false,
1065            emit_events: true,
1066            _subscriptions,
1067            _pending_update: false,
1068            cursor_line_end_affinity: false,
1069            auto_scroll: AutoScroll::default(),
1070        }
1071    }
1072
1073    /// Sets whether the context menu that shows on right-click is enabled.
1074    ///
1075    /// The context menu is enabled by default. Disabling it turns off the
1076    /// right-click menu entirely, including a custom menu set on the element.
1077    /// A custom menu already replaces the built-in one, so keep this enabled
1078    /// to show only your own items.
1079    pub fn context_menu(mut self, enable: bool) -> Self {
1080        self.enable_context_menu = enable;
1081        self
1082    }
1083
1084    pub fn set_context_menu_enabled(&mut self, enabled: bool) {
1085        self.enable_context_menu = enabled;
1086    }
1087
1088    /// Set whether search UI allows replacement, default is true.
1089    #[doc(hidden)]
1090    pub fn replaceable(mut self, allow: bool) -> Self {
1091        self.replaceable = allow;
1092        self
1093    }
1094
1095    /// Set placeholder
1096    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1097        self.placeholder = placeholder.into();
1098        self
1099    }
1100
1101    /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode.
1102    pub fn set_highlighter(
1103        &mut self,
1104        new_language: impl Into<SharedString>,
1105        cx: &mut Context<Self>,
1106    ) {
1107        match &mut self.mode {
1108            LayoutMode::CodeEditor {
1109                language,
1110                highlighter,
1111                ..
1112            } => {
1113                language.set_name(new_language.into());
1114                *highlighter.borrow_mut() = None;
1115            }
1116            _ => {}
1117        }
1118        self.refresh(cx);
1119    }
1120
1121    fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
1122        match &mut self.mode {
1123            LayoutMode::CodeEditor { highlighter, .. } => {
1124                *highlighter.borrow_mut() = None;
1125            }
1126            _ => {}
1127        }
1128        cx.notify();
1129    }
1130
1131    /// Install the parser/highlighter adapter used by code-editor mode.
1132    pub fn set_highlighter_factory(
1133        &mut self,
1134        factory: InputHighlighterFactory,
1135        cx: &mut Context<Self>,
1136    ) {
1137        self.mode.set_highlighter_factory(factory);
1138        self._pending_update = true;
1139        self.token_layout_cache = None;
1140        cx.notify();
1141    }
1142
1143    /// Install a default adapter without replacing an application-provided one.
1144    pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
1145        self.mode.ensure_highlighter_factory(factory);
1146    }
1147
1148    pub fn set_editor_style(&mut self, style: InputEditorStyle) {
1149        self.editor_style = style.clone();
1150        self.projected_editor_style = style;
1151    }
1152
1153    /// Draws a placeholder right after the text of each folded line, given its
1154    /// buffer row. Clicking it unfolds the line.
1155    pub fn set_fold_placeholder_renderer(
1156        &mut self,
1157        renderer: Option<FoldPlaceholderRenderer>,
1158        cx: &mut Context<Self>,
1159    ) {
1160        self.fold_placeholder_renderer = renderer;
1161        cx.notify();
1162    }
1163
1164    /// Fills each folded line across the editor, as VS Code's
1165    /// `editor.foldBackground`.
1166    pub fn set_fold_background(&mut self, color: Option<Hsla>, cx: &mut Context<Self>) {
1167        self.fold_background = color;
1168        cx.notify();
1169    }
1170
1171    /// Project semantics onto the editor, never onto a second focus owner.
1172    pub fn set_accessibility(&mut self, accessibility: InputAccessibility) {
1173        self.accessibility = Some(accessibility);
1174    }
1175
1176    fn handle_accessibility_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1177        if !self.disabled {
1178            self.focus(window, cx);
1179        }
1180    }
1181
1182    fn handle_accessibility_set_value(
1183        &mut self,
1184        data: Option<&gpui::accesskit::ActionData>,
1185        window: &mut Window,
1186        cx: &mut Context<Self>,
1187    ) {
1188        let Some(gpui::accesskit::ActionData::Value(value)) = data else {
1189            return;
1190        };
1191        // The action may have been queued before editability changed.
1192        if self.is_editable() {
1193            self.replace_all(value.to_string(), window, cx);
1194        }
1195    }
1196
1197    /// Set presentation padding for multi-line text and its scrollbar layout.
1198    #[doc(hidden)]
1199    pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
1200        self.editor_paddings = paddings;
1201    }
1202
1203    /// Supply the element painted in place of the editor's scrollbar, or
1204    /// `None` to keep Base's. The renderer is called where the editor paints
1205    /// its scrollbar, with that frame's [`EditorScrollbarContext`]. Like
1206    /// [`Self::set_editor_style`], this does not notify, so it can be called
1207    /// while rendering.
1208    ///
1209    /// [`EditorScrollbarContext`]: crate::input::EditorScrollbarContext
1210    pub fn set_scrollbar_renderer(
1211        &mut self,
1212        renderer: Option<crate::input::EditorScrollbarRenderer>,
1213    ) {
1214        self.scrollbar_renderer = renderer;
1215    }
1216
1217    pub fn apply_highlighter_fold_candidates(
1218        &mut self,
1219        candidates: Vec<crate::input::FoldRange>,
1220        cx: &mut Context<Self>,
1221    ) {
1222        if self.mode.is_folding() {
1223            self.display_map.set_fold_candidates(candidates);
1224        }
1225        cx.notify();
1226    }
1227
1228    #[inline]
1229    pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
1230        self.mode.diagnostics()
1231    }
1232
1233    #[inline]
1234    pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
1235        self.mode.diagnostics_mut()
1236    }
1237
1238    /// Set placeholder
1239    pub fn set_placeholder(
1240        &mut self,
1241        placeholder: impl Into<SharedString>,
1242        _: &mut Window,
1243        cx: &mut Context<Self>,
1244    ) {
1245        self.placeholder = placeholder.into();
1246        cx.notify();
1247    }
1248
1249    /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
1250    ///
1251    /// Returns:
1252    ///
1253    /// - The index of the line (zero-based) containing the offset.
1254    /// - The index of the sub-line (zero-based) within the line containing the offset.
1255    /// - The position of the offset.
1256    pub(super) fn line_and_position_for_offset(
1257        &self,
1258        offset: usize,
1259    ) -> (usize, usize, Option<Point<Pixels>>) {
1260        let Some(last_layout) = &self.last_layout else {
1261            return (0, 0, None);
1262        };
1263        let line_height = last_layout.line_height;
1264        let target_row = self.text.offset_to_point(offset.min(self.text.len())).row;
1265
1266        let mut y_offset = last_layout.visible_top;
1267        for (vi, line) in last_layout.lines.iter().enumerate() {
1268            let buffer_line = last_layout.visible_buffer_lines[vi];
1269            if buffer_line == target_row {
1270                let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
1271                let local_offset = offset.saturating_sub(prev_lines_offset).min(line.len());
1272                let pos = line
1273                    .position_for_index(local_offset, last_layout, false)
1274                    .unwrap_or_else(|| point(px(0.), px(0.)));
1275                let sub_line_index = (pos.y / line_height) as usize;
1276                let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
1277                return (vi, sub_line_index, Some(adjusted_pos));
1278            }
1279
1280            y_offset += line.size(line_height).height;
1281        }
1282        (0, 0, None)
1283    }
1284
1285    /// Set the value of the input field: plain text, or [`InputContent`] to
1286    /// restore text together with its inline tokens. Editing history is
1287    /// cleared and no [`InputEvent::Change`] is emitted.
1288    ///
1289    /// For single-line inputs the caret is placed at the end of the text while
1290    /// the view is scrolled back to the start, so a long value shows its
1291    /// beginning instead of its tail (matching HTML `<input>`). Multi-line
1292    /// inputs reset the selection to `0..0`.
1293    pub fn set_value(
1294        &mut self,
1295        value: impl Into<super::InputContent>,
1296        window: &mut Window,
1297        cx: &mut Context<Self>,
1298    ) {
1299        let content = value.into();
1300        self.inline_tokens = None;
1301        self.undo_manager.set_ignoring(true);
1302        self.emit_events = false;
1303        self.replace_text(content.text().clone(), window, cx);
1304        self.ime_original_text = None;
1305        self.install_tokens(content);
1306        self.undo_manager.set_ignoring(false);
1307        self.emit_events = true;
1308
1309        self.reset_selection();
1310        self.reset_lsp_state();
1311        self.reset_scroll_to_start();
1312
1313        self.undo_manager.clear();
1314        cx.notify();
1315    }
1316
1317    /// Replace the entire text content while preserving undo history.
1318    ///
1319    /// Unlike [`set_value`](Self::set_value), this method records the
1320    /// replacement in the undo stack, allowing the user to undo/redo
1321    /// the change. The selection is placed at the end of the new text
1322    /// for single-line inputs, or cleared (0..0) for multi-line inputs.
1323    ///
1324    /// Use this when programmatically replacing the full text but the
1325    /// user should still be able to undo the operation — e.g. formatting.
1326    pub fn replace_all(
1327        &mut self,
1328        text: impl Into<SharedString>,
1329        window: &mut Window,
1330        cx: &mut Context<Self>,
1331    ) {
1332        self.replace_text(text, window, cx);
1333        self.reset_selection();
1334        self.reset_lsp_state();
1335        self.reset_scroll_to_start();
1336
1337        cx.notify();
1338    }
1339
1340    /// Perform `f` with the user-facing edit restrictions lifted.
1341    ///
1342    /// The `disabled` and `readonly` modes only reject the changes made by the
1343    /// user, the programmatic APIs must always be able to update the text.
1344    pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1345        let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1346        (self.disabled, self.readonly) = (false, false);
1347        f(self);
1348        (self.disabled, self.readonly) = (was_disabled, was_readonly);
1349    }
1350
1351    /// Insert text at the current cursor position.
1352    ///
1353    /// And the cursor will be moved to the end of inserted text.
1354    pub fn insert(
1355        &mut self,
1356        text: impl Into<SharedString>,
1357        window: &mut Window,
1358        cx: &mut Context<Self>,
1359    ) {
1360        let text: SharedString = text.into();
1361        self.with_edits_allowed(|this| {
1362            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1363            let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1364            this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1365            let end = this.active_selection().end;
1366            this.set_cursor_to(end);
1367        });
1368    }
1369
1370    /// Replace text at the current cursor position.
1371    ///
1372    /// And the cursor will be moved to the end of replaced text.
1373    pub fn replace(
1374        &mut self,
1375        text: impl Into<SharedString>,
1376        window: &mut Window,
1377        cx: &mut Context<Self>,
1378    ) {
1379        let text: SharedString = text.into();
1380        self.with_edits_allowed(|this| {
1381            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1382            this.replace_text_in_range_silent(None, &text, window, cx);
1383            let end = this.active_selection().end;
1384            this.set_cursor_to(end);
1385        });
1386    }
1387
1388    fn replace_text(
1389        &mut self,
1390        text: impl Into<SharedString>,
1391        window: &mut Window,
1392        cx: &mut Context<Self>,
1393    ) {
1394        let text: SharedString = text.into();
1395        self.with_edits_allowed(|this| {
1396            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1397            let range = 0..this.text.chars().map(|c| c.len_utf16()).sum();
1398            this.replace_text_in_range_silent(Some(range), &text, window, cx);
1399            this.reset_highlighter(cx);
1400        });
1401    }
1402
1403    fn reset_selection(&mut self) {
1404        self.selections.remove_all_but_active();
1405
1406        // For single-line inputs the caret is placed at the end of the text
1407        // (matching HTML `<input>`); multi-line inputs reset the selection to
1408        // `0..0`.
1409        if self.is_single_line() {
1410            let end = self.text.len();
1411            self.set_cursor_to(end);
1412        } else {
1413            self.active_selection_mut().clear();
1414        }
1415    }
1416
1417    fn reset_lsp_state(&mut self) {
1418        if self.is_code_editor() {
1419            self._pending_update = true;
1420            M::reset_language_features(self);
1421        }
1422    }
1423
1424    fn reset_scroll_to_start(&mut self) {
1425        // Move scroll to the start. For single-line the caret is at the end, so
1426        // override the cursor-follow scroll for the next painted frame to keep
1427        // the start visible; the deferred offset is consumed during that paint.
1428        self.scroll_handle.set_offset(point(px(0.), px(0.)));
1429        if self.is_single_line() {
1430            self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1431        }
1432    }
1433
1434    /// Set with disabled mode.
1435    ///
1436    /// See also: [`Self::set_disabled`].
1437    #[allow(unused)]
1438    pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1439        self.disabled = disabled;
1440        self
1441    }
1442
1443    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1444        if self.disabled == disabled {
1445            return;
1446        }
1447
1448        self.disabled = disabled;
1449        if disabled {
1450            M::hide_context_menu(self, cx);
1451            M::clear_inline_completion(self, cx);
1452        }
1453        cx.notify();
1454    }
1455
1456    /// Set with read-only mode.
1457    ///
1458    /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1459    /// focus, cursor, selection and copy behavior, it only rejects any change
1460    /// of the text made by the user.
1461    ///
1462    /// See also: [`Self::set_readonly`].
1463    #[allow(unused)]
1464    pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1465        self.readonly = readonly;
1466        self
1467    }
1468
1469    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1470        if self.readonly == readonly {
1471            return;
1472        }
1473
1474        self.readonly = readonly;
1475        if readonly {
1476            M::hide_context_menu(self, cx);
1477            M::clear_inline_completion(self, cx);
1478            self.search_session.replace_mode = false;
1479        }
1480        cx.notify();
1481    }
1482
1483    /// Returns true if the user is allowed to change the text.
1484    ///
1485    /// This is false when the input is `disabled` or `readonly`, the programmatic
1486    /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1487    pub fn is_editable(&self) -> bool {
1488        !self.disabled && !self.readonly
1489    }
1490
1491    /// Set true to clear the input by pressing Escape key.
1492    ///
1493    /// Not on Android, where Escape is also the back button.
1494    pub fn clean_on_escape(mut self) -> Self {
1495        self.clean_on_escape = true;
1496        self
1497    }
1498
1499    pub fn set_clean_on_escape(&mut self, clean: bool) {
1500        self.clean_on_escape = clean;
1501    }
1502
1503    /// Set true to treat `Enter` as a submit action in multi-line mode,
1504    /// while `Shift+Enter` inserts a newline.
1505    ///
1506    /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1507    #[doc(hidden)]
1508    pub fn submit_on_enter(mut self, submit: bool) -> Self {
1509        self.submit_on_enter = submit;
1510        self
1511    }
1512
1513    pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1514        self.submit_on_enter = submit;
1515        cx.notify();
1516    }
1517
1518    /// Set the action a software keyboard shows on its enter key, like Search
1519    /// or Send. Pressing it still emits [`InputEvent::PressEnter`].
1520    ///
1521    /// Default is [`TextInputAction::Done`] for a single-line input (and a
1522    /// multi-line one that submits on enter), and [`TextInputAction::Enter`]
1523    /// (a line break) for a multi-line input.
1524    pub fn input_action(mut self, action: TextInputAction) -> Self {
1525        self.input_action = Some(action);
1526        self
1527    }
1528
1529    /// Set whether the platform may autocorrect the text and offer word
1530    /// suggestions.
1531    ///
1532    /// Default is `false`. Enable this explicitly for fields that accept prose;
1533    /// masking or revealing text does not change the setting.
1534    pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1535        self.autocorrect = Some(autocorrect);
1536        self
1537    }
1538
1539    /// Set how a software keyboard capitalizes the text.
1540    ///
1541    /// Default is [`Autocapitalize::None`]. Enable capitalization explicitly for
1542    /// fields where it is appropriate, independently of autocorrection.
1543    pub fn autocapitalize(mut self, autocapitalize: Autocapitalize) -> Self {
1544        self.autocapitalize = Some(autocapitalize);
1545        self
1546    }
1547
1548    /// The text assistance a platform IME (a software keyboard) should give
1549    /// this input, from [`Self::input_action`], [`Self::autocorrect`] and
1550    /// [`Self::autocapitalize`] or the defaults they describe.
1551    pub fn text_input_configuration(&self) -> TextInputConfiguration {
1552        // Masking is a presentation choice, not a reliable content type: a
1553        // revealed password must not acquire text assistance. Keep assistance
1554        // opt-in for structured fields such as passwords, email and URLs.
1555        let autocorrect = self.autocorrect.unwrap_or(false);
1556        let input_action =
1557            self.input_action
1558                .unwrap_or(if self.is_multi_line() && !self.submit_on_enter {
1559                    TextInputAction::Enter
1560                } else {
1561                    TextInputAction::Done
1562                });
1563        TextInputConfiguration {
1564            autocorrect,
1565            autocapitalize: self.autocapitalize.unwrap_or(Autocapitalize::None),
1566            suggestions: autocorrect,
1567            input_action,
1568        }
1569    }
1570
1571    /// Set whether to show whitespace characters.
1572    #[doc(hidden)]
1573    pub fn show_whitespaces(mut self, show: bool) -> Self {
1574        self.show_whitespaces = show;
1575        self
1576    }
1577
1578    /// Update whether to show whitespace characters.
1579    pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1580        self.show_whitespaces = show;
1581        cx.notify();
1582    }
1583
1584    /// Empty rows reserved below the last line of content ("scroll
1585    /// beyond last line"), code-editor mode only. Mirrors VSCode's
1586    /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1587    ///
1588    /// - `None` (default): half the viewport, floored at
1589    ///   [`BOTTOM_MARGIN_ROWS`] line-heights.
1590    /// - `Some(0)`: no trailing space; the cursor sits flush with the
1591    ///   last row at scroll-max.
1592    /// - `Some(n)`: exactly `n` rows.
1593    pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1594        self.scroll_beyond_last_line = rows;
1595        self
1596    }
1597
1598    /// Update [`Self::scroll_beyond_last_line`] after construction.
1599    pub fn set_scroll_beyond_last_line(
1600        &mut self,
1601        rows: Option<usize>,
1602        _: &mut Window,
1603        cx: &mut Context<Self>,
1604    ) {
1605        if self.scroll_beyond_last_line == rows {
1606            return;
1607        }
1608        self.scroll_beyond_last_line = rows;
1609        cx.notify();
1610    }
1611
1612    /// Minimum number of lines the cursor is kept clear of the viewport's
1613    /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1614    /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1615    /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1616    /// empty region; this controls the cursor's resting distance from the
1617    /// edge.
1618    ///
1619    /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to
1620    ///   one line on small viewports.
1621    /// - `Some(n)`: requests `n` lines, clamped to half the viewport.
1622    ///
1623    /// In a constrained viewport, edge clearance yields to the cursor's
1624    /// complete visual row so surrounding space cannot clip the text being edited.
1625    pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1626        self.cursor_surrounding_lines = lines;
1627        self
1628    }
1629
1630    /// Update [`Self::cursor_surrounding_lines`] after construction.
1631    pub fn set_cursor_surrounding_lines(
1632        &mut self,
1633        lines: Option<usize>,
1634        _: &mut Window,
1635        cx: &mut Context<Self>,
1636    ) {
1637        if self.cursor_surrounding_lines == lines {
1638            return;
1639        }
1640        self.cursor_surrounding_lines = lines;
1641        cx.notify();
1642    }
1643
1644    /// Set the default value of the input field.
1645    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1646        let text: SharedString = value.into();
1647        self.text = Rope::from(self.normalize_input(&text).as_ref());
1648        if let Some(diagnostics) = self.mode.diagnostics_mut() {
1649            diagnostics.reset(&self.text)
1650        }
1651        // Note: We can't call display_map.set_text here because it needs cx.
1652        // The text will be set during prepare_if_need in element.rs
1653        self._pending_update = true;
1654        self
1655    }
1656
1657    /// Return the value of the input field as an owned string.
1658    ///
1659    /// The string is materialized on each call. See [`Self::text`] for the
1660    /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1661    pub fn value(&self) -> SharedString {
1662        SharedString::new(self.text.to_string())
1663    }
1664
1665    /// Return the portion of the value within the input field that
1666    /// is selected by the user, as an owned string.
1667    ///
1668    /// The string is materialized on each call. See [`Self::selected_text`]
1669    /// for the same selection borrowed out of the [`Rope`] the state owns.
1670    pub fn selected_value(&self) -> SharedString {
1671        SharedString::new(self.selected_text().to_string())
1672    }
1673
1674    /// Return the value without mask.
1675    pub fn unmask_value(&self) -> SharedString {
1676        self.mask_pattern.unmask(&self.text.to_string()).into()
1677    }
1678
1679    /// Kept so existing render paths keep compiling.
1680    ///
1681    /// Configuration used to be collected by a facade and applied here; the
1682    /// state now configures itself, so this does nothing and can be deleted at
1683    /// the call site.
1684    #[doc(hidden)]
1685    pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1686
1687    /// Return the text [`Rope`] of the input field.
1688    ///
1689    /// Borrowed from the state, so reading even a large document copies
1690    /// nothing. See [`Self::value`] when an owned string is wanted.
1691    pub fn text(&self) -> &Rope {
1692        &self.text
1693    }
1694
1695    /// Report the change with its own snapshot before the legacy notification.
1696    fn emit_change(&mut self, cx: &mut Context<Self>) {
1697        if let Some(original) = self.ime_original_text.take() {
1698            self.last_input_edits = vec![(
1699                Self::full_input_edit(&original, &self.text),
1700                self.text.clone(),
1701            )];
1702        }
1703        cx.emit(InputEditsEvent {
1704            edits: self.last_input_edits.clone(),
1705        });
1706        cx.emit(InputEvent::Change);
1707    }
1708
1709    fn full_input_edit(old_text: &Rope, new_text: &Rope) -> InputEdit {
1710        InputEdit {
1711            start_byte: 0,
1712            old_end_byte: old_text.len(),
1713            new_end_byte: new_text.len(),
1714            start_position: old_text.offset_to_point(0),
1715            old_end_position: old_text.offset_to_point(old_text.len()),
1716            new_end_position: new_text.offset_to_point(new_text.len()),
1717        }
1718    }
1719
1720    /// Return the (0-based) [`Position`] of the cursor.
1721    pub fn cursor_position(&self) -> Position {
1722        let offset = self.cursor();
1723        self.text.offset_to_position(offset)
1724    }
1725
1726    /// Set (0-based) [`Position`] of the cursor.
1727    ///
1728    /// This will move the cursor to the specified line and column, and update the selection range.
1729    pub fn set_cursor_position(
1730        &mut self,
1731        position: impl Into<Position>,
1732        window: &mut Window,
1733        cx: &mut Context<Self>,
1734    ) {
1735        let position: Position = position.into();
1736        let offset = self.text.position_to_offset(&position);
1737
1738        self.move_to(offset, None, cx);
1739        self.update_preferred_column();
1740        self.focus(window, cx);
1741    }
1742
1743    /// Focus the input field.
1744    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1745        self.focus_handle.focus(window, cx);
1746        self.blink_cursor.update(cx, |cursor, cx| {
1747            cursor.start(cx);
1748        });
1749    }
1750
1751    /// Refresh the input, so the next render re-runs syntax highlighting and
1752    /// the LSP providers, not just a redraw.
1753    ///
1754    /// Assigning the `lsp` providers (or other render-affecting state) at
1755    /// runtime does not take effect until the text next changes. Call this
1756    /// afterwards to force the refresh on the next render.
1757    ///
1758    /// ```ignore
1759    /// input.update(cx, |state, cx| {
1760    ///     state.extras.lsp.hover_provider = Some(provider);
1761    ///     state.refresh(cx);
1762    /// });
1763    /// ```
1764    pub fn refresh(&mut self, cx: &mut Context<Self>) {
1765        self._pending_update = true;
1766        cx.notify();
1767    }
1768
1769    pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1770        self.undo_manager.break_transaction_coalescing();
1771        let mirrored = self.arrows_mirrored(cx);
1772        self.select_all_cursors_to(
1773            move |s, sel| {
1774                if mirrored {
1775                    s.next_boundary(sel.cursor_offset())
1776                } else {
1777                    s.previous_boundary(sel.cursor_offset())
1778                }
1779            },
1780            cx,
1781        );
1782    }
1783
1784    pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1785        let mirrored = self.arrows_mirrored(cx);
1786        self.select_all_cursors_to(
1787            move |s, sel| {
1788                if mirrored {
1789                    s.previous_boundary(sel.cursor_offset())
1790                } else {
1791                    s.next_boundary(sel.cursor_offset())
1792                }
1793            },
1794            cx,
1795        );
1796    }
1797
1798    pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1799        if self.is_single_line() {
1800            return;
1801        }
1802        self.select_all_cursors_to_with_affinity(
1803            |s, sel| {
1804                s.vertical_selection_target(
1805                    sel.cursor_offset(),
1806                    sel.column_anchor,
1807                    s.line_end_affinity_for(sel),
1808                    -1,
1809                )
1810            },
1811            true,
1812            cx,
1813        );
1814    }
1815
1816    pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1817        if self.is_single_line() {
1818            return;
1819        }
1820        self.select_all_cursors_to_with_affinity(
1821            |s, sel| {
1822                s.vertical_selection_target(
1823                    sel.cursor_offset(),
1824                    sel.column_anchor,
1825                    s.line_end_affinity_for(sel),
1826                    1,
1827                )
1828            },
1829            true,
1830            cx,
1831        );
1832    }
1833
1834    pub(super) fn on_action_select_all(
1835        &mut self,
1836        _: &SelectAll,
1837        window: &mut Window,
1838        cx: &mut Context<Self>,
1839    ) {
1840        self.select_all(window, cx);
1841    }
1842
1843    pub(super) fn select_to_start(
1844        &mut self,
1845        _: &SelectToStart,
1846        _: &mut Window,
1847        cx: &mut Context<Self>,
1848    ) {
1849        self.undo_manager.break_transaction_coalescing();
1850        self.select_all_cursors_to(|_, _| 0, cx);
1851    }
1852
1853    pub(super) fn select_to_end(
1854        &mut self,
1855        _: &SelectToEnd,
1856        _: &mut Window,
1857        cx: &mut Context<Self>,
1858    ) {
1859        self.undo_manager.break_transaction_coalescing();
1860        let end = self.text.len();
1861        self.select_all_cursors_to(move |_, _| end, cx);
1862    }
1863
1864    pub(super) fn select_to_start_of_line(
1865        &mut self,
1866        _: &SelectToStartOfLine,
1867        _: &mut Window,
1868        cx: &mut Context<Self>,
1869    ) {
1870        self.undo_manager.break_transaction_coalescing();
1871        self.select_all_cursors_to(
1872            |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1873            cx,
1874        );
1875    }
1876
1877    pub(super) fn select_to_end_of_line(
1878        &mut self,
1879        _: &SelectToEndOfLine,
1880        _: &mut Window,
1881        cx: &mut Context<Self>,
1882    ) {
1883        self.undo_manager.break_transaction_coalescing();
1884        self.select_all_cursors_to_with_affinity(
1885            |s, sel| {
1886                (
1887                    s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1888                    true,
1889                )
1890            },
1891            false,
1892            cx,
1893        );
1894    }
1895
1896    pub(super) fn select_to_previous_word(
1897        &mut self,
1898        _: &SelectToPreviousWordStart,
1899        _: &mut Window,
1900        cx: &mut Context<Self>,
1901    ) {
1902        self.undo_manager.break_transaction_coalescing();
1903        let mirrored = self.arrows_mirrored(cx);
1904        self.select_all_cursors_to(
1905            move |s, sel| {
1906                if mirrored {
1907                    s.next_end_of_word_at(sel.cursor_offset())
1908                } else {
1909                    s.previous_start_of_word_at(sel.cursor_offset())
1910                }
1911            },
1912            cx,
1913        );
1914    }
1915
1916    pub(super) fn select_to_next_word(
1917        &mut self,
1918        _: &SelectToNextWordEnd,
1919        _: &mut Window,
1920        cx: &mut Context<Self>,
1921    ) {
1922        self.undo_manager.break_transaction_coalescing();
1923        let mirrored = self.arrows_mirrored(cx);
1924        self.select_all_cursors_to(
1925            move |s, sel| {
1926                if mirrored {
1927                    s.previous_start_of_word_at(sel.cursor_offset())
1928                } else {
1929                    s.next_end_of_word_at(sel.cursor_offset())
1930                }
1931            },
1932            cx,
1933        );
1934    }
1935
1936    /// Return the start offset of the previous word.
1937    /// Return the previous start offset of the word before `offset`.
1938    pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1939        if self.masked {
1940            // The mask replaces every character, so the displayed text has no
1941            // word boundaries to move or delete by. Collapse the word to the
1942            // whole text.
1943            return 0;
1944        }
1945
1946        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1947        // FIXME: Avoid to_string
1948        let left_part = self.text.slice(0..offset).to_string();
1949
1950        let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1951            .rfind(|(_, s)| !s.trim_start().is_empty())
1952            .map(|(i, _)| i)
1953            .unwrap_or(0);
1954        self.token_boundary(target, Bias::Left)
1955    }
1956
1957    /// Return the next end offset of the word after `offset`.
1958    pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1959        if self.masked {
1960            // See `previous_start_of_word_at`.
1961            return self.text.len();
1962        }
1963
1964        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1965        let right_part = self.text.slice(offset..self.text.len()).to_string();
1966
1967        let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1968            .find(|(_, s)| !s.trim_start().is_empty())
1969            .map(|(i, s)| offset + i + s.len())
1970            .unwrap_or(self.text.len());
1971        self.token_boundary(target, Bias::Right)
1972    }
1973
1974    /// Get start of line byte offset for the given `offset`.
1975    ///
1976    /// When soft wrap is active, first press goes to visual line start,
1977    /// second press (already at visual start) goes to logical line start.
1978    pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1979        if self.is_single_line() {
1980            return 0;
1981        }
1982
1983        let row = self.text.offset_to_point(offset).row;
1984        let logical_start = self.text.line_start_offset(row);
1985
1986        if self.soft_wrap && self.is_code_editor() {
1987            let wrap_point = self
1988                .display_map
1989                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1990            if let Some(line) = self.display_map.line(row)
1991                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1992            {
1993                let visual_start = logical_start + range.start;
1994                if offset != visual_start {
1995                    return visual_start;
1996                }
1997            }
1998        }
1999
2000        logical_start
2001    }
2002
2003    /// Get end of line byte offset for the given `offset`.
2004    ///
2005    /// When soft wrap is active, first press goes to visual line end,
2006    /// second press (already at visual end) goes to logical line end.
2007    pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2008        if self.is_single_line() {
2009            return self.text.len();
2010        }
2011
2012        let row = self.text.offset_to_point(offset).row;
2013        let logical_start = self.text.line_start_offset(row);
2014        let logical_end = self.text.line_end_offset(row);
2015
2016        if self.soft_wrap && self.is_code_editor() {
2017            // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
2018            // the next row, and a second End press would keep walking down instead of falling
2019            // through to the logical line end.
2020            let wrap_point = self
2021                .display_map
2022                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2023            if let Some(line) = self.display_map.line(row)
2024                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2025            {
2026                let visual_end = logical_start + range.end;
2027                if offset != visual_end {
2028                    return visual_end;
2029                }
2030            }
2031        }
2032
2033        logical_end
2034    }
2035
2036    /// Get indent string of next line.
2037    ///
2038    /// To get current and next line indent, to return more depth one.
2039    pub(super) fn indent_of_next_line(&mut self) -> String {
2040        self.indent_of_next_line_at(self.cursor())
2041    }
2042
2043    /// Get indent string of the next line, relative to the given `offset`.
2044    pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
2045        if self.is_single_line() {
2046            return "".into();
2047        }
2048
2049        let mut current_indent = String::new();
2050        let mut next_indent = String::new();
2051        let line_end_affinity = self.line_end_affinity_at(offset);
2052        let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
2053        let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
2054        for c in self.text.slice(current_line_start_pos..).chars() {
2055            if !c.is_whitespace() {
2056                break;
2057            }
2058            if c == '\n' || c == '\r' {
2059                break;
2060            }
2061            current_indent.push(c);
2062        }
2063
2064        for c in self.text.slice(next_line_start_pos..).chars() {
2065            if !c.is_whitespace() {
2066                break;
2067            }
2068            if c == '\n' || c == '\r' {
2069                break;
2070            }
2071            next_indent.push(c);
2072        }
2073
2074        if next_indent.len() > current_indent.len() {
2075            return next_indent;
2076        }
2077
2078        // Smart indent: one extra level after lines ending with a trigger.
2079        // Skipped inside strings and comments: the trigger is literal text.
2080        if let Some(rules) = self.mode.language_config() {
2081            if self.mode.is_smart_indent()
2082                && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
2083            {
2084                let line_before: String = self
2085                    .text
2086                    .slice(current_line_start_pos..offset)
2087                    .chars()
2088                    .collect();
2089                if rules.opens_indent(line_before.trim_end()) {
2090                    let tab = self.mode.tab_size();
2091                    if tab.hard_tabs {
2092                        current_indent.push('\t');
2093                    } else {
2094                        for _ in 0..tab.tab_size {
2095                            current_indent.push(' ');
2096                        }
2097                    }
2098                } else {
2099                    let line_after = self.text.slice(offset..next_line_start_pos).to_string();
2100                    if rules.closes_indent(&line_after) {
2101                        let tab = self.mode.tab_size();
2102                        if current_indent.ends_with('\t') {
2103                            current_indent.pop();
2104                        } else {
2105                            for _ in 0..tab.tab_size {
2106                                if !current_indent.ends_with(' ') {
2107                                    break;
2108                                }
2109                                current_indent.pop();
2110                            }
2111                        }
2112                    }
2113                }
2114            }
2115        }
2116
2117        current_indent
2118    }
2119
2120    /// Delete every selection as one batch. Collapsed cursors are first
2121    /// expanded to a deletion range by `collapsed_target` and non-empty
2122    /// selections delete their own range.
2123    ///
2124    /// `collapsed_intent` is the intent to record when every cursor is
2125    /// collapsed, which is what makes a run of single-character deletes undo
2126    /// as one gesture. Deleting a real selection is always atomic.
2127    fn delete_selections(
2128        &mut self,
2129        silent: bool,
2130        collapsed_intent: EditIntent,
2131        mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
2132        window: &mut Window,
2133        cx: &mut Context<Self>,
2134    ) {
2135        if !self.is_editable() {
2136            return;
2137        }
2138        let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
2139        let intent = if cursors.iter().all(|sel| sel.is_empty()) {
2140            collapsed_intent
2141        } else {
2142            EditIntent::Atomic
2143        };
2144        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
2145        for sel in &cursors {
2146            let range = if sel.is_empty() {
2147                collapsed_target(self, sel.cursor_offset())
2148            } else {
2149                sel.start..sel.end
2150            };
2151            let (start, end) = (range.start.min(range.end), range.start.max(range.end));
2152            let mut selection = *sel;
2153            selection.start = start;
2154            selection.end = end;
2155            new_selections.push(selection);
2156        }
2157        // Capture the user's selections before expanding or merging deletion
2158        // ranges. The edit ranges cannot reconstruct their original carets.
2159        self.undo_manager.begin_transaction_with(intent);
2160        self.undo_manager
2161            .record_selections(cursors.clone(), cursors.clone());
2162        self.selections.replace_all(new_selections);
2163        self.undo_manager.set_pending_intent(intent);
2164
2165        let was_silent = self.silent_replace_text;
2166        self.silent_replace_text = silent;
2167        self.replace_text_in_range(None, "", window, cx);
2168        self.silent_replace_text = was_silent;
2169        self.undo_manager
2170            .record_selections(cursors, self.selections.iter().copied().collect());
2171        self.undo_manager.commit_transaction();
2172        self.pause_blink_cursor(cx);
2173    }
2174
2175    /// Decide pairing against the pre-edit text, before an opening quote can
2176    /// change its own syntax context. Ordinary characters never query syntax.
2177    fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
2178        if self.silent_replace_text
2179            || self.ime_marked_range.is_some()
2180            || !self.selections.is_single()
2181            || !self.active_selection().is_empty()
2182            || !range.is_empty()
2183            || range.start != self.cursor()
2184            || text.chars().count() != 1
2185            || !self.mode.is_auto_close()
2186        {
2187            return None;
2188        }
2189        let rules = self.mode.language_config()?;
2190        if self
2191            .text
2192            .chars_at(range.start)
2193            .next()
2194            .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
2195        {
2196            return None;
2197        }
2198        for (open, close, not_in) in rules.closing_pairs() {
2199            let Some(prefix) = open.strip_suffix(text) else {
2200                continue;
2201            };
2202            if !self.text_before_matches(range.start, prefix) {
2203                continue;
2204            }
2205            let start = range.start - prefix.len();
2206            if open == close
2207                && (self.is_escaped_at(start)
2208                    || self
2209                        .text
2210                        .chars_at(start)
2211                        .reversed()
2212                        .next()
2213                        .is_some_and(|c| c.is_alphanumeric() || c == '_'))
2214            {
2215                continue;
2216            }
2217            if not_in.contains(&M::editing_syntax_context(self, start)) {
2218                continue;
2219            }
2220            return Some((open.len(), close.into()));
2221        }
2222        None
2223    }
2224
2225    fn text_before_matches(&self, offset: usize, text: &str) -> bool {
2226        offset >= text.len()
2227            && self.text.is_char_boundary(offset - text.len())
2228            && self.text.slice(offset - text.len()..offset) == text
2229    }
2230
2231    fn text_after_matches(&self, offset: usize, text: &str) -> bool {
2232        offset + text.len() <= self.text.len()
2233            && self.text.is_char_boundary(offset + text.len())
2234            && self.text.slice(offset..offset + text.len()) == text
2235    }
2236
2237    fn is_escaped_at(&self, offset: usize) -> bool {
2238        self.text
2239            .chars_at(offset)
2240            .reversed()
2241            .take_while(|c| *c == '\\')
2242            .count()
2243            % 2
2244            == 1
2245    }
2246
2247    /// Cursor target when a typed closer should skip over an existing one.
2248    ///
2249    /// Returns `Some(offset)` when `new_text` is a single closer from the
2250    /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
2251    /// not escaped. The caller then moves the cursor without editing text or
2252    /// history. `None` means insert normally.
2253    fn skip_over_target(&self, new_text: &str) -> Option<usize> {
2254        if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
2255            return None;
2256        }
2257        let rules = self.mode.language_config()?;
2258        let cursor = self.cursor();
2259        for (open, close, not_in) in rules.closing_pairs() {
2260            for (index, _) in close.char_indices() {
2261                if !close[index..].starts_with(new_text)
2262                    || !self.text_before_matches(cursor, &close[..index])
2263                    || !self.text_after_matches(cursor, &close[index..])
2264                {
2265                    continue;
2266                }
2267                let context = M::editing_syntax_context(self, cursor);
2268                let generated =
2269                    self.mode
2270                        .auto_closed_pairs()
2271                        .contains_closer(cursor, index, close.len());
2272                if !generated
2273                    && not_in.contains(&context)
2274                    && !(context == crate::input::SyntaxContext::String && open == close)
2275                {
2276                    continue;
2277                }
2278                if self.is_escaped_at(cursor - index) {
2279                    continue;
2280                }
2281                return Some(cursor + new_text.len());
2282            }
2283        }
2284        None
2285    }
2286
2287    pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
2288        // Nothing to delete at the start of the text. Propagate so an ancestor
2289        // (e.g. a command palette navigating back a level) can act on it.
2290        // This is harmless when nothing upstream is bound to backspace. With multiple
2291        // cursors the others can still delete, so only the lone-cursor case
2292        // propagates.
2293        if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
2294            cx.propagate();
2295            return;
2296        }
2297
2298        // Pair deletion follows automatic closing rules, independently of
2299        // structural brackets used by Enter.
2300        if self.mode.is_auto_close()
2301            && self.selections.is_single()
2302            && self.active_selection().is_empty()
2303        {
2304            let off = self.cursor();
2305            let deletion = self.mode.language_config().and_then(|rules| {
2306                rules.closing_pairs().find_map(|(open, close, not_in)| {
2307                    if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
2308                    {
2309                        return None;
2310                    }
2311                    let start = off - open.len();
2312                    let generated = self
2313                        .mode
2314                        .auto_closed_pairs()
2315                        .contains(start..off, off..off + close.len());
2316                    if self.is_escaped_at(start)
2317                        || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
2318                    {
2319                        return None;
2320                    }
2321                    Some(start..off + close.len())
2322                })
2323            });
2324            if let Some(range) = deletion {
2325                let utf16 = self.range_to_utf16(&range);
2326                self.replace_text_in_range_silent(Some(utf16), "", window, cx);
2327                return;
2328            }
2329        }
2330
2331        self.delete_selections(
2332            false,
2333            EditIntent::Backspace,
2334            |s, offset| s.previous_boundary(offset)..offset,
2335            window,
2336            cx,
2337        );
2338    }
2339
2340    pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2341        self.delete_selections(
2342            false,
2343            EditIntent::DeleteForward,
2344            |s, offset| offset..s.next_boundary(offset),
2345            window,
2346            cx,
2347        );
2348    }
2349
2350    pub(super) fn delete_to_beginning_of_line(
2351        &mut self,
2352        _: &DeleteToBeginningOfLine,
2353        window: &mut Window,
2354        cx: &mut Context<Self>,
2355    ) {
2356        self.delete_selections(
2357            true,
2358            EditIntent::Atomic,
2359            |s, offset| {
2360                let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
2361                if start == offset {
2362                    start = start.saturating_sub(1);
2363                }
2364                start..offset
2365            },
2366            window,
2367            cx,
2368        );
2369    }
2370
2371    pub(super) fn delete_to_end_of_line(
2372        &mut self,
2373        _: &DeleteToEndOfLine,
2374        window: &mut Window,
2375        cx: &mut Context<Self>,
2376    ) {
2377        self.delete_selections(
2378            true,
2379            EditIntent::Atomic,
2380            |s, offset| {
2381                let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
2382                if end == offset {
2383                    end = (end + 1).clamp(0, s.text.len());
2384                }
2385                offset..end
2386            },
2387            window,
2388            cx,
2389        );
2390    }
2391
2392    pub(super) fn delete_previous_word(
2393        &mut self,
2394        _: &DeleteToPreviousWordStart,
2395        window: &mut Window,
2396        cx: &mut Context<Self>,
2397    ) {
2398        self.delete_selections(
2399            true,
2400            EditIntent::Atomic,
2401            |s, offset| s.previous_start_of_word_at(offset)..offset,
2402            window,
2403            cx,
2404        );
2405    }
2406
2407    pub(super) fn delete_next_word(
2408        &mut self,
2409        _: &DeleteToNextWordEnd,
2410        window: &mut Window,
2411        cx: &mut Context<Self>,
2412    ) {
2413        self.delete_selections(
2414            true,
2415            EditIntent::Atomic,
2416            |s, offset| offset..s.next_end_of_word_at(offset),
2417            window,
2418            cx,
2419        );
2420    }
2421
2422    pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
2423        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2424            return;
2425        }
2426
2427        // Clear inline completion on enter (user chose not to accept it)
2428        if M::has_inline_completion(self) {
2429            M::clear_inline_completion(self, cx);
2430        }
2431
2432        // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
2433        // (without Shift) is treated as submit: propagate the action and emit
2434        // PressEnter without inserting a newline. `Shift+Enter` still inserts
2435        // a newline. A secondary `Enter` (Cmd/Ctrl+Enter) is always a submit
2436        // gesture and never inserts a newline.
2437        let insert_newline =
2438            self.is_multi_line() && !action.secondary && (!self.submit_on_enter || action.shift);
2439
2440        if insert_newline {
2441            if !self.selections.is_single() {
2442                // Insert a newline (with per-line indent) at every cursor.
2443                self.selections.merge_overlapping();
2444                let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2445                let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
2446                for sel in &selections {
2447                    let indent = if self.is_code_editor() {
2448                        self.indent_of_next_line_at(sel.cursor_offset())
2449                    } else {
2450                        String::new()
2451                    };
2452                    edits.push((sel.start..sel.end, format!("\n{}", indent)));
2453                }
2454                edits.sort_by_key(|(range, _)| range.start);
2455                self.replace_text_in_ranges(&edits, window, cx);
2456                self.pause_blink_cursor(cx);
2457            } else {
2458                // Bracket split: Enter between `{|}` produces `{\n  \n}`
2459                // with the cursor on the middle line. Controlled by smart_indent,
2460                // independently of automatic closing.
2461                // Skipped inside strings and comments: splitting there would
2462                // restructure literal text.
2463                let mut split = false;
2464                if self.is_code_editor() && self.active_selection().is_empty() {
2465                    if let Some(rules) = self.mode.language_config() {
2466                        if self.mode.is_smart_indent()
2467                            && M::editing_syntax_context(self, self.cursor())
2468                                == crate::input::SyntaxContext::Code
2469                        {
2470                            let off = self.cursor();
2471                            let is_pair = rules.brackets.iter().any(|p| {
2472                                !p.open.is_empty()
2473                                    && !p.close.is_empty()
2474                                    && p.open != p.close
2475                                    && self.text_before_matches(off, p.open.as_ref())
2476                                    && self.text_after_matches(off, p.close.as_ref())
2477                            });
2478                            if is_pair {
2479                                // Base indent: leading whitespace only.
2480                                let line_end_affinity = self.line_end_affinity_at(off);
2481                                let line_start = self.start_of_line_at(off, line_end_affinity);
2482                                let mut indent = String::new();
2483                                for c in self.text.slice(line_start..).chars() {
2484                                    if !c.is_whitespace() || c == '\n' || c == '\r' {
2485                                        break;
2486                                    }
2487                                    indent.push(c);
2488                                }
2489                                // Extra level only with smart indent enabled.
2490                                let mut inner = indent.clone();
2491                                if self.mode.is_smart_indent() {
2492                                    let tab = self.mode.tab_size();
2493                                    if tab.hard_tabs {
2494                                        inner.push('\t');
2495                                    } else {
2496                                        for _ in 0..tab.tab_size {
2497                                            inner.push(' ');
2498                                        }
2499                                    }
2500                                }
2501                                let new_line_text = format!("\n{inner}\n{indent}");
2502                                self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2503                                self.set_cursor_to(off + 1 + inner.len());
2504                                self.update_preferred_column();
2505                                let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2506                                self.undo_manager
2507                                    .record_selections(cursors.clone(), cursors);
2508                                self.pause_blink_cursor(cx);
2509                                split = true;
2510                            }
2511                        }
2512                    }
2513                }
2514                if !split {
2515                    // Get current line indent
2516                    let indent = if self.is_code_editor() {
2517                        self.indent_of_next_line()
2518                    } else {
2519                        "".to_string()
2520                    };
2521
2522                    // Add newline and indent
2523                    let new_line_text = format!("\n{}", indent);
2524                    self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2525                    self.pause_blink_cursor(cx);
2526                }
2527            }
2528        } else {
2529            // Single line input or submit-on-enter: just emit the event
2530            // (e.g.: in a dialog to confirm, or a chat textarea to send).
2531            self.undo_manager.break_transaction_coalescing();
2532            cx.propagate();
2533        }
2534
2535        cx.emit(InputEvent::PressEnter {
2536            secondary: action.secondary,
2537            shift: action.shift,
2538        });
2539    }
2540
2541    pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2542        self.replace_text("", window, cx);
2543        self.set_selection(0, 0);
2544        self.scroll_to(0, None, cx);
2545    }
2546
2547    pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2548        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2549            return;
2550        }
2551
2552        // Escape also dismisses a request whose popup has not arrived yet.
2553        M::hide_context_menu(self, cx);
2554
2555        // Collapse extra cursors back to the active one first.
2556        if !self.selections.is_single() {
2557            self.undo_manager.break_transaction_coalescing();
2558            self.selections.remove_all_but_active();
2559            cx.notify();
2560            return;
2561        }
2562
2563        // Clear inline completion on escape
2564        if M::has_inline_completion(self) {
2565            M::clear_inline_completion(self, cx);
2566            return; // Consume the escape, don't propagate
2567        }
2568        M::clear_inline_completion(self, cx);
2569
2570        // The handles and the edit menu are the topmost surface to dismiss.
2571        if self.touch_selection().is_some() {
2572            self.dismiss_touch_selection(cx);
2573            return;
2574        }
2575
2576        if self.ime_marked_range.is_some() {
2577            self.unmark_text(window, cx);
2578        }
2579
2580        // Android delivers its back button as escape, and back leaves a field's
2581        // text alone: it closes what is open or navigates.
2582        if self.clean_on_escape && !cfg!(target_os = "android") {
2583            return self.clean(window, cx);
2584        }
2585
2586        cx.propagate();
2587    }
2588
2589    /// Show the right-click context menu as a native OS menu.
2590    pub(crate) fn handle_right_click_menu(
2591        &mut self,
2592        position: Point<Pixels>,
2593        offset: usize,
2594        window: &mut Window,
2595        cx: &mut Context<Self>,
2596    ) {
2597        if self.disabled {
2598            return;
2599        }
2600        if crate::GlobalState::is_in_deferred_context(cx) {
2601            return;
2602        }
2603
2604        self.context_menu_offset = Some(offset);
2605        if !self.active_selection().contains(offset) {
2606            self.move_to(offset, None, cx);
2607        }
2608
2609        if self.is_code_editor() {
2610            M::on_hover_definition(self, offset, window, cx);
2611        }
2612
2613        if let Some(handler) = self.context_menu_handler.clone() {
2614            let capabilities = self.context_menu_capabilities();
2615            let input = cx.weak_entity();
2616            // The handler runs with the input released, so a custom builder can
2617            // read it (cursor, selection, text) to build its items.
2618            window.defer(cx, move |window, cx| {
2619                if input.upgrade().is_none() {
2620                    return;
2621                }
2622                let previous_focus = window.focused(cx);
2623                handler(NativeMenu::new(), capabilities, position, window, cx);
2624                // A drawn menu takes focus synchronously; native menus leave it
2625                // on the input. Capture it here rather than in the handler.
2626                input
2627                    .update(cx, |this, cx| {
2628                        if window.focused(cx) == previous_focus
2629                            && !this.focus_handle.is_focused(window)
2630                            && this.has_selection_focus(window, cx)
2631                        {
2632                            // A custom handler can reuse an already-focused popup.
2633                            return;
2634                        }
2635                        let menu_focus = window.focused(cx).filter(|focus| {
2636                            Some(focus) != previous_focus.as_ref() && *focus != this.focus_handle
2637                        });
2638                        this.set_selection_focus(menu_focus, cx);
2639                    })
2640                    .ok();
2641            });
2642        }
2643    }
2644
2645    pub(super) fn add_cursor_above(
2646        &mut self,
2647        _: &AddCursorAbove,
2648        _: &mut Window,
2649        cx: &mut Context<Self>,
2650    ) {
2651        self.add_cursor_vertical(-1, cx);
2652    }
2653
2654    pub(super) fn add_cursor_below(
2655        &mut self,
2656        _: &AddCursorBelow,
2657        _: &mut Window,
2658        cx: &mut Context<Self>,
2659    ) {
2660        self.add_cursor_vertical(1, cx);
2661    }
2662
2663    /// Add a new cursor one display line above (`move_lines < 0`) or below each
2664    /// existing cursor, preserving the column. Cursors that would not move (at
2665    /// the first/last display row) or that would duplicate an existing cursor
2666    /// are skipped.
2667    fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2668        if !self.is_multi_line() {
2669            return;
2670        }
2671
2672        self.pause_blink_cursor(cx);
2673        // Changing the cursor set ends the editing gesture that came before it.
2674        self.undo_manager.break_transaction_coalescing();
2675
2676        let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2677            .selections
2678            .iter()
2679            .map(|sel| {
2680                (
2681                    sel.cursor_offset(),
2682                    sel.column_anchor,
2683                    self.line_end_affinity_for(sel),
2684                )
2685            })
2686            .collect();
2687        let mut offsets: std::collections::HashSet<usize> =
2688            sources.iter().map(|(offset, _, _)| *offset).collect();
2689
2690        let mut newest: Option<usize> = None;
2691        for (offset, anchor, line_end_affinity) in sources {
2692            let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2693            let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2694            if target == offset || offsets.contains(&target) {
2695                continue;
2696            }
2697            offsets.insert(target);
2698            let id = self.selections.generate_id();
2699            let mut cursor = CursorSelection::new(id, target, target);
2700            cursor.column_anchor = anchor;
2701            self.selections.add(cursor);
2702            newest = Some(target);
2703        }
2704
2705        if let Some(newest) = newest {
2706            self.scroll_to(newest, None, cx);
2707        }
2708        cx.notify();
2709    }
2710
2711    /// Add an additional collapsed cursor at `offset`.
2712    ///
2713    /// Rejected when `offset` lands inside an existing selection or exactly on
2714    /// an existing cursor.
2715    pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2716        if !self.is_multi_line() {
2717            return;
2718        }
2719
2720        for sel in self.selections.iter() {
2721            if sel.contains(offset) {
2722                return;
2723            }
2724            if sel.is_collapsed() && sel.cursor_offset() == offset {
2725                return;
2726            }
2727        }
2728
2729        self.undo_manager.break_transaction_coalescing();
2730        let id = self.selections.generate_id();
2731        let mut selection = CursorSelection::new(id, offset, offset);
2732        selection.column_anchor = self.preferred_column_for(offset);
2733        self.selections.add(selection);
2734        cx.notify();
2735    }
2736
2737    /// Build a columnar (block) selection spanning the rows between the two
2738    /// points, one selection per display row at the same column span.
2739    ///
2740    /// The span keeps the columns the pointer sat past the end of a short row, so a row
2741    /// that runs out of text does not narrow the block for the rows that do reach that
2742    /// far. Each row is then clipped to its own end, selecting as much of the span as it
2743    /// actually has.
2744    pub(super) fn build_columnar_selection(
2745        &mut self,
2746        start: ColumnarPoint,
2747        end: ColumnarPoint,
2748        cx: &mut Context<Self>,
2749    ) {
2750        if !self.is_multi_line() {
2751            return;
2752        }
2753
2754        self.undo_manager.break_transaction_coalescing();
2755
2756        let (start_row, start_col) = self.columnar_row_column(start);
2757        let (end_row, end_col) = self.columnar_row_column(end);
2758        let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2759        let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2760
2761        let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2762        for row in start_row..=end_row {
2763            let sel_start = self
2764                .display_map
2765                .display_row_column_to_offset(row, start_col);
2766            let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2767            let id = self.selections.generate_id();
2768            let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2769            let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2770            new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2771        }
2772
2773        self.selections.replace_all(new_selections);
2774        cx.notify();
2775    }
2776
2777    /// Resolve a columnar point to the display row it is on and the column it reaches,
2778    /// counting the columns beyond the row's end so a short row keeps the full span.
2779    fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2780        let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2781        let row = self
2782            .display_map
2783            .wrap_row_to_display_row(display_point.row)
2784            .unwrap_or_else(|| {
2785                self.display_map
2786                    .nearest_visible_display_row(display_point.row)
2787            });
2788
2789        (row, display_point.column + point.columns_past_line_end)
2790    }
2791
2792    pub(super) fn on_mouse_down(
2793        &mut self,
2794        event: &MouseDownEvent,
2795        window: &mut Window,
2796        cx: &mut Context<Self>,
2797    ) {
2798        // A token that consumed the press (a double click selecting it) must
2799        // not also place the caret.
2800        if window.default_prevented() {
2801            return;
2802        }
2803        // A tap asks for the virtual keyboard. Focus alone does not when it
2804        // moves from another input, or stays here, after the user hid it.
2805        if event.button == MouseButton::Left
2806            && crate::GlobalState::is_touch_press(cx)
2807            && !self.disabled
2808            && !self.readonly
2809        {
2810            window.request_virtual_keyboard();
2811        }
2812        self.undo_manager.break_transaction_coalescing();
2813        // Treat every press like a cursor move: take focus now rather than
2814        // after GPUI's focus observer runs, show the caret at once and restart
2815        // the idle delay, whatever phase the blink was in.
2816        if !self.disabled {
2817            self.focus(window, cx);
2818            self.pause_blink_cursor(cx);
2819        }
2820        // Input has its own text selection; suppress the window-level text
2821        // selection (Root) so it does not start a drag from here.
2822        crate::global_state::GlobalState::suppress_text_selection(cx);
2823
2824        // Clear inline completion on any mouse interaction
2825        M::clear_inline_completion(self, cx);
2826        // A tap on the touch selection asks for its menu back. Any other press
2827        // places the caret or starts a new drag, and the handles and the menu
2828        // no longer belong to what is selected.
2829        if event.button == MouseButton::Left
2830            && event.click_count == 1
2831            && self.reopen_edit_menu_at(event.position, cx)
2832        {
2833            return;
2834        }
2835        self.dismiss_touch_selection(cx);
2836
2837        // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2838        // Clear the marked range.
2839        if let Some(ime_marked_range) = &self.ime_marked_range {
2840            if ime_marked_range.len() == 0 {
2841                self.ime_marked_range = None;
2842            }
2843        }
2844
2845        self.selecting = true;
2846        let (offset, line_end_affinity, columns_past_line_end) =
2847            self.resolve_mouse_position(event.position);
2848
2849        if M::on_click(self, event, offset, window, cx) {
2850            return;
2851        }
2852
2853        // Triple click to select line
2854        if event.button == MouseButton::Left && event.click_count >= 3 {
2855            self.select_line(offset, window, cx);
2856            return;
2857        }
2858
2859        // Double click to select word
2860        if event.button == MouseButton::Left && event.click_count == 2 {
2861            self.select_word(offset, window, cx);
2862            // A double tap is touch's other way to select a word, and it
2863            // gets the handles and the menu like a long press does.
2864            if crate::GlobalState::is_touch_press(cx) {
2865                self.keep_touch_selection(cx);
2866            }
2867            return;
2868        }
2869
2870        // Show Mouse context menu
2871        if event.button == MouseButton::Right {
2872            if self.enable_context_menu {
2873                if !self.active_selection().contains(offset) {
2874                    self.move_to(offset, None, cx);
2875                }
2876                self.pending_context_menu = Some((event.position, offset));
2877            }
2878            return;
2879        }
2880
2881        // Multi-cursor placement, multi-line only.
2882        if self.is_multi_line() && event.button == MouseButton::Left {
2883            if event.modifiers.alt
2884                && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2885            {
2886                // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2887                // Mark selecting so the drag handler extends the block.
2888                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2889                self.selecting = true;
2890                self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2891                return;
2892            } else if event.modifiers.alt {
2893                self.add_cursor_at(offset, cx);
2894                // Keep click-to-add behavior, but use this press as the block
2895                // anchor if the user continues dragging with the left button.
2896                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2897                return;
2898            }
2899        }
2900
2901        if event.modifiers.shift {
2902            self.select_to_with_affinity(offset, line_end_affinity, cx);
2903        } else {
2904            self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2905        }
2906    }
2907
2908    pub(super) fn on_mouse_up(
2909        &mut self,
2910        event: &MouseUpEvent,
2911        window: &mut Window,
2912        cx: &mut Context<Self>,
2913    ) {
2914        if event.button == MouseButton::Right {
2915            if let Some((position, offset)) = self.pending_context_menu.take() {
2916                self.handle_right_click_menu(position, offset, window, cx);
2917            }
2918        }
2919        if self.active_selection().is_empty() {
2920            self.active_selection_mut().reversed = false;
2921        }
2922        self.selecting = false;
2923        self.selected_word_range = None;
2924        self.column_select_start = None;
2925        self.auto_scroll.stop();
2926    }
2927
2928    pub(super) fn on_mouse_move(
2929        &mut self,
2930        event: &MouseMoveEvent,
2931        window: &mut Window,
2932        cx: &mut Context<Self>,
2933    ) {
2934        // `last_bounds` is moved by the scroll offset; `input_bounds` is the visible area.
2935        let within_bounds = self.input_bounds.contains(&event.position);
2936
2937        if !within_bounds {
2938            // Clear hover when mouse leaves the input
2939            M::clear_hover_state(self, cx);
2940            return;
2941        }
2942
2943        // Show diagnostic popover on mouse move
2944        let (offset, _) = self.index_for_mouse_position(event.position);
2945        M::on_mouse_move(self, offset, event, window, cx);
2946
2947        if self.is_code_editor() {
2948            // Keep the current popover while the pointer stays on the same
2949            // diagnostic, so moving over a squiggle neither repaints nor
2950            // rebuilds the popover.
2951            match self
2952                .mode
2953                .diagnostics()
2954                .and_then(|set| set.for_offset(offset))
2955            {
2956                Some(diagnostic) => {
2957                    if self.diagnostic_popover.as_deref() != Some(diagnostic) {
2958                        self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
2959                        cx.notify();
2960                    }
2961                }
2962                None => {
2963                    if self.diagnostic_popover.take().is_some() {
2964                        cx.notify();
2965                    }
2966                }
2967            }
2968        }
2969    }
2970
2971    pub(super) fn on_scroll_wheel(
2972        &mut self,
2973        event: &ScrollEvent,
2974        window: &mut Window,
2975        cx: &mut Context<Self>,
2976    ) {
2977        let line_height = self
2978            .last_layout
2979            .as_ref()
2980            .map(|layout| layout.line_height)
2981            .unwrap_or(window.line_height());
2982        let delta = event.delta.pixel_delta(line_height);
2983
2984        let old_offset = self.scroll_handle.offset();
2985        let precise = matches!(event.delta, gpui::ScrollDelta::Pixels(_));
2986        if !precise || !self.scroll_bounce || cx.reduce_motion() || !self.overflows_vertically() {
2987            let displaced = self.overscroll.offset() != 0.;
2988            self.overscroll.reset();
2989            if displaced {
2990                cx.notify();
2991            }
2992        }
2993        let bounces = self.scroll_bounce
2994            && precise
2995            && !cx.reduce_motion()
2996            && delta.y.abs() >= delta.x.abs()
2997            && self.overflows_vertically();
2998        if bounces {
2999            let mut overscroll = std::mem::take(&mut self.overscroll);
3000            let stretched = overscroll.packet(
3001                delta.y.as_f32(),
3002                event.touch_phase,
3003                self.input_bounds.size.height.as_f32(),
3004                cx.background_executor().now(),
3005                |dy| {
3006                    let before = self.scroll_handle.offset();
3007                    self.update_scroll_offset(
3008                        Some(point(before.x + delta.x, before.y + px(dy))),
3009                        cx,
3010                    );
3011                    (self.scroll_handle.offset().y - before.y).as_f32()
3012                },
3013            );
3014            self.overscroll = overscroll;
3015            if stretched {
3016                cx.notify();
3017            }
3018        } else {
3019            self.overscroll
3020                .touch_phase(event.touch_phase, cx.background_executor().now());
3021            // Axis drift must not drop the end of a vertical drag.
3022            if matches!(
3023                event.touch_phase,
3024                gpui::TouchPhase::Ended | gpui::TouchPhase::Cancelled
3025            ) && self.overscroll.offset() != 0.
3026            {
3027                self.overscroll.packet(
3028                    0.,
3029                    event.touch_phase,
3030                    self.input_bounds.size.height.as_f32(),
3031                    cx.background_executor().now(),
3032                    |_| 0.,
3033                );
3034                cx.notify();
3035            }
3036            self.update_scroll_offset(Some(old_offset + delta), cx);
3037        }
3038
3039        // Text that has room to scroll keeps a scroll over it even where the
3040        // text ends, so reaching the end does not scroll the region around the
3041        // input; text that fits leaves the scroll to that region.
3042        if self.scroll_handle.offset() != old_offset || self.overflows_along(delta) {
3043            cx.stop_propagation();
3044        }
3045
3046        if self.diagnostic_popover.take().is_some() {
3047            cx.notify();
3048        }
3049        // The handles follow the text; the menu would sit over whatever
3050        // scrolls underneath it, so it steps aside until the finger lifts.
3051        self.edit_menu_on_scroll(event.touch_phase, cx);
3052    }
3053
3054    /// Whether the text takes a wheel event moving by `delta` from the
3055    /// scroll areas around it: it has room to scroll along the axis the
3056    /// event mostly moves on. Unlike [`Self::overflows_along`], an event that
3057    /// moves on neither axis, such as a gesture's start or end, goes to text
3058    /// that can scroll vertically.
3059    pub(super) fn takes_scroll(&self, delta: Point<Pixels>) -> bool {
3060        if delta.y.abs() >= delta.x.abs() {
3061            self.overflows_vertically()
3062        } else {
3063            self.scroll_size.width > self.input_bounds.size.width
3064        }
3065    }
3066
3067    /// Whether the text has room to scroll along the axis `delta` mostly
3068    /// moves on. A trackpad swipe drifts a little off its axis, so the drift
3069    /// alone does not claim the scroll.
3070    fn overflows_along(&self, delta: Point<Pixels>) -> bool {
3071        if delta.y.abs() >= delta.x.abs() {
3072            delta.y != px(0.) && self.overflows_vertically()
3073        } else {
3074            self.scroll_size.width > self.input_bounds.size.width
3075        }
3076    }
3077
3078    /// Whether multi-line text is taller than the input.
3079    fn overflows_vertically(&self) -> bool {
3080        self.is_multi_line() && self.scroll_size.height > self.input_bounds.size.height
3081    }
3082
3083    pub(super) fn update_scroll_offset(
3084        &mut self,
3085        offset: Option<Point<Pixels>>,
3086        cx: &mut Context<Self>,
3087    ) {
3088        let mut offset = offset.unwrap_or(self.scroll_handle.offset());
3089        let safe_y_range =
3090            (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.);
3091
3092        offset.y = if self.is_single_line() {
3093            px(0.)
3094        } else {
3095            offset.y.clamp(safe_y_range.start, safe_y_range.end)
3096        };
3097        offset.x = clamp_horizontal_scroll_offset(
3098            offset.x,
3099            self.scroll_size.width,
3100            self.input_bounds.size.width,
3101            self.text_align,
3102        );
3103        if self.scroll_handle.offset() != offset {
3104            self.scroll_handle.set_offset(offset);
3105            cx.notify();
3106        }
3107    }
3108
3109    /// Scroll to make the given offset visible.
3110    ///
3111    /// If `direction` is Some, will keep edges at the same side.
3112    pub(crate) fn scroll_to(
3113        &mut self,
3114        offset: usize,
3115        direction: Option<MoveDirection>,
3116        cx: &mut Context<Self>,
3117    ) {
3118        let padding = if direction.is_some() {
3119            ScrollPadding::SurroundingLines
3120        } else {
3121            ScrollPadding::Minimal
3122        };
3123        self.scroll_to_with_padding(offset, direction, padding, cx);
3124    }
3125
3126    /// Reveal an offset with independently chosen direction restriction and padding.
3127    /// Search uses surrounding lines without restricting movement to match order.
3128    pub(crate) fn scroll_to_with_padding(
3129        &mut self,
3130        offset: usize,
3131        direction: Option<MoveDirection>,
3132        padding: ScrollPadding,
3133        cx: &mut Context<Self>,
3134    ) {
3135        let Some(last_layout) = self.last_layout.as_ref() else {
3136            return;
3137        };
3138        let Some(bounds) = self.last_bounds.as_ref() else {
3139            return;
3140        };
3141
3142        let mut scroll_offset = self.scroll_handle.offset();
3143        let was_offset = scroll_offset;
3144        let line_height = last_layout.line_height;
3145
3146        let point = self.text.offset_to_point(offset);
3147
3148        let row = point.row;
3149
3150        // Resolve the wrapped row even when the target is outside the last layout.
3151        let display_row = self
3152            .display_map
3153            .offset_to_display_row(offset, self.line_end_affinity_at(offset));
3154        let row_offset_y = line_height * display_row;
3155
3156        // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
3157        // in layout_cursors, so shifting the text here would cause a first-click visual jump.
3158        let safety_margin = match last_layout.text_align {
3159            TextAlign::Left => RIGHT_MARGIN,
3160            TextAlign::Right => px(0.),
3161            TextAlign::Center => CURSOR_WIDTH,
3162        };
3163        if let Some(vi) = last_layout
3164            .visible_buffer_lines
3165            .iter()
3166            .position(|&line| line == row)
3167        {
3168            let line = &last_layout.lines[vi];
3169            let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
3170            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
3171                let bounds_width = bounds.size.width - last_layout.line_number_width;
3172                let col_offset_x = pos.x;
3173                if col_offset_x - safety_margin < -scroll_offset.x {
3174                    // If the position is out of the visible area, scroll to make it visible
3175                    scroll_offset.x = -col_offset_x + safety_margin;
3176                } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
3177                    scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
3178                }
3179            }
3180        }
3181
3182        // Scroll the row into view. Use the same edge clearance helper as
3183        // `TextElement::layout_cursors` so both scroll-into-view paths agree
3184        // (a mismatch flickered on `Down` at end-of-buffer with a small
3185        // `cursor_surrounding_lines` override).
3186        let edge_height =
3187            if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
3188                super::element::cursor_surrounding_padding(
3189                    self.mode.is_auto_grow(),
3190                    self.cursor_surrounding_lines,
3191                    super::element::viewport_visible_lines(bounds.size.height, line_height),
3192                    line_height,
3193                )
3194            } else {
3195                px(0.)
3196            };
3197        scroll_offset.y = super::element::reveal_row(
3198            scroll_offset.y,
3199            row_offset_y,
3200            line_height,
3201            bounds.size.height,
3202            edge_height,
3203        );
3204
3205        // Avoid necessary scroll, when it was already in the correct position.
3206        if direction == Some(MoveDirection::Up) {
3207            scroll_offset.y = scroll_offset.y.max(was_offset.y);
3208        } else if direction == Some(MoveDirection::Down) {
3209            scroll_offset.y = scroll_offset.y.min(was_offset.y);
3210        }
3211
3212        // Clamp the deferred target into the same safe range that
3213        // `update_scroll_offset` enforces on persist, so paint never shows an
3214        // over-scrolled frame before the post-paint clamp pulls it back.
3215        let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.));
3216        scroll_offset.x = scroll_offset.x.min(px(0.));
3217        scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.));
3218        self.deferred_scroll_offset = Some(scroll_offset);
3219        cx.notify();
3220    }
3221
3222    pub(super) fn show_character_palette(
3223        &mut self,
3224        _: &ShowCharacterPalette,
3225        window: &mut Window,
3226        _: &mut Context<Self>,
3227    ) {
3228        window.show_character_palette();
3229    }
3230
3231    /// The text of every non-empty selection, in document order.
3232    fn selected_texts(&self) -> Vec<String> {
3233        let mut selections: Vec<CursorSelection> = self
3234            .selections
3235            .iter()
3236            .copied()
3237            .filter(|sel| !sel.is_empty())
3238            .collect();
3239        selections.sort_by_key(|sel| sel.start);
3240        selections
3241            .iter()
3242            .map(|sel| self.text.slice(*sel).to_string())
3243            .collect()
3244    }
3245
3246    pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
3247        if self.selections.iter().all(|sel| sel.is_empty()) {
3248            // Nothing selected here: let Root copy the window's text selection.
3249            cx.propagate();
3250            return;
3251        }
3252        if !self.is_copyable() {
3253            return;
3254        }
3255
3256        let texts = self.selected_texts();
3257
3258        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3259    }
3260
3261    pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
3262        if !self.is_copyable() {
3263            return;
3264        }
3265
3266        let texts = self.selected_texts();
3267
3268        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3269
3270        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3271        self.replace_text_in_range_silent(None, "", window, cx);
3272    }
3273
3274    pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
3275        if !self.is_editable() {
3276            return;
3277        }
3278        if let Some(clipboard) = cx.read_from_clipboard() {
3279            self.insert_clipboard(clipboard, window, cx);
3280            return;
3281        }
3282        // The synchronous read is empty on platforms whose clipboard is
3283        // asynchronous and permission-gated (the web), so fall back to the
3284        // real read. It has to start here, still inside the user activation
3285        // that dispatched `Paste`, or the browser refuses the read.
3286        let read = cx.read_from_clipboard_async();
3287        let target = self.paste_target();
3288        cx.spawn_in(window, async move |this, cx| match read.await {
3289            Ok(Some(clipboard)) => {
3290                this.update_in(cx, |this, window, cx| {
3291                    // The read can sit behind a permission prompt for as
3292                    // long as the user likes. If they edited, moved the
3293                    // caret or left the input meanwhile, the paste would
3294                    // land where they no longer mean it to; drop it, as the
3295                    // browser's own paste event only reaches the focused
3296                    // input too.
3297                    if this.is_editable()
3298                        && this.focus_handle.is_focused(window)
3299                        && this.paste_target() == target
3300                    {
3301                        this.insert_clipboard(clipboard, window, cx);
3302                    }
3303                })
3304                .ok();
3305            }
3306            Ok(None) => {}
3307            Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
3308        })
3309        .detach();
3310    }
3311
3312    /// Where a paste would go right now: the document as edited so far and
3313    /// the selections it would replace. Two equal targets mean an edit made
3314    /// for one still applies to the other.
3315    fn paste_target(&self) -> PasteTarget {
3316        PasteTarget {
3317            document_revision: self.document_revision,
3318            selections: self.selections.iter().copied().collect(),
3319        }
3320    }
3321
3322    /// Inserts the clipboard text the way `Paste` does: one atomic edit,
3323    /// newlines dropped on a single-line input, one line per selection when
3324    /// the counts match on a multi-line one. A clipboard without text (an
3325    /// image, say) is left alone rather than replacing the selection with
3326    /// nothing.
3327    fn insert_clipboard(
3328        &mut self,
3329        clipboard: ClipboardItem,
3330        window: &mut Window,
3331        cx: &mut Context<Self>,
3332    ) {
3333        let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
3334            return;
3335        };
3336        // A paste is one atomic edit, never part of a typing run.
3337        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3338
3339        if !self.is_multi_line() {
3340            new_text = new_text.replace('\n', "");
3341            self.replace_text_in_range_silent(None, &new_text, window, cx);
3342            return;
3343        }
3344
3345        // Distribute one clipboard line per selection when the counts match.
3346        // Otherwise insert the whole clipboard text at each cursor.
3347        if !self.selections.is_single() {
3348            self.selections.merge_overlapping();
3349        }
3350        let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
3351        let count = self.selections.len();
3352        if count > 1 && lines.len() == count {
3353            let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3354            selections.sort_by_key(|sel| sel.start);
3355            let edits: Vec<(Range<usize>, String)> = selections
3356                .iter()
3357                .zip(lines)
3358                .map(|(sel, line)| (sel.start..sel.end, line))
3359                .collect();
3360            self.replace_text_in_ranges(&edits, window, cx);
3361        } else {
3362            self.replace_text_in_range_silent(None, &new_text, window, cx);
3363        }
3364        self.scroll_to(self.cursor(), None, cx);
3365    }
3366
3367    /// The intent of a batch the caller did not label: inserting text at
3368    /// collapsed cursors is typing, anything else stands on its own.
3369    fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
3370        if !new_text.is_empty()
3371            && !new_text.contains(['\n', '\r'])
3372            && edits.iter().all(|(range, _)| range.is_empty())
3373        {
3374            EditIntent::Typing
3375        } else {
3376            EditIntent::Atomic
3377        }
3378    }
3379
3380    /// Where a cursor stood before an edit made with this intent.
3381    ///
3382    /// Backspace and forward delete expand a collapsed cursor over the text
3383    /// they are about to remove, so the recorded cursor has to collapse back to
3384    /// the side it came from for undo to restore it where the user left it.
3385    fn collapse_for_intent(
3386        intent: EditIntent,
3387        mut selection: CursorSelection,
3388        range: &Range<usize>,
3389    ) -> CursorSelection {
3390        match intent {
3391            EditIntent::Backspace => selection.place_at(range.end, None),
3392            EditIntent::DeleteForward => selection.place_at(range.start, None),
3393            EditIntent::Typing | EditIntent::Atomic => {}
3394        }
3395        selection
3396    }
3397
3398    /// Whether an edit rewrites the character before a collapsed cursor, as the
3399    /// macOS Korean IME does on each keystroke instead of marking text.
3400    fn rewrites_typed_char(
3401        &self,
3402        selection: CursorSelection,
3403        range: &Range<usize>,
3404        old_text: &str,
3405        new_text: &str,
3406    ) -> bool {
3407        !self.silent_replace_text
3408            && selection.is_collapsed()
3409            && selection.cursor_offset() == range.end
3410            && old_text.chars().count() == 1
3411            && !old_text.contains(['\n', '\r'])
3412            && !new_text.contains(['\n', '\r'])
3413    }
3414
3415    fn push_history(
3416        &mut self,
3417        text: &Rope,
3418        range: &Range<usize>,
3419        new_text: &str,
3420        requested_intent: Option<EditIntent>,
3421        selection_before: CursorSelection,
3422        selection_after: Option<CursorSelection>,
3423    ) -> bool {
3424        self.document_revision = self.document_revision.wrapping_add(1);
3425        let token_delta = self.edit_tokens(range, new_text.len());
3426        if self.undo_manager.is_ignoring() {
3427            return false;
3428        }
3429
3430        let range =
3431            text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
3432        let old_text = text.slice(range.clone()).to_string();
3433        let new_range = range.start..range.start + new_text.len();
3434
3435        let intent = requested_intent.unwrap_or_else(|| {
3436            if range.is_empty()
3437                && old_text.is_empty()
3438                && !new_text.is_empty()
3439                && !new_text.contains(['\n', '\r'])
3440                || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
3441            {
3442                EditIntent::Typing
3443            } else {
3444                EditIntent::Atomic
3445            }
3446        });
3447
3448        let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
3449        let selection_after =
3450            selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
3451
3452        let open_transaction = self.undo_manager.has_open_transaction();
3453        let mut change = Change::new(range, &old_text, new_range, new_text);
3454        change.token_delta = token_delta;
3455        let recorded = self.undo_manager.record_transaction(change, intent);
3456        // A batch records its own cursor sets. This covers a change that is a
3457        // transaction on its own.
3458        if recorded && !open_transaction {
3459            self.undo_manager
3460                .record_selections(vec![selection_before], vec![selection_after]);
3461        }
3462        recorded
3463    }
3464
3465    pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
3466        self.replay_history(true, window, cx);
3467    }
3468
3469    pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
3470        self.replay_history(false, window, cx);
3471    }
3472
3473    fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
3474        if !self.is_editable() {
3475            return;
3476        }
3477        let replay = if undo {
3478            self.undo_manager.undo()
3479        } else {
3480            self.undo_manager.redo()
3481        };
3482        let Some(replay) = replay else {
3483            return;
3484        };
3485        let token_aware = self.inline_tokens.is_some()
3486            || replay
3487                .changes
3488                .iter()
3489                .any(|change| change.token_delta.is_some());
3490        let emit_events = self.emit_events;
3491        if token_aware {
3492            self.emit_events = false;
3493            self.last_input_edits.clear();
3494        }
3495        self.replaying_history = token_aware;
3496        self.undo_manager.set_ignoring(true);
3497        for change in &replay.changes {
3498            let (range, text) = if undo {
3499                (change.new_range.into(), &change.old_text)
3500            } else {
3501                (change.old_range.into(), &change.new_text)
3502            };
3503            let range_utf16 = self.range_to_utf16(&range);
3504            self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
3505            self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
3506        }
3507        self.restore_selections(replay.selections);
3508        self.mode
3509            .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
3510        if token_aware {
3511            // Token replay bypasses IME normalization; a stale marked range
3512            // would otherwise describe text that no longer exists.
3513            self.ime_marked_range = None;
3514        }
3515        self.undo_manager.set_ignoring(false);
3516        self.replaying_history = false;
3517        self.emit_events = emit_events;
3518        if token_aware {
3519            if emit_events {
3520                self.emit_change(cx);
3521            } else {
3522                self.last_input_edits.clear();
3523            }
3524        }
3525        cx.notify();
3526    }
3527
3528    /// Restore a set of selections captured in a transaction, clamping offsets
3529    /// to the current text length and out of tokens. `None` leaves the current
3530    /// selections as the replay left them.
3531    fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
3532        let Some(selections) = selections else {
3533            return;
3534        };
3535
3536        let len = self.text.len();
3537        let restored: Vec<CursorSelection> = selections
3538            .into_iter()
3539            .map(|mut sel| {
3540                let (start, end) = (sel.start.min(len), sel.end.min(len));
3541                let start_bias = if start == end {
3542                    Bias::Right
3543                } else {
3544                    Bias::Left
3545                };
3546                sel.start = self.token_boundary(start, start_bias);
3547                sel.end = self.token_boundary(end, Bias::Right);
3548                sel
3549            })
3550            .collect();
3551        self.selections.replace_all(restored);
3552        self.selections.merge_overlapping();
3553    }
3554
3555    /// Get byte offset of the text under the pointer at the right-click that last opened
3556    /// the context menu.
3557    ///
3558    /// A right-click inside the selection keeps the selection and the cursor, so a custom
3559    /// context menu reads this to find the word under the pointer. The offset is the
3560    /// UTF-8 offset.
3561    pub fn context_menu_offset(&self) -> Option<usize> {
3562        self.context_menu_offset
3563    }
3564
3565    /// Get byte offset of the cursor.
3566    ///
3567    /// The offset is the UTF-8 offset.
3568    pub fn cursor(&self) -> usize {
3569        if let Some(ime_marked_range) = &self.ime_marked_range {
3570            return ime_marked_range.end;
3571        }
3572
3573        self.selections.active().cursor_offset()
3574    }
3575
3576    /// Returns the active selection.
3577    pub(super) fn active_selection(&self) -> &CursorSelection {
3578        self.selections.active()
3579    }
3580
3581    /// Returns a mutable reference to the active selection.
3582    pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
3583        self.selections.active_mut()
3584    }
3585
3586    /// Sets the active selection to the given range, keeping its `reversed`
3587    /// and `column_anchor` state untouched.
3588    pub(super) fn set_selection(&mut self, start: usize, end: usize) {
3589        let range = self.normalize_token_range(start..end);
3590        let (start, end) = (range.start, range.end);
3591        let active = self.active_selection_mut();
3592        active.start = start;
3593        active.end = end;
3594    }
3595
3596    /// Collapses the active selection to a cursor at the given offset,
3597    /// clearing `reversed`.
3598    pub(super) fn set_cursor_to(&mut self, offset: usize) {
3599        let offset = self.token_boundary(offset, Bias::Right);
3600        let active = self.active_selection_mut();
3601        active.start = offset;
3602        active.end = offset;
3603        active.reversed = false;
3604    }
3605
3606    /// Visible row range in the last laid-out viewport, `None` before first layout.
3607    pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3608        self.last_layout.as_ref().map(|l| l.visible_range.clone())
3609    }
3610
3611    /// Current scroll offset of the editor viewport.
3612    pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
3613        self.scroll_handle.offset()
3614    }
3615
3616    /// Set scroll offset of the editor viewport.
3617    ///
3618    /// The offset will be clamped to the valid range, and applied after the next layout.
3619    pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
3620        self.deferred_scroll_offset = Some(offset);
3621        cx.notify();
3622    }
3623
3624    /// Laid-out line height; `None` before first layout.
3625    pub fn line_height(&self) -> Option<gpui::Pixels> {
3626        self.last_layout.as_ref().map(|l| l.line_height)
3627    }
3628
3629    /// Returns the active selection as a byte range into the text.
3630    ///
3631    /// With multiple cursors, this reads only the active selection.
3632    ///
3633    /// The range is empty (`start == end`) when no text is selected; in
3634    /// that case the offset equals `cursor()`. Byte offsets are measured
3635    /// in the underlying rope's byte units.
3636    pub fn selected_range(&self) -> std::ops::Range<usize> {
3637        (*self.selections.active()).into()
3638    }
3639
3640    /// Whether the active selection's caret is at the start of its range.
3641    ///
3642    /// Collapsed selections are not reversed. Use this with [`Self::selected_range`]
3643    /// and [`Self::set_selected_range_with_direction`] to restore a selection.
3644    pub fn is_selection_reversed(&self) -> bool {
3645        let selection = self.selections.active();
3646        !selection.is_empty() && selection.reversed
3647    }
3648
3649    pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3650        self.undo_manager.break_transaction_coalescing();
3651        self.selections.remove_all_but_active();
3652        self.set_selection(0, self.text.len());
3653        cx.notify();
3654    }
3655
3656    /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
3657    ///
3658    /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
3659    /// clipped to the preceding character boundary.
3660    pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3661        self.set_selected_range_with_direction(range, false, cx);
3662    }
3663
3664    /// Set the selected UTF-8 byte range and the active caret direction.
3665    ///
3666    /// With `reversed`, the caret is at the start and the anchor is at the end.
3667    /// Empty ranges collapse to a caret regardless of direction. Range clipping,
3668    /// token boundaries and removal of additional cursors follow
3669    /// [`Self::set_selected_range`].
3670    pub fn set_selected_range_with_direction(
3671        &mut self,
3672        range: Range<usize>,
3673        reversed: bool,
3674        cx: &mut Context<Self>,
3675    ) {
3676        let range = self.normalize_token_range(range);
3677        let end_bias = if range.start == range.end {
3678            Bias::Left
3679        } else {
3680            Bias::Right
3681        };
3682        let start = self.text.clip_offset(range.start, Bias::Left);
3683        let end = self.text.clip_offset(range.end, end_bias);
3684
3685        let (anchor, head) = if reversed { (end, start) } else { (start, end) };
3686        self.move_to(anchor, None, cx);
3687        self.active_selection_mut().reversed = false;
3688        self.selected_word_range = None;
3689        self.select_to(head, cx);
3690    }
3691
3692    /// Add `range` as an additional selection, keeping the existing ones —
3693    /// the programmatic equivalent of Alt-clicking another cursor into the
3694    /// text.
3695    ///
3696    /// The range is clipped to the text and expanded to character
3697    /// boundaries, like [`Self::set_selected_range`]. A range already
3698    /// covered by a selection adds nothing. Overlapping selections are merged.
3699    /// On a single-line input there is no second cursor to add, so the call
3700    /// replaces the selection instead.
3701    /// The view scrolls to the new selection.
3702    pub fn add_selection(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3703        if !self.is_multi_line() {
3704            self.set_selected_range(range, cx);
3705            return;
3706        }
3707
3708        let range = self.normalize_token_range(range);
3709        let end_bias = if range.start == range.end {
3710            Bias::Left
3711        } else {
3712            Bias::Right
3713        };
3714        let start = self.cursor_boundary(range.start, Bias::Left);
3715        // Match set_selected_range: expand UTF-8 boundaries first, then place
3716        // the selection endpoint without splitting a CRLF newline.
3717        let end = self.cursor_boundary(self.text.clip_offset(range.end, end_bias), Bias::Left);
3718
3719        for sel in self.selections.iter() {
3720            if sel.start <= start && end <= sel.end {
3721                return;
3722            }
3723        }
3724
3725        self.undo_manager.break_transaction_coalescing();
3726        self.selected_word_range = None;
3727        self.pause_blink_cursor(cx);
3728        M::hide_context_menu(self, cx);
3729        M::clear_inline_completion(self, cx);
3730        let id = self.selections.generate_id();
3731        let mut selection = CursorSelection::new(id, start, end);
3732        selection.column_anchor = self.preferred_column_for(end);
3733        self.selections.add(selection);
3734        self.selections.merge_overlapping();
3735        self.scroll_to(end, None, cx);
3736        cx.notify();
3737    }
3738
3739    /// Resolve a mouse position to a byte offset in the text.
3740    ///
3741    /// Also reports the caret's line-end affinity for that offset: `true` when the position
3742    /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
3743    /// end of that row rather than at the start of the next one. Callers that place or extend a
3744    /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
3745    /// caret one row below the pointer.
3746    pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3747        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3748        (offset, line_end_affinity)
3749    }
3750
3751    /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
3752    /// how many columns the pointer sits past the end of that row.
3753    ///
3754    /// Only a columnar selection needs the third value; everywhere else a position past
3755    /// the end of a row means the end of that row, and
3756    /// [`Self::index_for_mouse_position`] is the call to make.
3757    pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3758        // If the text is empty, always return 0
3759        if self.text.len() == 0 {
3760            return (0, false, 0);
3761        }
3762
3763        let (Some(bounds), Some(last_layout)) =
3764            (self.last_bounds.as_ref(), self.last_layout.as_ref())
3765        else {
3766            return (0, false, 0);
3767        };
3768
3769        let line_height = last_layout.line_height;
3770        let line_number_width = last_layout.line_number_width;
3771
3772        // TIP: About the IBeam cursor
3773        //
3774        // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3775
3776        // The position is relative to the bounds of the text input
3777        //
3778        // bounds.origin:
3779        //
3780        // - included the input padding.
3781        // - included the scroll offset.
3782        let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3783
3784        let mut y_offset = last_layout.visible_top;
3785        // Position relative to the last line walked, kept for a pointer that ends up
3786        // below every line.
3787        let mut last_line_pos = None;
3788
3789        // Traverse visible buffer lines (compact, no hidden entries)
3790        for (vi, (line_layout, _buffer_line)) in last_layout
3791            .lines
3792            .iter()
3793            .zip(last_layout.visible_buffer_lines.iter())
3794            .enumerate()
3795        {
3796            let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3797
3798            // Calculate line origin for this display row
3799            let line_origin = point(px(0.), y_offset);
3800            let pos = inner_position - line_origin;
3801
3802            // Return offset by use closest_index_for_x if is single line mode.
3803            if self.is_single_line() {
3804                let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3805                // A single line never wraps, so there is no boundary to disambiguate.
3806                return (
3807                    self.resolve_index(line_start_offset + local_index),
3808                    false,
3809                    0,
3810                );
3811            }
3812
3813            // Check if mouse is in this line's bounds
3814            if let Some((local_index, line_end_affinity)) =
3815                line_layout.closest_index_for_position(pos, last_layout)
3816            {
3817                return (
3818                    self.resolve_index(line_start_offset + local_index),
3819                    line_end_affinity,
3820                    line_layout.columns_past_line_end(pos, last_layout),
3821                );
3822            } else if pos.y < px(0.) {
3823                // Mouse is above this line, return start of this line
3824                return (self.resolve_index(line_start_offset), false, 0);
3825            }
3826
3827            y_offset += line_layout.size(line_height).height;
3828            last_line_pos = Some(pos);
3829        }
3830
3831        // Clamp to the last laid-out row. Returning the end of the whole document
3832        // would select unseen text before drag autoscroll has reached it.
3833        let last_position = last_layout
3834            .lines
3835            .last()
3836            .zip(last_line_pos)
3837            .zip(last_layout.visible_line_byte_offsets.last())
3838            .map(|((line_layout, pos), line_start)| {
3839                let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3840                let pos = point(pos.x, last_row_top);
3841                (
3842                    self.resolve_index(line_start + line_layout.len()),
3843                    false,
3844                    line_layout.columns_past_line_end(pos, last_layout),
3845                )
3846            });
3847
3848        last_position.unwrap_or((self.text.len(), false, 0))
3849    }
3850
3851    /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3852    /// is masked.
3853    fn resolve_index(&self, index: usize) -> usize {
3854        if self.masked {
3855            self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3856        } else {
3857            index.min(self.text.len())
3858        }
3859    }
3860
3861    /// Returns a y offsetted point for the line origin.
3862    /// Select the text from the current cursor position to the given offset.
3863    ///
3864    /// The offset is the UTF-8 offset.
3865    ///
3866    /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
3867    /// Extend a single selection so its moving end lands at `offset`, flipping
3868    /// `reversed` when the ends cross. When a sticky `word_range` is given the
3869    /// selection is kept covering it.
3870    fn extend_selection(
3871        sel: &mut CursorSelection,
3872        offset: usize,
3873        word_range: Option<CursorSelection>,
3874    ) {
3875        if sel.reversed {
3876            sel.start = offset;
3877        } else {
3878            sel.end = offset;
3879        }
3880
3881        if sel.end < sel.start {
3882            sel.reversed = !sel.reversed;
3883            std::mem::swap(&mut sel.start, &mut sel.end);
3884        }
3885
3886        if let Some(word_range) = word_range {
3887            if sel.start > word_range.start {
3888                sel.start = word_range.start;
3889            }
3890            if sel.end < word_range.end {
3891                sel.end = word_range.end;
3892            }
3893        }
3894    }
3895
3896    /// Extend only the active selection to `offset`. Used by mouse drag.
3897    pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
3898        self.select_to_with_affinity(offset, false, cx);
3899    }
3900
3901    /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
3902    ///
3903    /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
3904    /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
3905    /// the text rather than from a visual position, so the caret has no reason to keep sticking
3906    /// to the end of a wrapped row.
3907    pub(crate) fn select_to_with_affinity(
3908        &mut self,
3909        offset: usize,
3910        line_end_affinity: bool,
3911        cx: &mut Context<Self>,
3912    ) {
3913        M::clear_inline_completion(self, cx);
3914
3915        self.cursor_line_end_affinity = line_end_affinity;
3916        let offset = self.cursor_boundary(offset, Bias::Left);
3917        let word_range = self.selected_word_range;
3918        Self::extend_selection(self.active_selection_mut(), offset, word_range);
3919        let range = self.normalize_token_range(self.selected_range());
3920        self.set_selection(range.start, range.end);
3921
3922        if self.active_selection().is_empty() {
3923            self.update_preferred_column();
3924        }
3925        cx.notify()
3926    }
3927
3928    /// Extend every selection to the offset produced by `f`, then merge any
3929    /// selections that now overlap. Used by keyboard selection commands.
3930    fn select_all_cursors_to(
3931        &mut self,
3932        f: impl Fn(&Self, &CursorSelection) -> usize,
3933        cx: &mut Context<Self>,
3934    ) {
3935        self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
3936    }
3937
3938    /// Extend selections with caret affinity, preserving their column anchors even
3939    /// when vertical movement collapses a selection to a cursor.
3940    fn select_all_cursors_to_with_affinity(
3941        &mut self,
3942        f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
3943        preserve_column: bool,
3944        cx: &mut Context<Self>,
3945    ) {
3946        self.pause_blink_cursor(cx);
3947        self.undo_manager.break_transaction_coalescing();
3948        M::clear_inline_completion(self, cx);
3949
3950        let mut active_affinity = false;
3951        let new_selections: Vec<CursorSelection> = self
3952            .selections
3953            .iter()
3954            .map(|sel| {
3955                let (offset, affinity) = f(self, sel);
3956                if sel.id == self.active_selection().id {
3957                    active_affinity = affinity;
3958                }
3959                let offset = self.cursor_boundary(offset, Bias::Left);
3960                let mut new_sel = *sel;
3961                Self::extend_selection(&mut new_sel, offset, None);
3962                let range = self.normalize_token_range(new_sel.start..new_sel.end);
3963                new_sel.start = range.start;
3964                new_sel.end = range.end;
3965                if !preserve_column {
3966                    new_sel.column_anchor =
3967                        self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
3968                } else if new_sel.column_anchor.is_none() {
3969                    new_sel.column_anchor = self.preferred_column_for_with_affinity(
3970                        sel.cursor_offset(),
3971                        self.line_end_affinity_for(sel),
3972                    );
3973                }
3974                new_sel
3975            })
3976            .collect();
3977        self.cursor_line_end_affinity = active_affinity;
3978        self.selections.replace_all(new_selections);
3979        self.selections.merge_overlapping();
3980
3981        self.scroll_to(self.cursor(), None, cx);
3982        cx.notify()
3983    }
3984
3985    /// Unselects the currently selected text.
3986    pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3987        self.undo_manager.break_transaction_coalescing();
3988        let offset = self.cursor();
3989        self.set_cursor_to(offset);
3990        cx.notify()
3991    }
3992
3993    #[inline]
3994    pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
3995        self.text.offset_utf16_to_offset(offset)
3996    }
3997
3998    #[inline]
3999    pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
4000        self.text.offset_to_offset_utf16(offset)
4001    }
4002
4003    #[inline]
4004    pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
4005        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
4006    }
4007
4008    #[inline]
4009    pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
4010        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
4011    }
4012
4013    /// If offset falls on a hidden (folded) line, clamp backward to the end of
4014    /// the fold header line (last visible position before the fold).
4015    fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
4016        let line = self.text.offset_to_point(offset).row;
4017        if self.display_map.is_buffer_line_hidden(line) {
4018            for fold in self.display_map.folded_ranges() {
4019                if line > fold.start_line && line <= fold.end_line {
4020                    return self.text.line_end_offset(fold.start_line);
4021                }
4022            }
4023        }
4024        offset
4025    }
4026
4027    /// If offset falls on a hidden (folded) line, clamp forward to the start of
4028    /// the fold end line (first visible position after the fold).
4029    fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
4030        let line = self.text.offset_to_point(offset).row;
4031        if self.display_map.is_buffer_line_hidden(line) {
4032            for fold in self.display_map.folded_ranges() {
4033                if line > fold.start_line && line <= fold.end_line {
4034                    return self.text.line_start_offset(fold.end_line);
4035                }
4036            }
4037        }
4038        offset
4039    }
4040
4041    /// Clip a cursor/selection offset without splitting a CRLF newline. This does
4042    /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
4043    pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
4044        let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
4045        if offset > 0
4046            && self.text.char_at(offset - 1) == Some('\r')
4047            && self.text.char_at(offset) == Some('\n')
4048        {
4049            if bias == Bias::Left {
4050                offset - 1
4051            } else {
4052                offset + 1
4053            }
4054        } else {
4055            offset
4056        }
4057    }
4058
4059    pub(super) fn previous_boundary(&self, offset: usize) -> usize {
4060        let offset =
4061            self.cursor_boundary(previous_grapheme_boundary(&self.text, offset), Bias::Left);
4062        self.clamp_offset_to_visible_backward(offset)
4063    }
4064
4065    pub(super) fn next_boundary(&self, offset: usize) -> usize {
4066        let offset = self.cursor_boundary(next_grapheme_boundary(&self.text, offset), Bias::Right);
4067        self.clamp_offset_to_visible_forward(offset)
4068    }
4069
4070    /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
4071    pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
4072        (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
4073            && !self.disabled
4074            && self.blink_cursor.read(cx).visible()
4075            && window.is_window_active()
4076    }
4077
4078    fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4079        self.blink_cursor.update(cx, |cursor, cx| {
4080            cursor.start(cx);
4081        });
4082        cx.emit(InputEvent::Focus);
4083    }
4084
4085    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4086        self.cancel_mouse_gesture(cx);
4087        self.revealed_viewport = None;
4088        if M::is_context_menu_open(self, cx) {
4089            return;
4090        }
4091
4092        M::hide_context_menu(self, cx);
4093        self.undo_manager.break_transaction_coalescing();
4094
4095        // NOTE: Do not cancel select, when blur.
4096        // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
4097
4098        M::clear_hover_state(self, cx);
4099        self.diagnostic_popover = None;
4100        M::clear_inline_completion(self, cx);
4101        self.dismiss_touch_selection(cx);
4102        self.blink_cursor.update(cx, |cursor, cx| {
4103            cursor.stop(cx);
4104        });
4105        self.clamp_number_value(window, cx);
4106        cx.emit(InputEvent::Blur);
4107        cx.notify();
4108    }
4109
4110    /// Clamp the number value to the `min`/`max` range, used on blur.
4111    ///
4112    /// Out-of-range values are allowed while typing (e.g. `1` is an
4113    /// intermediate state of `15` when min is 10), and clamped on blur.
4114    fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4115        if !self.is_single_line() {
4116            return;
4117        }
4118        if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4119            return;
4120        }
4121        if self.number_min.is_none() && self.number_max.is_none() {
4122            return;
4123        }
4124
4125        let Ok(value) = self.unmask_value().parse::<f64>() else {
4126            return;
4127        };
4128
4129        let clamped = match (self.number_min, self.number_max) {
4130            (Some(min), _) if value < min => min,
4131            (_, Some(max)) if value > max => max,
4132            _ => return,
4133        };
4134
4135        // The clamped value must pass the `pattern`/`validate` check,
4136        // otherwise keep the value as is.
4137        let new_text = clamped.to_string();
4138        if !self.is_valid_input(&new_text, cx) {
4139            return;
4140        }
4141
4142        let range = self.range_to_utf16(&(0..self.text.len()));
4143        self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
4144    }
4145
4146    pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
4147        self.blink_cursor.update(cx, |cursor, cx| {
4148            cursor.pause(cx);
4149        });
4150    }
4151
4152    pub(super) fn cancel_mouse_gesture(&mut self, cx: &mut Context<Self>) {
4153        let was_dragging = self.selecting || self.column_select_start.is_some();
4154        self.selecting = false;
4155        self.column_select_start = None;
4156        self.auto_scroll.stop();
4157        if was_dragging {
4158            cx.notify();
4159        }
4160    }
4161
4162    pub(super) fn on_drag_move(
4163        &mut self,
4164        event: &MouseMoveEvent,
4165        window: &mut Window,
4166        cx: &mut Context<Self>,
4167    ) {
4168        if event.pressed_button != Some(MouseButton::Left) {
4169            self.cancel_mouse_gesture(cx);
4170            return;
4171        }
4172        if self.text.len() == 0 {
4173            return;
4174        }
4175
4176        if self.last_layout.is_none() {
4177            return;
4178        }
4179
4180        if !self.focus_handle.is_focused(window) {
4181            return;
4182        }
4183
4184        if !self.selecting {
4185            return;
4186        }
4187
4188        self.auto_scroll.last_drag_position = Some(event.position);
4189        let (offset, line_end_affinity, columns_past_line_end) =
4190            self.resolve_mouse_position(event.position);
4191        if let Some(start) = self.column_select_start {
4192            let end = ColumnarPoint::new(offset, columns_past_line_end);
4193            self.build_columnar_selection(start, end, cx);
4194        } else {
4195            self.select_to_with_affinity(offset, line_end_affinity, cx);
4196        }
4197
4198        if !self.is_single_line() {
4199            let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
4200            // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
4201            let scroll_delta = delta.map(|d| -d);
4202            self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
4203                let current = state.scroll_handle.offset();
4204                state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
4205                if let Some(pos) = state.auto_scroll.last_drag_position {
4206                    let (offset, line_end_affinity, columns_past_line_end) =
4207                        state.resolve_mouse_position(pos);
4208                    if let Some(start) = state.column_select_start {
4209                        let end = ColumnarPoint::new(offset, columns_past_line_end);
4210                        state.build_columnar_selection(start, end, cx);
4211                    } else {
4212                        state.select_to_with_affinity(offset, line_end_affinity, cx);
4213                    }
4214                }
4215            });
4216        }
4217    }
4218
4219    /// Normalize the inserted text before applying it to the input.
4220    ///
4221    /// For number inputs (with [`MaskPattern::Number`]), this converts
4222    /// full-width number characters into their ASCII equivalents,
4223    /// e.g. `12。5` -> `12.5`.
4224    pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
4225        let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4226            normalize_number_input(new_text)
4227        } else {
4228            Cow::Borrowed(new_text)
4229        };
4230
4231        if self.is_single_line() && normalized.contains(['\n', '\r']) {
4232            Cow::Owned(normalized.replace(['\n', '\r'], ""))
4233        } else {
4234            normalized
4235        }
4236    }
4237
4238    pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
4239        if new_text.is_empty() {
4240            return true;
4241        }
4242
4243        if let Some(validate) = &self.validate {
4244            if !validate(new_text, cx) {
4245                return false;
4246            }
4247        }
4248
4249        if !self.mask_pattern.is_valid(new_text) {
4250            return false;
4251        }
4252
4253        let Some(pattern) = &self.pattern else {
4254            return true;
4255        };
4256
4257        pattern.is_match(new_text)
4258    }
4259
4260    /// Set the mask pattern for formatting the input text.
4261    ///
4262    /// The pattern can contain:
4263    /// - 9: Any digit or dot
4264    /// - A: Any letter
4265    /// - *: Any character
4266    /// - Other characters will be treated as literal mask characters
4267    ///
4268    /// Example: "(999)999-999" for phone numbers
4269    pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
4270        self.mask_pattern = pattern.into();
4271        self.mask_pattern_set = true;
4272        if let Some(placeholder) = self.mask_pattern.placeholder() {
4273            self.placeholder = placeholder.into();
4274        }
4275        self
4276    }
4277
4278    pub fn set_mask_pattern(
4279        &mut self,
4280        pattern: impl Into<MaskPattern>,
4281        _: &mut Window,
4282        cx: &mut Context<Self>,
4283    ) {
4284        self.mask_pattern = pattern.into();
4285        self.mask_pattern_set = true;
4286        if let Some(placeholder) = self.mask_pattern.placeholder() {
4287            self.placeholder = placeholder.into();
4288        }
4289        cx.notify();
4290    }
4291
4292    /// Apply the default numeric mask unless the caller explicitly selected a mask.
4293    pub fn ensure_number_mask(&mut self) {
4294        if self.mask_pattern_set {
4295            return;
4296        }
4297        self.mask_pattern = MaskPattern::Number {
4298            separator: None,
4299            fraction: None,
4300        };
4301    }
4302
4303    pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
4304        let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
4305        self.input_bounds = new_bounds;
4306
4307        // Update display_map wrap_width if changed.
4308        if let Some(last_layout) = self.last_layout.as_ref() {
4309            if wrap_width_changed {
4310                let wrap_width = if !self.soft_wrap {
4311                    // None to disable wrapping (will use Pixels::MAX)
4312                    None
4313                } else {
4314                    last_layout.wrap_width
4315                };
4316
4317                self.display_map.on_layout_changed(wrap_width, cx);
4318                if self.is_multi_line() {
4319                    self.mode.update_auto_grow(&self.display_map);
4320                }
4321                cx.notify();
4322            }
4323        }
4324    }
4325
4326    /// Return the active selection's text, borrowed out of the [`Rope`]
4327    /// the state owns.
4328    ///
4329    /// See [`Self::selected_value`] when an owned string is wanted.
4330    pub fn selected_text(&self) -> RopeSlice<'_> {
4331        let range_utf16 = self.range_to_utf16(&self.selected_range());
4332        let range = self.range_from_utf16(&range_utf16);
4333        self.text.slice(range)
4334    }
4335
4336    /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
4337    ///
4338    /// Returns `None` when the requested range is not currently laid out or visible.
4339    pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
4340        let Some(last_layout) = self.last_layout.as_ref() else {
4341            return None;
4342        };
4343
4344        let Some(last_bounds) = self.last_bounds else {
4345            return None;
4346        };
4347
4348        let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
4349        let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
4350
4351        let Some(start_pos) = start_pos else {
4352            return None;
4353        };
4354        let Some(end_pos) = end_pos else {
4355            return None;
4356        };
4357
4358        Some(Bounds::from_corners(
4359            last_bounds.origin + start_pos,
4360            last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
4361        ))
4362    }
4363
4364    /// Replace text in range in silent.
4365    ///
4366    /// This will not trigger any UI interaction, such as auto-completion.
4367    pub(crate) fn replace_text_in_range_silent(
4368        &mut self,
4369        range_utf16: Option<Range<usize>>,
4370        new_text: &str,
4371        window: &mut Window,
4372        cx: &mut Context<Self>,
4373    ) {
4374        self.silent_replace_text = true;
4375        self.replace_text_in_range(range_utf16, new_text, window, cx);
4376        self.silent_replace_text = false;
4377    }
4378
4379    /// Apply a batch of edits as one atomic history transaction.
4380    ///
4381    /// `edits` are `(byte range in the current pre-edit document, replacement)`
4382    /// pairs.
4383    pub(crate) fn replace_text_in_ranges(
4384        &mut self,
4385        edits: &[(Range<usize>, String)],
4386        window: &mut Window,
4387        cx: &mut Context<Self>,
4388    ) {
4389        if !self.is_editable() || edits.is_empty() {
4390            return;
4391        }
4392
4393        // Every edit invalidates provider responses for the previous document,
4394        // including deletion and indentation which do not trigger completion.
4395        M::hide_context_menu(self, cx);
4396        M::clear_inline_completion(self, cx);
4397
4398        // Sort descending by start so applying front-of-vec first edits the
4399        // highest offsets first, leaving lower offsets unchanged.
4400        let mut sorted: Vec<(Range<usize>, &str)> = edits
4401            .iter()
4402            .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
4403            .collect();
4404        sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
4405        if !self.token_spans().is_empty() {
4406            let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
4407            for (range, text) in sorted {
4408                if let Some(last) = merged
4409                    .last_mut()
4410                    .filter(|last| range.end > last.0.start || range == last.0)
4411                {
4412                    last.0.start = range.start.min(last.0.start);
4413                    last.0.end = range.end.max(last.0.end);
4414                } else {
4415                    merged.push((range, text));
4416                }
4417            }
4418            sorted = merged;
4419        }
4420
4421        #[cfg(debug_assertions)]
4422        for pair in sorted.windows(2) {
4423            debug_assert!(
4424                pair[1].0.end <= pair[0].0.start,
4425                "replace_text_in_ranges requires disjoint ranges"
4426            );
4427        }
4428
4429        // Wrap multiple edits in one explicit transaction so they undo as a
4430        // unit. A single edit records directly, which keeps it eligible for
4431        // the undo manager's typing coalescing.
4432        let requested_intent = self.undo_manager.take_pending_intent();
4433        let selection_before = *self.active_selection();
4434        let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
4435        // Snapshot the cursors before applying, so undo can restore them. A
4436        // delete has already expanded them over the text it removes, so they
4437        // collapse back to where the user left them.
4438        let selections_before: Vec<CursorSelection> = self
4439            .selections
4440            .iter()
4441            .map(|selection| {
4442                Self::collapse_for_intent(
4443                    requested_intent.unwrap_or(EditIntent::Atomic),
4444                    *selection,
4445                    &(selection.start..selection.end),
4446                )
4447            })
4448            .collect();
4449        let group = sorted.len() > 1;
4450        if group {
4451            self.undo_manager.begin_transaction();
4452        }
4453
4454        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4455        let mut recorded = false;
4456        // Several edits reach the highlighter as one batch, so it reparses
4457        // once for the change instead of once per edit.
4458        let mut highlighter_edits = Vec::new();
4459        // Token-aware history replay applies several replacements but emits one
4460        // `Change` at the end, so its edits accumulate instead of being
4461        // discarded with each silent replacement.
4462        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4463        if !accumulate_replay_edits {
4464            self.last_input_edits.clear();
4465        }
4466        for (range, new_text) in &sorted {
4467            let old_text = self.text.clone();
4468            self.mode.adjust_auto_closed_pair(range, new_text.len());
4469            self.text.replace(range.clone(), new_text);
4470
4471            M::adjust_annotations(self, range, new_text.len());
4472            recorded |= self.push_history(
4473                &old_text,
4474                range,
4475                new_text,
4476                requested_intent,
4477                selection_before,
4478                None,
4479            );
4480
4481            // Incremental, single-range updates must run per edit.
4482            self.display_map
4483                .adjust_folds_for_edit(&old_text, range, new_text);
4484            self.display_map
4485                .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
4486
4487            let edit = super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
4488            if self.emit_events || self.replaying_history {
4489                self.last_input_edits.push((edit, self.text.clone()));
4490            }
4491
4492            if group {
4493                if self.is_code_editor() {
4494                    highlighter_edits.push((edit, self.text.clone()));
4495                }
4496            } else {
4497                self.mode.update_highlighter(
4498                    super::mode::HighlighterUpdate {
4499                        selected_range: range,
4500                        old_text: &old_text,
4501                        new_text: &self.text,
4502                        change_text: new_text,
4503                        force: true,
4504                        input_edit: Some(edit),
4505                    },
4506                    window,
4507                    cx,
4508                );
4509
4510                self.update_fold_candidates_incremental(range, new_text);
4511            }
4512        }
4513
4514        if group {
4515            self.mode
4516                .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
4517
4518            // Fold candidates are read from the reparsed document, so each
4519            // edit is located where it ended up once every edit was applied.
4520            // `sorted` runs from the highest offset down.
4521            let mut shift = 0isize;
4522            for (range, new_text) in sorted.iter().rev() {
4523                let start = (range.start as isize + shift) as usize;
4524                self.update_fold_candidates_incremental(&(start..start), new_text);
4525                shift += new_text.len() as isize - range.len() as isize;
4526            }
4527
4528            self.undo_manager.commit_transaction();
4529        }
4530
4531        // One observable update per batch instead of one per edit.
4532        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4533            diagnostics.reset(&self.text)
4534        }
4535        M::refresh_language_features(self, window, cx);
4536        self.update_search(cx);
4537
4538        // Compute the resulting cursors.
4539        // One collapsed cursor per edit, at the end of its inserted text.
4540        let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
4541        ascending.sort_by_key(|edit| edit.0.start);
4542        let text_len = self.text.len();
4543        let mut delta: isize = 0;
4544        let mut edit_results = Vec::with_capacity(ascending.len());
4545        for (range, new_text) in &ascending {
4546            let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
4547            edit_results.push((range.clone(), offset));
4548            delta += new_text.len() as isize - (range.end as isize - range.start as isize);
4549        }
4550
4551        let mut used = vec![false; edit_results.len()];
4552        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
4553        for selection in original_selections {
4554            if let Ok(index) = edit_results
4555                .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
4556                    (range.start, range.end)
4557                })
4558                && !used[index]
4559            {
4560                let offset = edit_results[index].1;
4561                used[index] = true;
4562                let mut selection = selection;
4563                selection.place_at(offset, None);
4564                new_selections.push(selection);
4565            }
4566        }
4567        for (index, (_, offset)) in edit_results.into_iter().enumerate() {
4568            if !used[index] {
4569                new_selections.push(CursorSelection::new(
4570                    self.selections.generate_id(),
4571                    offset,
4572                    offset,
4573                ));
4574            }
4575        }
4576        self.selections.replace_all(new_selections);
4577        self.selections.merge_overlapping();
4578
4579        // Record the cursor snapshots for undo/redo restore.
4580        let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
4581        if recorded {
4582            self.undo_manager.record_auto_closed_pairs(
4583                auto_closed_pairs_before,
4584                self.mode.auto_closed_pairs().clone(),
4585            );
4586            self.undo_manager
4587                .record_selections(selections_before, selections_after);
4588        }
4589
4590        self.ime_marked_range.take();
4591        self.update_preferred_column();
4592        self.dismiss_touch_selection(cx);
4593        if self.is_multi_line() {
4594            self.mode.update_auto_grow(&self.display_map);
4595        }
4596        if self.emit_events {
4597            self.emit_change(cx);
4598        }
4599        cx.notify();
4600    }
4601
4602    /// Update fold candidates from tree-sitter syntax tree (full extraction).
4603    /// Used only on initial load or language changes.
4604    fn update_fold_candidates(&mut self) {
4605        if !self.mode.is_folding() {
4606            return;
4607        }
4608
4609        let Some(highlighter_rc) = self.mode.highlighter() else {
4610            return;
4611        };
4612
4613        let highlighter = highlighter_rc.borrow();
4614        let Some(highlighter) = highlighter.as_ref() else {
4615            return;
4616        };
4617
4618        let fold_ranges = highlighter.fold_ranges(&self.text);
4619        self.display_map.set_fold_candidates(fold_ranges);
4620    }
4621
4622    /// Incrementally update fold candidates after a text edit.
4623    /// Only traverses the edited region of the syntax tree instead of the full tree.
4624    fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
4625        if !self.mode.is_folding() {
4626            return;
4627        }
4628
4629        let Some(highlighter_rc) = self.mode.highlighter() else {
4630            return;
4631        };
4632
4633        let highlighter = highlighter_rc.borrow();
4634        let Some(highlighter) = highlighter.as_ref() else {
4635            return;
4636        };
4637
4638        // The new byte range in the updated text after the edit
4639        let new_end = edit_range.start + new_text.len();
4640        self.display_map.update_fold_candidates_for_edit(
4641            |range, text| highlighter.fold_ranges_for_edit(range, text),
4642            edit_range.start..new_end,
4643            &self.text,
4644        );
4645    }
4646}
4647
4648impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4649    fn text_for_range(
4650        &mut self,
4651        range_utf16: Range<usize>,
4652        adjusted_range: &mut Option<Range<usize>>,
4653        _window: &mut Window,
4654        _cx: &mut Context<Self>,
4655    ) -> Option<String> {
4656        let range = self.range_from_utf16(&range_utf16);
4657        adjusted_range.replace(self.range_to_utf16(&range));
4658        Some(self.text.slice(range).to_string())
4659    }
4660
4661    fn selected_text_range(
4662        &mut self,
4663        _ignore_disabled_input: bool,
4664        _window: &mut Window,
4665        _cx: &mut Context<Self>,
4666    ) -> Option<UTF16Selection> {
4667        Some(UTF16Selection {
4668            range: self.range_to_utf16(&self.selected_range()),
4669            reversed: self.active_selection().reversed,
4670        })
4671    }
4672
4673    /// Select the given range, as the platform's own text UI asks when it
4674    /// drives the selection: a native selection handle, or the macOS IME.
4675    ///
4676    /// The end that moved becomes the cursor, so dragging the start handle
4677    /// leaves a reversed selection and keeps the moving end in view. Text and
4678    /// undo history are left alone.
4679    fn set_selected_text_range(
4680        &mut self,
4681        range_utf16: Range<usize>,
4682        _window: &mut Window,
4683        cx: &mut Context<Self>,
4684    ) {
4685        let previous = self.selected_range();
4686        let was_reversed = self.active_selection().reversed;
4687        let range = self.range_from_utf16(&range_utf16);
4688        let range = range.start.min(range.end)..range.start.max(range.end);
4689        self.set_selected_range(range, cx);
4690
4691        let range = self.selected_range();
4692        let reversed = if range == previous {
4693            was_reversed
4694        } else if !range.is_empty() && range.end == previous.start {
4695            true
4696        } else if !range.is_empty() && range.start == previous.end {
4697            false
4698        } else {
4699            !range.is_empty() && range.start != previous.start && range.end == previous.end
4700        };
4701        self.active_selection_mut().reversed = reversed;
4702        self.scroll_to(self.cursor(), None, cx);
4703        cx.notify();
4704    }
4705
4706    fn marked_text_range(
4707        &self,
4708        _window: &mut Window,
4709        _cx: &mut Context<Self>,
4710    ) -> Option<Range<usize>> {
4711        self.ime_marked_range
4712            .map(|range| self.range_to_utf16(&range.into()))
4713    }
4714
4715    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4716        self.ime_marked_range = None;
4717        self.undo_manager.commit_transaction();
4718        // Unmarking keeps the preedit as committed text, which marked edits
4719        // never reported. Android keyboards compose every word and often end
4720        // with only this call (hiding the keyboard, moving the caret).
4721        if self.ime_original_text.as_ref() == Some(&self.text) {
4722            self.ime_original_text = None;
4723        } else if self.ime_original_text.is_some() && self.emit_events {
4724            self.emit_change(cx);
4725        }
4726    }
4727
4728    /// Replace text in range.
4729    ///
4730    /// - If the new text is invalid, it will not be replaced.
4731    /// - If `range_utf16` is not provided, the current selected range will be used.
4732    fn replace_text_in_range(
4733        &mut self,
4734        range_utf16: Option<Range<usize>>,
4735        new_text: &str,
4736        window: &mut Window,
4737        cx: &mut Context<Self>,
4738    ) {
4739        let requested_intent = self.undo_manager.take_pending_intent();
4740        if !self.is_editable() {
4741            return;
4742        }
4743        let selection_before = *self.active_selection();
4744        // Committing a composition ends the transaction it opened, whether or
4745        // not the platform follows up with `unmark_text`.
4746        let ends_composition = self.ime_marked_range.is_some();
4747
4748        self.pause_blink_cursor(cx);
4749
4750        // NOTE: The normalization keeps the UTF-16 length, but may change the
4751        // UTF-8 byte length, so all the byte-offset calculations below must
4752        // use the normalized text.
4753        let new_text = if self.replaying_history {
4754            Cow::Borrowed(new_text)
4755        } else {
4756            self.normalize_input(new_text)
4757        };
4758        let new_text: &str = &new_text;
4759
4760        let range = range_utf16
4761            .as_ref()
4762            .map(|range_utf16| self.range_from_utf16(range_utf16))
4763            .or(self.ime_marked_range.map(|range| {
4764                let range = self.range_to_utf16(&(range.start..range.end));
4765                self.range_from_utf16(&range)
4766            }))
4767            .unwrap_or(self.selected_range());
4768        let range = self.normalize_token_range(range);
4769
4770        // Skip-over as a pure cursor move: a typed closer that already follows
4771        // the cursor moves past it without touching text or history, so Undo
4772        // never exposes a transient duplicate. Only for interactive single
4773        // keystrokes (current selection, no IME mark, not silent replays).
4774        // `take_pending_intent` above already consumed any request.
4775        if range.is_empty()
4776            && range.start == self.cursor()
4777            && self.ime_marked_range.is_none()
4778            && !self.silent_replace_text
4779            && self.is_code_editor()
4780            && self.selections.is_single()
4781            && self.active_selection().is_empty()
4782        {
4783            if let Some(target) = self.skip_over_target(new_text) {
4784                self.set_cursor_to(target);
4785                self.update_preferred_column();
4786                cx.notify();
4787                return;
4788            }
4789        }
4790
4791        if self.is_multi_line() {
4792            let multi_cursor = range_utf16.is_none()
4793                && self.ime_marked_range.is_none()
4794                && !self.selections.is_single();
4795            if multi_cursor {
4796                self.selections.merge_overlapping();
4797                let mut edits: Vec<(Range<usize>, String)> = self
4798                    .selections
4799                    .iter()
4800                    .map(|sel| (sel.start..sel.end, new_text.to_string()))
4801                    .collect();
4802                edits.sort_by_key(|(range, _)| range.start);
4803                // One keystroke across several cursors is one batch, committed
4804                // with the intent of the keystroke so a run of them coalesces
4805                // into one undo just like single-cursor typing.
4806                let intent =
4807                    requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
4808                self.undo_manager.begin_transaction_with(intent);
4809                self.undo_manager.set_pending_intent(intent);
4810                self.replace_text_in_ranges(&edits, window, cx);
4811                self.undo_manager.commit_transaction();
4812            } else {
4813                if range_utf16.is_some() {
4814                    self.selections.remove_all_but_active();
4815                }
4816                if let Some(intent) = requested_intent {
4817                    self.undo_manager.set_pending_intent(intent);
4818                }
4819                if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
4820                    // One edit keeps the pair atomic even at undo coalescing limits.
4821                    let replacement = format!("{new_text}{closer}");
4822                    self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
4823                    let cursor = range.start + new_text.len();
4824                    self.mode.track_auto_closed_pair(
4825                        cursor - open_len..cursor,
4826                        cursor..cursor + closer.len(),
4827                    );
4828                    self.undo_manager
4829                        .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
4830                    self.set_cursor_to(cursor);
4831                    self.update_preferred_column();
4832                    self.undo_manager.record_selections(
4833                        vec![selection_before],
4834                        self.selections.iter().copied().collect(),
4835                    );
4836                } else {
4837                    self.replace_text_in_ranges(
4838                        &[(range.clone(), new_text.to_string())],
4839                        window,
4840                        cx,
4841                    );
4842                }
4843            }
4844            if ends_composition {
4845                self.undo_manager.commit_transaction();
4846            }
4847
4848            if !self.silent_replace_text {
4849                M::on_text_typed(self, &range, new_text, window, cx);
4850            }
4851            return;
4852        }
4853
4854        // Single-line path
4855        let old_text = self.text.clone();
4856        // Token-aware history replay applies several replacements but emits one
4857        // `Change` at the end, so its edits accumulate instead of being
4858        // discarded with each silent replacement.
4859        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4860        if !accumulate_replay_edits {
4861            self.last_input_edits.clear();
4862        }
4863        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4864        self.text.replace(range.clone(), new_text);
4865
4866        let mut new_offset = (range.start + new_text.len()).min(self.text.len());
4867
4868        // True if the mask has changed the text, e.g. regrouping the
4869        // separators or completing a leading dot.
4870        let mut mask_changed = false;
4871
4872        if self.is_single_line() {
4873            let pending_text = self.text.to_string();
4874            // Check if the new text is valid.
4875            //
4876            // Only reject the edit if the old text was valid, to avoid
4877            // trapping a pre-existing invalid text (e.g. a `default_value`
4878            // that does not conform), the user can still edit to fix it.
4879            if !self.replaying_history
4880                && !self.validated_token_edit
4881                && !self.is_valid_input(&pending_text, cx)
4882                && self.is_valid_input(&old_text.to_string(), cx)
4883            {
4884                self.text = old_text;
4885                return;
4886            }
4887
4888            if !self.replaying_history && !self.mask_pattern.is_none() {
4889                let mask_text = self.mask_pattern.mask(&pending_text);
4890                mask_changed = mask_text.as_str() != pending_text;
4891                self.text = Rope::from(mask_text.as_str());
4892                let new_text_len =
4893                    (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
4894                new_offset = (range.start + new_text_len).min(mask_text.len());
4895            }
4896        }
4897
4898        if mask_changed {
4899            // Masking rewrites the whole document, so ranges recorded against
4900            // the old text no longer point at anything.
4901            M::reset_annotations(self);
4902        } else {
4903            M::adjust_annotations(self, &range, new_text.len());
4904        }
4905        if mask_changed {
4906            // A segment-based history entry no longer matches the masked
4907            // document, record a whole-document change instead, so that
4908            // undo/redo can restore the text exactly.
4909            self.push_history(
4910                &old_text,
4911                &(0..old_text.len()),
4912                &self.text.to_string(),
4913                Some(EditIntent::Atomic),
4914                selection_before,
4915                Some((new_offset..new_offset).into()),
4916            );
4917        } else {
4918            self.push_history(
4919                &old_text,
4920                &range,
4921                &new_text,
4922                requested_intent,
4923                selection_before,
4924                None,
4925            );
4926        }
4927        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4928            diagnostics.reset(&self.text)
4929        }
4930        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4931        self.display_map
4932            .adjust_folds_for_edit(&old_text, &range, new_text);
4933        self.display_map
4934            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4935
4936        let edit = if mask_changed {
4937            Self::full_input_edit(&old_text, &self.text)
4938        } else {
4939            super::mode::replacement_input_edit(&old_text, &self.text, &range, new_text)
4940        };
4941        if self.emit_events || self.replaying_history {
4942            self.last_input_edits.push((edit, self.text.clone()));
4943        }
4944
4945        self.mode.update_highlighter::<M>(
4946            super::mode::HighlighterUpdate {
4947                selected_range: &range,
4948                old_text: &old_text,
4949                new_text: &self.text,
4950                change_text: &new_text,
4951                force: true,
4952                input_edit: Some(edit),
4953            },
4954            window,
4955            cx,
4956        );
4957
4958        self.update_fold_candidates_incremental(&range, new_text);
4959        M::refresh_language_features(self, window, cx);
4960        self.set_cursor_to(new_offset);
4961        self.ime_marked_range.take();
4962        // A commit ends the IME composition: macOS delivers `insertText:` for
4963        // the confirmed candidate without a following `unmarkText`, so close
4964        // the transaction here. Leaving it open would keep merging every later
4965        // edit into the same change, which then carries the text and selection
4966        // of the first composition.
4967        if ends_composition {
4968            self.undo_manager
4969                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4970            self.undo_manager.commit_transaction();
4971        }
4972        self.update_preferred_column();
4973        self.update_search(cx);
4974        self.dismiss_touch_selection(cx);
4975        if self.is_multi_line() {
4976            self.mode.update_auto_grow(&self.display_map);
4977        }
4978        if !self.silent_replace_text {
4979            M::on_text_typed(self, &range, &new_text, window, cx);
4980        }
4981        if self.emit_events {
4982            self.emit_change(cx);
4983        }
4984        cx.notify();
4985    }
4986
4987    /// Mark text is the IME temporary insert on typing.
4988    fn replace_and_mark_text_in_range(
4989        &mut self,
4990        range_utf16: Option<Range<usize>>,
4991        new_text: &str,
4992        new_selected_range_utf16: Option<Range<usize>>,
4993        window: &mut Window,
4994        cx: &mut Context<Self>,
4995    ) {
4996        let requested_intent = self.undo_manager.take_pending_intent();
4997        if !self.is_editable() {
4998            return;
4999        }
5000        let selection_before = *self.active_selection();
5001
5002        let starts_composition = self.ime_marked_range.is_none();
5003        if starts_composition {
5004            // Even a canceled preedit separates the typing gestures on either
5005            // side; its no-op transaction must not reconnect those gestures.
5006            self.undo_manager.break_transaction_coalescing();
5007            self.undo_manager.begin_transaction();
5008        }
5009
5010        // Collapse any extra cursors so we never leave stale secondary cursors behind.
5011        self.selections.remove_all_but_active();
5012
5013        M::reset_language_features(self);
5014
5015        // See the same NOTE in `replace_text_in_range`.
5016        let new_text = if self.replaying_history {
5017            Cow::Borrowed(new_text)
5018        } else {
5019            self.normalize_input(new_text)
5020        };
5021        let new_text: &str = &new_text;
5022
5023        let range = range_utf16
5024            .as_ref()
5025            .map(|range_utf16| self.range_from_utf16(range_utf16))
5026            .or(self.ime_marked_range.map(|range| {
5027                let range = self.range_to_utf16(&(range.start..range.end));
5028                self.range_from_utf16(&range)
5029            }))
5030            .unwrap_or(self.selected_range());
5031        let range = self.normalize_token_range(range);
5032
5033        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
5034        let old_text = self.text.clone();
5035        // Marked text does not emit `InputEvent::Change`, so no edit belongs to
5036        // the most recent change after it.
5037        self.last_input_edits.clear();
5038        self.mode.adjust_auto_closed_pair(&range, new_text.len());
5039        self.text.replace(range.clone(), new_text);
5040
5041        if self.is_single_line() {
5042            let pending_text = self.text.to_string();
5043            // See the same NOTE in `replace_text_in_range`.
5044            if !self.replaying_history
5045                && !self.validated_token_edit
5046                && !self.is_valid_input(&pending_text, cx)
5047                && self.is_valid_input(&old_text.to_string(), cx)
5048            {
5049                self.text = old_text;
5050                if starts_composition {
5051                    self.undo_manager.commit_transaction();
5052                }
5053                return;
5054            }
5055        }
5056
5057        if self.ime_original_text.is_none() {
5058            self.ime_original_text = Some(old_text.clone());
5059        }
5060        M::adjust_annotations(self, &range, new_text.len());
5061        if let Some(diagnostics) = self.mode.diagnostics_mut() {
5062            diagnostics.reset(&self.text)
5063        }
5064        // Adjust folds before updating wrap map: remove overlapping folds and shift others
5065        self.display_map
5066            .adjust_folds_for_edit(&old_text, &range, new_text);
5067        self.display_map
5068            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5069
5070        self.mode.update_highlighter::<M>(
5071            super::mode::HighlighterUpdate {
5072                selected_range: &range,
5073                old_text: &old_text,
5074                new_text: &self.text,
5075                change_text: &new_text,
5076                force: true,
5077                input_edit: None,
5078            },
5079            window,
5080            cx,
5081        );
5082
5083        self.update_fold_candidates_incremental(&range, new_text);
5084        M::refresh_language_features(self, window, cx);
5085        if new_text.is_empty() {
5086            // Cancel selection, when cancel IME input.
5087            self.set_cursor_to(range.start);
5088            self.ime_marked_range = None;
5089        } else {
5090            self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
5091            let new_range = new_selected_range_utf16
5092                .as_ref()
5093                .map(|range_utf16| {
5094                    let new_text = Rope::from(new_text);
5095                    range.start + new_text.offset_utf16_to_offset(range_utf16.start)
5096                        ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
5097                })
5098                .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
5099            self.set_selection(new_range.start, new_range.end);
5100        }
5101        if self.is_multi_line() {
5102            self.mode.update_auto_grow(&self.display_map);
5103        }
5104        if self.push_history(
5105            &old_text,
5106            &range,
5107            new_text,
5108            requested_intent,
5109            selection_before,
5110            Some(*self.active_selection()),
5111        ) {
5112            self.undo_manager
5113                .record_selections(vec![selection_before], vec![*self.active_selection()]);
5114            self.undo_manager.record_auto_closed_pairs(
5115                auto_closed_pairs_before,
5116                self.mode.auto_closed_pairs().clone(),
5117            );
5118        }
5119        if new_text.is_empty() {
5120            self.undo_manager.commit_transaction();
5121        }
5122        cx.notify();
5123    }
5124
5125    /// Used to position IME candidates.
5126    fn bounds_for_range(
5127        &mut self,
5128        range_utf16: Range<usize>,
5129        bounds: Bounds<Pixels>,
5130        _window: &mut Window,
5131        _cx: &mut Context<Self>,
5132    ) -> Option<Bounds<Pixels>> {
5133        let last_layout = self.last_layout.as_ref()?;
5134        let line_height = last_layout.line_height;
5135        let line_number_width = last_layout.line_number_width;
5136        let range = self.range_from_utf16(&range_utf16);
5137
5138        let mut start_origin = None;
5139        let mut end_origin = None;
5140        let line_number_origin = point(line_number_width, px(0.));
5141        let mut y_offset = last_layout.visible_top;
5142
5143        let start_row = self
5144            .text
5145            .offset_to_point(range.start.min(self.text.len()))
5146            .row;
5147        let end_row = self
5148            .text
5149            .offset_to_point(range.end.min(self.text.len()))
5150            .row;
5151
5152        for (vi, line) in last_layout.lines.iter().enumerate() {
5153            if start_origin.is_some() && end_origin.is_some() {
5154                break;
5155            }
5156
5157            let buffer_line = last_layout.visible_buffer_lines[vi];
5158            let index_offset = last_layout.visible_line_byte_offsets[vi];
5159
5160            if start_origin.is_none() && buffer_line == start_row {
5161                let local_offset = range.start.saturating_sub(index_offset).min(line.len());
5162                let p = line
5163                    .position_for_index(local_offset, last_layout, false)
5164                    .unwrap_or_else(|| point(px(0.), px(0.)));
5165                start_origin = Some(p + point(px(0.), y_offset));
5166            }
5167
5168            if end_origin.is_none() && buffer_line == end_row {
5169                let local_offset = range.end.saturating_sub(index_offset).min(line.len());
5170                let p = line
5171                    .position_for_index(local_offset, last_layout, false)
5172                    .unwrap_or_else(|| point(px(0.), px(0.)));
5173                end_origin = Some(p + point(px(0.), y_offset));
5174            }
5175
5176            y_offset += line.size(line_height).height;
5177        }
5178
5179        let start_origin = start_origin.or_else(|| {
5180            let offset = self.last_cursor.or(Some(self.cursor()))?;
5181            let (_, _, origin) = self.line_and_position_for_offset(offset);
5182            origin.map(|origin| origin - line_number_origin)
5183        })?;
5184        let mut end_origin = end_origin.unwrap_or(start_origin);
5185        // Ensure at same line.
5186        end_origin.y = start_origin.y;
5187        if end_origin.x <= start_origin.x {
5188            end_origin.x = start_origin.x + px(1.);
5189        }
5190
5191        Some(Bounds::from_corners(
5192            bounds.origin + line_number_origin + start_origin,
5193            // + line_height for show IME panel under the cursor line.
5194            bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
5195        ))
5196    }
5197
5198    fn character_index_for_point(
5199        &mut self,
5200        point: gpui::Point<Pixels>,
5201        _window: &mut Window,
5202        _cx: &mut Context<Self>,
5203    ) -> Option<usize> {
5204        let last_layout = self.last_layout.as_ref()?;
5205        // The same origin as `resolve_mouse_position`: past the gutter, at the first
5206        // visible line.
5207        let inner_point = self.last_bounds?.localize(&point)?
5208            - gpui::point(last_layout.line_number_width, last_layout.visible_top);
5209
5210        let mut line_top = px(0.);
5211        for (vi, line) in last_layout.lines.iter().enumerate() {
5212            let offset = last_layout.visible_line_byte_offsets[vi];
5213            let line_point = inner_point - gpui::point(px(0.), line_top);
5214            if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
5215                return Some(self.offset_to_utf16(self.resolve_index(offset + utf8_index)));
5216            }
5217            line_top += line.size(last_layout.line_height).height;
5218        }
5219
5220        None
5221    }
5222
5223    fn text_input_configuration(
5224        &mut self,
5225        _window: &mut Window,
5226        _cx: &mut Context<Self>,
5227    ) -> TextInputConfiguration {
5228        InputBaseState::text_input_configuration(self)
5229    }
5230}
5231
5232impl<M: InputModeKind> Focusable for InputBaseState<M> {
5233    fn focus_handle(&self, _cx: &App) -> FocusHandle {
5234        self.focus_handle.clone()
5235    }
5236}
5237
5238impl<M: InputModeKind> Render for InputBaseState<M> {
5239    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5240        // Before anything reads it: the element resolves this style during
5241        // layout and paint, and both happen after this call in the same frame.
5242        self.editor_style = self
5243            .projected_editor_style
5244            .resolved(&crate::Theme::global(cx).tokens);
5245        let entity = cx.entity();
5246        let text_runs = self.accessibility_text_runs(window);
5247        if self._pending_update {
5248            self.mode.update_highlighter::<M>(
5249                super::mode::HighlighterUpdate {
5250                    selected_range: &(0..0),
5251                    old_text: &self.text,
5252                    new_text: &self.text,
5253                    change_text: "",
5254                    force: false,
5255                    input_edit: None,
5256                },
5257                window,
5258                cx,
5259            );
5260
5261            self.update_fold_candidates();
5262            M::refresh_language_features(self, window, cx);
5263            self._pending_update = false;
5264        }
5265
5266        let element = div()
5267            .id(EDITOR_ELEMENT_ID)
5268            .key_context(CONTEXT)
5269            .when_some(self.accessibility.as_ref(), |this, accessibility| {
5270                this.when_some(accessibility.role, |this, role| this.role(role))
5271                    .when_some(accessibility.label.clone(), |this, label| {
5272                        this.aria_label(label)
5273                    })
5274                    .when_some(accessibility.placeholder.clone(), |this, placeholder| {
5275                        this.aria_placeholder(placeholder)
5276                    })
5277                    .when_some(accessibility.accessibility_id.clone(), |this, id| {
5278                        this.accessibility_id(id)
5279                    })
5280                    .when(
5281                        accessibility.value_exposed
5282                            && !self.masked
5283                            && (window.is_a11y_active() || cfg!(feature = "test-support")),
5284                        |this| this.aria_value(self.text.to_string()),
5285                    )
5286                    .when_some(text_runs, |this, runs| {
5287                        this.a11y_synthetic_children(move |builder| runs.push(builder))
5288                    })
5289                    .on_a11y_action(gpui::AccessibleAction::Focus, {
5290                        let entity = entity.clone();
5291                        move |_, window, cx| {
5292                            entity.update(cx, |state, cx| {
5293                                state.handle_accessibility_focus(window, cx)
5294                            });
5295                        }
5296                    })
5297                    .when(self.is_editable(), |this| {
5298                        this.on_a11y_action(gpui::AccessibleAction::SetValue, {
5299                            let entity = entity.clone();
5300                            move |data, window, cx| {
5301                                entity.update(cx, |state, cx| {
5302                                    state.handle_accessibility_set_value(data, window, cx)
5303                                });
5304                            }
5305                        })
5306                    })
5307            })
5308            .when(self.is_editable(), |this| {
5309                this.on_action(window.listener_for(&entity, InputBaseState::backspace))
5310                    .on_action(window.listener_for(&entity, InputBaseState::delete))
5311                    .on_action(
5312                        window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
5313                    )
5314                    .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
5315                    .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
5316                    .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
5317                    .on_action(window.listener_for(&entity, InputBaseState::enter))
5318                    .on_action(window.listener_for(&entity, InputBaseState::escape))
5319                    .on_action(window.listener_for(&entity, InputBaseState::paste))
5320                    .on_action(window.listener_for(&entity, InputBaseState::cut))
5321                    .on_action(window.listener_for(&entity, InputBaseState::undo))
5322                    .on_action(window.listener_for(&entity, InputBaseState::redo))
5323                    .when(self.is_multi_line(), |this| {
5324                        this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
5325                            .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
5326                            .on_action(window.listener_for(&entity, InputBaseState::indent_block))
5327                            .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
5328                    })
5329            })
5330            .on_action(window.listener_for(&entity, InputBaseState::left))
5331            .on_action(window.listener_for(&entity, InputBaseState::right))
5332            .on_action(window.listener_for(&entity, InputBaseState::select_left))
5333            .on_action(window.listener_for(&entity, InputBaseState::select_right))
5334            .when(self.is_multi_line(), |this| {
5335                this.on_action(window.listener_for(&entity, InputBaseState::up))
5336                    .on_action(window.listener_for(&entity, InputBaseState::down))
5337                    .on_action(window.listener_for(&entity, InputBaseState::select_up))
5338                    .on_action(window.listener_for(&entity, InputBaseState::select_down))
5339                    .on_action(window.listener_for(&entity, InputBaseState::page_up))
5340                    .on_action(window.listener_for(&entity, InputBaseState::page_down))
5341                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
5342                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
5343            })
5344            .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
5345            .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
5346            .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
5347            .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
5348            .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
5349            .on_action(window.listener_for(&entity, InputBaseState::home))
5350            .on_action(window.listener_for(&entity, InputBaseState::end))
5351            .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
5352            .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
5353            .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
5354            .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
5355            .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
5356            .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
5357            .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
5358            .on_action({
5359                let entity = entity.clone();
5360                move |_: &ActivateToken, window, cx| {
5361                    let state = entity.read(cx);
5362                    let activation = state
5363                        .token_spans()
5364                        .iter()
5365                        .find(|span| span.range() == state.selected_range())
5366                        .and_then(|span| {
5367                            state.range_to_bounds(&span.range()).and_then(|bounds| {
5368                                state.token_activation(
5369                                    span.range().start,
5370                                    bounds,
5371                                    gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
5372                                        bounds,
5373                                        ..Default::default()
5374                                    }),
5375                                )
5376                            })
5377                        });
5378                    if let Some((listener, event)) = activation {
5379                        listener(&event, window, cx);
5380                    }
5381                }
5382            })
5383            .on_action(window.listener_for(&entity, InputBaseState::copy))
5384            .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
5385            .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
5386            .on_mouse_down(
5387                MouseButton::Left,
5388                window.listener_for(&entity, InputBaseState::on_mouse_down),
5389            )
5390            .on_mouse_down(
5391                MouseButton::Right,
5392                window.listener_for(&entity, InputBaseState::on_mouse_down),
5393            )
5394            .on_mouse_up(
5395                MouseButton::Left,
5396                window.listener_for(&entity, InputBaseState::on_mouse_up),
5397            )
5398            .on_mouse_up(
5399                MouseButton::Right,
5400                window.listener_for(&entity, InputBaseState::on_mouse_up),
5401            )
5402            .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
5403            .on_scroll(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
5404            .when(self.is_multi_line() && !self.disabled, |this| {
5405                this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
5406            })
5407            .when(!self.disabled, |this| {
5408                if self.is_multi_line() && window.modifiers().alt {
5409                    this.cursor_crosshair()
5410                } else {
5411                    this.cursor_text()
5412                }
5413            })
5414            .flex_1()
5415            // A single line fills the frame and sits at its vertical center,
5416            // so the frame needs no layout of its own to hold it. It is never
5417            // shorter than its line, though: this root clips (overflow-x
5418            // hidden clips both axes), and a frame whose padding leaves less
5419            // than a line, like Component's Input, would cut off descenders.
5420            .map(|this| {
5421                if self.is_multi_line() {
5422                    this.h_full()
5423                } else {
5424                    this.min_h_full().flex().items_center()
5425                }
5426            })
5427            .flex_grow_1()
5428            .overflow_x_hidden()
5429            .when(self.is_multi_line(), |this| {
5430                this.pt(self.editor_paddings.top)
5431                    .pr(self.editor_paddings.right)
5432                    .pb(self.editor_paddings.bottom)
5433                    .pl(self.editor_paddings.left)
5434            })
5435            .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
5436            .when(self.shows_scrollbar(), |this| {
5437                this.child(EditorScrollbar::new(entity.clone()))
5438            });
5439
5440        // Actions only one mode handles are registered by that mode, where
5441        // `Self` is concrete enough to name its own entity type.
5442        M::register_actions(element, &entity, window)
5443            .test_support()
5444            .track_focus(&self.focus_handle)
5445    }
5446}
5447
5448#[cfg(test)]
5449mod tests {
5450    use super::*;
5451
5452    #[gpui::test]
5453    fn test_set_value_waits_for_the_first_layout(cx: &mut TestAppContext) {
5454        cx.update(crate::init);
5455        let (state, cx) = cx.add_window_view(|window, cx| {
5456            let mut state = crate::input::InputState::new(window, cx);
5457            state.set_value("hello", window, cx);
5458            // Made outside drawing, the state only has a placeholder font to shape with.
5459            assert_eq!(state.display_map().wrap_row_count(), 0);
5460            state
5461        });
5462        cx.update(|window, cx| window.draw(cx).clear(cx));
5463        state.read_with(cx, |state, _| {
5464            assert_eq!(state.value(), "hello");
5465            assert_eq!(state.display_map().wrap_row_count(), 1);
5466        });
5467    }
5468
5469    #[gpui::test]
5470    fn accessibility_actions_recheck_live_editability(cx: &mut TestAppContext) {
5471        cx.update(crate::init);
5472        let (state, cx) = cx.add_window_view(|window, cx| {
5473            crate::input::InputState::new(window, cx).default_value("initial")
5474        });
5475        let changes = Rc::new(Cell::new(0));
5476        let observed = changes.clone();
5477        let _subscription = cx.update(|_, cx| {
5478            cx.subscribe(&state, move |_, event: &InputEvent, _| {
5479                if matches!(event, InputEvent::Change) {
5480                    observed.set(observed.get() + 1);
5481                }
5482            })
5483        });
5484        cx.update(|window, cx| {
5485            state.update(cx, |state, cx| {
5486                state.handle_accessibility_set_value(None, window, cx);
5487                state.handle_accessibility_focus(window, cx);
5488                assert!(state.focus_handle.is_focused(window));
5489            });
5490            window.draw(cx).clear(cx);
5491        });
5492        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5493        assert_eq!(changes.get(), 0);
5494
5495        let action = gpui::accesskit::ActionData::Value("updated🦀".into());
5496        cx.update(|window, cx| {
5497            state.update(cx, |state, cx| {
5498                state.handle_accessibility_set_value(Some(&action), window, cx)
5499            });
5500        });
5501        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5502        assert_eq!(changes.get(), 1);
5503        for disabled in [false, true] {
5504            cx.update(|window, cx| {
5505                window.blur(cx);
5506                state.update(cx, |state, cx| {
5507                    state.set_disabled(disabled, cx);
5508                    state.set_readonly(!disabled, cx);
5509                    state.handle_accessibility_focus(window, cx);
5510                    assert_eq!(state.focus_handle.is_focused(window), !disabled);
5511                    let rejected = gpui::accesskit::ActionData::Value("rejected".into());
5512                    state.handle_accessibility_set_value(Some(&rejected), window, cx);
5513                });
5514            });
5515            assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5516            assert_eq!(changes.get(), 1);
5517        }
5518        cx.update(|window, cx| {
5519            state.update(cx, |state, cx| {
5520                state.set_disabled(false, cx);
5521                state.set_readonly(false, cx);
5522                state.handle_accessibility_focus(window, cx);
5523            });
5524            window.draw(cx).clear(cx);
5525            window.dispatch_action(Box::new(Undo), cx);
5526        });
5527        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5528        cx.update(|window, cx| {
5529            state.update(cx, |state, cx| {
5530                state.set_masked(true, window, cx);
5531                state.handle_accessibility_set_value(Some(&action), window, cx);
5532            });
5533        });
5534        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5535    }
5536
5537    #[gpui::test]
5538    fn accessibility_set_value_preserves_exact_editor_text(cx: &mut TestAppContext) {
5539        cx.update(crate::init);
5540        let (editor, cx) = cx.add_window_view(|window, cx| {
5541            crate::input::EditorState::new(window, cx).language("rust")
5542        });
5543        let action = gpui::accesskit::ActionData::Value("(".into());
5544        cx.update(|window, cx| {
5545            editor.update(cx, |editor, cx| {
5546                editor.handle_accessibility_set_value(Some(&action), window, cx)
5547            });
5548        });
5549        assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "(");
5550    }
5551
5552    #[gpui::test]
5553    fn revealing_a_password_keeps_text_assistance_disabled(cx: &mut TestAppContext) {
5554        cx.update(crate::init);
5555        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5556            let state = cx.new(|cx| crate::input::InputState::new(window, cx).masked(true));
5557            let hidden = state.read(cx).text_input_configuration();
5558            assert!(!hidden.autocorrect && !hidden.suggestions);
5559            assert_eq!(hidden.autocapitalize, Autocapitalize::None);
5560
5561            // The component's reveal button uses this same state transition.
5562            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5563            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5564            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5565            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5566            gpui::EmptyView
5567        });
5568    }
5569
5570    #[gpui::test]
5571    fn text_input_configuration_follows_the_input(cx: &mut TestAppContext) {
5572        use crate::input::{InputState, TextareaState};
5573
5574        cx.update(crate::init);
5575        let mut states = None;
5576        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5577            states = Some((
5578                cx.new(|cx| InputState::new(window, cx)),
5579                cx.new(|cx| InputState::new(window, cx).masked(true)),
5580                cx.new(|cx| TextareaState::new(window, cx)),
5581                cx.new(|cx| {
5582                    InputState::new(window, cx)
5583                        .input_action(TextInputAction::Search)
5584                        .autocorrect(true)
5585                        .autocapitalize(Autocapitalize::Words)
5586                }),
5587            ));
5588            gpui::EmptyView
5589        });
5590        let (plain, masked, textarea, search) = states.unwrap();
5591
5592        cx.read(|cx| {
5593            assert_eq!(
5594                plain.read(cx).text_input_configuration(),
5595                TextInputConfiguration {
5596                    input_action: TextInputAction::Done,
5597                    ..Default::default()
5598                }
5599            );
5600            assert_eq!(
5601                masked.read(cx).text_input_configuration(),
5602                TextInputConfiguration {
5603                    input_action: TextInputAction::Done,
5604                    ..Default::default()
5605                }
5606            );
5607            assert_eq!(
5608                textarea.read(cx).text_input_configuration(),
5609                TextInputConfiguration {
5610                    input_action: TextInputAction::Enter,
5611                    ..Default::default()
5612                }
5613            );
5614            let search = search.read(cx).text_input_configuration();
5615            assert_eq!(search.input_action, TextInputAction::Search);
5616            assert_eq!(search.autocapitalize, Autocapitalize::Words);
5617            assert!(search.autocorrect);
5618            assert!(search.suggestions);
5619        });
5620    }
5621
5622    #[gpui::test]
5623    fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) {
5624        use crate::input::{CompletionProvider, EditorState};
5625        use gpui::Task;
5626        use lsp_types::{CompletionContext, CompletionResponse};
5627        use std::cell::RefCell;
5628
5629        #[derive(Default)]
5630        struct Provider {
5631            starts: RefCell<Vec<usize>>,
5632            queries: RefCell<Vec<(usize, String)>>,
5633        }
5634
5635        impl CompletionProvider for Provider {
5636            fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
5637                self.starts.borrow_mut().push(offset);
5638                true
5639            }
5640
5641            fn completions(
5642                &self,
5643                _: &Rope,
5644                offset: usize,
5645                trigger: CompletionContext,
5646                _: &mut Window,
5647                _: &mut App,
5648            ) -> Task<anyhow::Result<CompletionResponse>> {
5649                self.queries
5650                    .borrow_mut()
5651                    .push((offset, trigger.trigger_character.unwrap()));
5652                Task::ready(Ok(CompletionResponse::Array(vec![])))
5653            }
5654        }
5655
5656        cx.update(crate::init);
5657        let mut editor = None;
5658        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5659            editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
5660            gpui::EmptyView
5661        });
5662        let editor = editor.unwrap();
5663        let provider = Rc::new(Provider::default());
5664        window
5665            .update(cx, |_, window, cx| {
5666                editor.update(cx, |state, cx| {
5667                    state.extras.lsp.completion_provider = Some(provider.clone());
5668                    state
5669                        .extras
5670                        .context_menu_content
5671                        .completion
5672                        .trigger_start_offset = Some(0);
5673                    state.extras.context_menu_content.completion.query = "aa".into();
5674                    state.set_cursor_to(1);
5675                    state.add_cursor_at(0, cx);
5676
5677                    state.replace_text_in_range(None, "中", window, cx);
5678
5679                    assert_eq!(state.value(), "中a中a");
5680                    assert_eq!(provider.starts.borrow().as_slice(), &[4]);
5681                    assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
5682                });
5683            })
5684            .unwrap();
5685    }
5686
5687    #[gpui::test]
5688    fn selected_range_restores_unicode_direction_without_splitting_characters(
5689        cx: &mut TestAppContext,
5690    ) {
5691        use crate::input::EditorState;
5692        cx.update(crate::init);
5693        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5694            let _state = cx.new(|cx| {
5695                let mut state = EditorState::new(window, cx).default_value("中😀a");
5696                state.set_selected_range_with_direction(3..8, true, cx);
5697                let selected = state.selected_text_range(false, window, cx).unwrap();
5698                assert_eq!(selected.range, 1..4);
5699                assert!(selected.reversed);
5700                assert_eq!(state.selected_range(), 3..8);
5701                assert!(state.is_selection_reversed());
5702                let range = state.selected_range();
5703                let reversed = state.is_selection_reversed();
5704                state.set_selected_range_with_direction(range, reversed, cx);
5705                assert!(state.is_selection_reversed());
5706                state.set_selected_range(3..8, cx);
5707                let selected = state.selected_text_range(false, window, cx).unwrap();
5708                assert_eq!(selected.range, 1..4);
5709                assert!(!selected.reversed);
5710                assert!(!state.is_selection_reversed());
5711                // A reversed Rust Range remains empty for existing callers.
5712                state.set_selected_range(Range { start: 8, end: 3 }, cx);
5713                assert_eq!(state.selected_range(), 8..8);
5714                assert!(!state.is_selection_reversed());
5715                state.set_selected_range_with_direction(4..4, true, cx);
5716                assert!(!state.is_selection_reversed());
5717                assert_eq!(
5718                    state.selected_text_range(false, window, cx).unwrap().range,
5719                    1..1
5720                );
5721                state
5722            });
5723            gpui::EmptyView
5724        });
5725    }
5726
5727    #[gpui::test]
5728    fn test_set_tokens_keeps_text_selection_and_history(cx: &mut TestAppContext) {
5729        use crate::input::{InlineToken, InlineTokenError, InputContent};
5730        let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
5731        let bold = |text: &str| {
5732            InputContent::new(text.to_string())
5733                .with_token(2..7, InlineToken::new("bold", "**b**"))
5734                .unwrap()
5735        };
5736        view.window_handle
5737            .update(cx, |_, window, cx| {
5738                view.input.update(cx, |state, cx| {
5739                    state.set_selected_range(9..9, cx);
5740                    state.insert("!", window, cx);
5741                    state.set_selected_range(9..9, cx);
5742                    state.set_tokens(bold("a **b** c!"), cx).unwrap();
5743                    assert_eq!(state.value(), "a **b** c!");
5744                    assert_eq!(state.selected_range(), 9..9);
5745                    assert_eq!(state.tokens().len(), 1);
5746
5747                    assert_eq!(
5748                        state.set_tokens(bold("a **b** c"), cx),
5749                        Err(InlineTokenError::TextMismatch)
5750                    );
5751                    state
5752                        .set_tokens(InputContent::new("a **b** c!"), cx)
5753                        .unwrap();
5754                    assert!(state.tokens().is_empty());
5755                    state.set_selected_range(4..4, cx);
5756                    assert_eq!(
5757                        state.set_tokens(bold("a **b** c!"), cx),
5758                        Err(InlineTokenError::SplitsSelection)
5759                    );
5760                    state.undo(&Undo, window, cx);
5761                    assert_eq!(state.value(), "a **b** c");
5762                });
5763            })
5764            .unwrap();
5765    }
5766
5767    #[gpui::test]
5768    fn test_set_tokens_rejects_a_token_through_any_cursor(cx: &mut TestAppContext) {
5769        use crate::input::{InlineToken, InlineTokenError, InputContent};
5770        let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
5771        view.window_handle
5772            .update(cx, |_, _, cx| {
5773                view.input.update(cx, |state, cx| {
5774                    state.set_selected_range(9..9, cx);
5775                    let id = state.selections.generate_id();
5776                    state.selections.add(CursorSelection::new(id, 4, 4));
5777                    let content = InputContent::new("a **b** c")
5778                        .with_token(2..7, InlineToken::new("bold", "**b**"))
5779                        .unwrap();
5780                    assert_eq!(
5781                        state.set_tokens(content, cx),
5782                        Err(InlineTokenError::SplitsSelection)
5783                    );
5784                    assert!(state.tokens().is_empty());
5785                });
5786            })
5787            .unwrap();
5788    }
5789
5790    #[gpui::test]
5791    fn test_set_tokens_undo_redo_replays_edits_inside_and_before_a_token(cx: &mut TestAppContext) {
5792        use crate::input::{InlineToken, InputContent};
5793        let view = InputView::build_textarea(cx, |state| state.default_value("a **** c"));
5794        let bold = |text: &str, range: Range<usize>| {
5795            InputContent::new(text.to_string())
5796                .with_token(range, InlineToken::new("bold", "**b**"))
5797                .unwrap()
5798        };
5799        view.window_handle
5800            .update(cx, |_, window, cx| {
5801                view.input.update(cx, |state, cx| {
5802                    state.set_selected_range(4..4, cx);
5803                    state.insert("b", window, cx);
5804                    state.set_selected_range(9..9, cx);
5805                    state.set_tokens(bold("a **b** c", 2..7), cx).unwrap();
5806
5807                    state.undo(&Undo, window, cx);
5808                    assert_eq!(state.value(), "a **** c");
5809                    assert!(state.tokens().is_empty());
5810                    state.redo(&Redo, window, cx);
5811                    assert_eq!(state.value(), "a **b** c");
5812                    assert!(state.tokens().is_empty());
5813                    assert_eq!(state.selected_range(), 5..5);
5814
5815                    state.set_selected_range(0..0, cx);
5816                    state.insert("z", window, cx);
5817                    state.set_selected_range(10..10, cx);
5818                    state.set_tokens(bold("za **b** c", 3..8), cx).unwrap();
5819
5820                    state.undo(&Undo, window, cx);
5821                    assert_eq!(state.value(), "a **b** c");
5822                    let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
5823                    assert_eq!(ranges, vec![2..7]);
5824                    state.redo(&Redo, window, cx);
5825                    assert_eq!(state.value(), "za **b** c");
5826                    let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
5827                    assert_eq!(ranges, vec![3..8]);
5828                });
5829            })
5830            .unwrap();
5831    }
5832
5833    #[gpui::test]
5834    fn test_set_tokens_refreshes_the_token_layout(cx: &mut TestAppContext) {
5835        use crate::input::{InlineToken, InputContent};
5836        let view = InputView::build_textarea(cx, |state| state.default_value("@a x @a y"));
5837        let mention = || InlineToken::new("a", "@a");
5838        view.window_handle
5839            .update(cx, |_, _, cx| {
5840                view.input.update(cx, |state, cx| {
5841                    let content = InputContent::new("@a x @a y")
5842                        .with_token(0..2, mention())
5843                        .and_then(|content| content.with_token(5..7, mention()))
5844                        .unwrap();
5845                    state.set_tokens(content, cx).unwrap();
5846                });
5847            })
5848            .unwrap();
5849        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5850        visual.update(|window, cx| window.draw(cx).clear(cx));
5851        view.input.update(&mut visual, |state, cx| {
5852            let content = InputContent::new("@a x @a y")
5853                .with_token(5..7, mention())
5854                .unwrap();
5855            state.set_tokens(content, cx).unwrap();
5856        });
5857        visual.update(|window, cx| window.draw(cx).clear(cx));
5858        view.input.read_with(&visual, |state, _| {
5859            let cache = state.token_layout_cache.as_ref().unwrap();
5860            let ranges: Vec<_> = cache
5861                .metrics
5862                .iter()
5863                .map(|(range, _)| range.clone())
5864                .collect();
5865            assert_eq!(ranges, vec![5..7]);
5866        });
5867    }
5868
5869    #[gpui::test]
5870    fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
5871        use crate::input::{InlineToken, InlineTokenPresentation};
5872        let width = Rc::new(Cell::new(4000.));
5873        let render_width = width.clone();
5874        let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
5875        view.window_handle
5876            .update(cx, |_, window, cx| {
5877                view.input.update(cx, |state, cx| {
5878                    state
5879                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
5880                        .unwrap();
5881                    state
5882                        .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
5883                        .unwrap();
5884                    state.set_token_presentation(
5885                        InlineTokenPresentation::default()
5886                            .token(move |_, _, _| div().w(px(render_width.get()))),
5887                    );
5888                });
5889            })
5890            .unwrap();
5891        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5892        visual.update(|window, cx| window.draw(cx).clear(cx));
5893        view.input.read_with(&visual, |state, _| {
5894            assert_eq!(state.display_map.wrap_row_count(), 2);
5895            let first = state.range_to_bounds(&(0..2)).unwrap();
5896            let second = state.range_to_bounds(&(2..4)).unwrap();
5897            assert!(second.origin.y > first.origin.y);
5898            assert_eq!(
5899                state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
5900                2
5901            );
5902        });
5903        width.set(100.);
5904        view.input.update(&mut visual, |_, cx| cx.notify());
5905        visual.update(|window, cx| window.draw(cx).clear(cx));
5906        view.input.read_with(&visual, |state, _| {
5907            assert_eq!(state.display_map.wrap_row_count(), 1)
5908        });
5909    }
5910
5911    #[gpui::test]
5912    fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
5913        use crate::input::{InlineToken, InlineTokenPresentation};
5914        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5915        let target = view.input.clone();
5916        view.window_handle
5917            .update(cx, |_, window, cx| {
5918                view.input.update(cx, |state, cx| {
5919                    state
5920                        .replace_range_with_token(
5921                            7..13,
5922                            InlineToken::new("a", "@alice"),
5923                            window,
5924                            cx,
5925                        )
5926                        .unwrap();
5927                    state.set_token_presentation(
5928                        InlineTokenPresentation::default()
5929                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5930                            .on_token_click(move |_, window, cx| {
5931                                target.update(cx, |state, cx| {
5932                                    state.set_value("activated", window, cx)
5933                                })
5934                            }),
5935                    );
5936                    state.focus(window, cx);
5937                    state.set_selected_range(7..13, cx);
5938                });
5939            })
5940            .unwrap();
5941        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5942        visual.update(|window, cx| window.draw(cx).clear(cx));
5943        visual.update(|window, cx| {
5944            let state = view.input.read(cx);
5945            let bounds = state.range_to_bounds(&(7..13)).unwrap();
5946            assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
5947            let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
5948            let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
5949            assert_eq!((left, right), (7, 13));
5950            window.dispatch_action(Box::new(ActivateToken), cx);
5951        });
5952        visual.run_until_parked();
5953        view.input.read_with(&visual, |state, _| {
5954            assert_eq!(state.value().as_ref(), "activated")
5955        });
5956    }
5957
5958    #[gpui::test]
5959    fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
5960        use crate::input::InlineToken;
5961        cx.update(crate::init);
5962        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5963        view.window_handle
5964            .update(cx, |_, window, cx| {
5965                view.input.update(cx, |state, cx| {
5966                    state
5967                        .replace_range_with_token(
5968                            7..13,
5969                            InlineToken::new("a", "@alice"),
5970                            window,
5971                            cx,
5972                        )
5973                        .unwrap();
5974                    state.set_selected_range(0..0, cx);
5975                });
5976            })
5977            .unwrap();
5978        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5979        visual.update(|window, cx| window.draw(cx).clear(cx));
5980        let bounds = view
5981            .input
5982            .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
5983        visual.simulate_click(bounds.center(), gpui::Modifiers::default());
5984        visual.run_until_parked();
5985        view.input.read_with(&visual, |state, _| {
5986            assert_eq!(state.selected_range(), 7..13, "a click selects the token");
5987        });
5988    }
5989
5990    #[gpui::test]
5991    fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) {
5992        use crate::input::{InlineToken, InlineTokenPresentation};
5993        use gpui::{Bounds, point, px, size};
5994        cx.update(crate::init);
5995        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5996        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
5997        view.window_handle
5998            .update(cx, |_, window, cx| {
5999                view.input.update(cx, |state, cx| {
6000                    state
6001                        .replace_range_with_token(
6002                            7..13,
6003                            InlineToken::new("a", "@alice"),
6004                            window,
6005                            cx,
6006                        )
6007                        .unwrap();
6008                    state.set_token_presentation(
6009                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6010                    );
6011                    state.set_selected_range(0..0, cx);
6012                });
6013            })
6014            .unwrap();
6015        view.window_handle
6016            .update(cx, |_, _, cx| {
6017                view.input.update(cx, |state, _| {
6018                    let (_, entered) = state
6019                        .token_hover(7, bounds, true, None)
6020                        .expect("hover enters an enabled token");
6021                    assert!(entered.is_hovered());
6022                    assert_eq!(entered.token().id().as_ref(), "a");
6023                    assert_eq!(entered.range(), 7..13);
6024                    assert_eq!(entered.bounds(), bounds);
6025                    let (_, left) = state
6026                        .token_hover(7, bounds, false, None)
6027                        .expect("hover leaves the same token");
6028                    assert!(!left.is_hovered());
6029                    assert_eq!(state.selected_range(), 0..0, "hover never selects");
6030                    assert!(state.token_hover(99, bounds, true, None).is_none());
6031                });
6032            })
6033            .unwrap();
6034
6035        // Disabled tokens suppress hover, matching click; readonly allows it.
6036        view.window_handle
6037            .update(cx, |_, _, cx| {
6038                view.input.update(cx, |state, cx| {
6039                    state.set_disabled(true, cx);
6040                });
6041            })
6042            .unwrap();
6043        view.window_handle
6044            .update(cx, |_, _, cx| {
6045                view.input.update(cx, |state, _| {
6046                    assert!(state.token_hover(7, bounds, true, None).is_none())
6047                })
6048            })
6049            .unwrap();
6050        view.window_handle
6051            .update(cx, |_, _, cx| {
6052                view.input.update(cx, |state, cx| {
6053                    state.set_disabled(false, cx);
6054                    state.set_readonly(true, cx);
6055                });
6056            })
6057            .unwrap();
6058        view.window_handle
6059            .update(cx, |_, _, cx| {
6060                view.input.update(cx, |state, _| {
6061                    assert!(state.token_hover(7, bounds, true, None).is_some())
6062                })
6063            })
6064            .unwrap();
6065
6066        // Without a hover listener there is no hover activation.
6067        view.window_handle
6068            .update(cx, |_, _, cx| {
6069                view.input.update(cx, |state, _| {
6070                    state.set_token_presentation(InlineTokenPresentation::default());
6071                });
6072            })
6073            .unwrap();
6074        view.window_handle
6075            .update(cx, |_, _, cx| {
6076                view.input.update(cx, |state, _| {
6077                    assert!(state.token_hover(7, bounds, true, None).is_none())
6078                })
6079            })
6080            .unwrap();
6081    }
6082
6083    #[gpui::test]
6084    fn test_inline_token_hover_exit_delivered_when_token_removed(cx: &mut TestAppContext) {
6085        use crate::input::{InlineToken, InlineTokenPresentation};
6086        use std::cell::RefCell;
6087        use std::rc::Rc;
6088        cx.update(crate::init);
6089        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6090        let events: Rc<RefCell<Vec<(SharedString, bool)>>> = Rc::new(RefCell::new(Vec::new()));
6091        let sink = events.clone();
6092        view.window_handle
6093            .update(cx, |_, window, cx| {
6094                view.input.update(cx, |state, cx| {
6095                    state
6096                        .replace_range_with_token(
6097                            7..13,
6098                            InlineToken::new("a", "@alice"),
6099                            window,
6100                            cx,
6101                        )
6102                        .unwrap();
6103                    state.set_token_presentation(
6104                        InlineTokenPresentation::default()
6105                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6106                            .on_token_hover(move |event, _, _| {
6107                                sink.borrow_mut()
6108                                    .push((event.token().id().clone(), event.is_hovered()));
6109                            }),
6110                    );
6111                });
6112            })
6113            .unwrap();
6114        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6115        visual.update(|window, cx| window.draw(cx).clear(cx));
6116        let known_bounds = view.input.read_with(&visual, |state, _| {
6117            state
6118                .token_bounds
6119                .get(&7)
6120                .copied()
6121                .expect("placed token bounds")
6122        });
6123        visual.simulate_mouse_move(known_bounds.center(), None, gpui::Modifiers::default());
6124        visual.run_until_parked();
6125        visual.update(|window, cx| window.draw(cx).clear(cx));
6126        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6127
6128        // Remove the token while the pointer is still over its stale row: the
6129        // exit must fire even though the token element that owns the hover
6130        // mask is gone.
6131        view.window_handle
6132            .update(cx, |_, window, cx| {
6133                view.input
6134                    .update(cx, |state, cx| state.set_value("no tokens", window, cx));
6135            })
6136            .unwrap();
6137        visual.run_until_parked();
6138        visual.update(|window, cx| window.draw(cx).clear(cx));
6139        assert_eq!(
6140            events.borrow().as_slice(),
6141            &[("a".into(), true), ("a".into(), false)]
6142        );
6143    }
6144
6145    #[gpui::test]
6146    fn test_inline_token_hover_bounds_stay_single_row_at_wrap_boundary(cx: &mut TestAppContext) {
6147        use crate::input::{InlineToken, InlineTokenPresentation};
6148        cx.update(crate::init);
6149        let view = InputView::build_textarea(cx, |state| {
6150            state
6151                .rows(4)
6152                .default_value("aaaa bbbb cccc dddd @alice eeee ffff")
6153        });
6154        view.window_handle
6155            .update(cx, |_, window, cx| {
6156                view.input.update(cx, |state, cx| {
6157                    state
6158                        .replace_range_with_token(
6159                            20..26,
6160                            InlineToken::new("a", "@alice"),
6161                            window,
6162                            cx,
6163                        )
6164                        .unwrap();
6165                    state.set_token_presentation(
6166                        InlineTokenPresentation::default()
6167                            .token(|_, _, _| div().w(px(60.)).h(px(20.))),
6168                    );
6169                });
6170            })
6171            .unwrap();
6172        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6173        visual.update(|window, cx| window.draw(cx).clear(cx));
6174        let (placed, ranged, line_height) = view.input.read_with(&visual, |state, _| {
6175            (
6176                state
6177                    .token_bounds
6178                    .get(&20)
6179                    .copied()
6180                    .expect("placed token bounds"),
6181                state.range_to_bounds(&(20..26)),
6182                state.last_layout.as_ref().unwrap().line_height,
6183            )
6184        });
6185        // The laid-out element always occupies exactly one row of height, even
6186        // when the range-extent path resolves the same end boundary onto the
6187        // next visual row at a soft-wrap edge.
6188        assert!(placed.size.height <= line_height + px(1.), "{placed:?}");
6189        assert!(
6190            placed.size.width <= px(61.) && placed.size.width > px(0.),
6191            "{placed:?}"
6192        );
6193        if let Some(ranged) = ranged {
6194            assert!(
6195                ranged.size.height >= placed.size.height - px(1.),
6196                "{ranged:?} vs {placed:?}"
6197            );
6198        }
6199    }
6200
6201    #[gpui::test]
6202    fn test_inline_token_hover_same_offset_replacement_exits_predecessor(cx: &mut TestAppContext) {
6203        use crate::input::{InlineToken, InlineTokenPresentation};
6204        use std::{cell::RefCell, rc::Rc};
6205        cx.update(crate::init);
6206        let view = InputView::build(cx, |state| state.default_value("@alice!"));
6207        let events = Rc::new(RefCell::new(Vec::new()));
6208        let sink = events.clone();
6209        view.window_handle
6210            .update(cx, |_, window, cx| {
6211                view.input.update(cx, |state, cx| {
6212                    state
6213                        .replace_range_with_token(0..6, InlineToken::new("a", "@alice"), window, cx)
6214                        .unwrap();
6215                    state.set_token_presentation(
6216                        InlineTokenPresentation::default()
6217                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6218                            .on_token_hover(move |event, _, _| {
6219                                sink.borrow_mut()
6220                                    .push((event.token().id().clone(), event.is_hovered()));
6221                            }),
6222                    );
6223                });
6224            })
6225            .unwrap();
6226        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6227        visual.update(|window, cx| window.draw(cx).clear(cx));
6228        let bounds = view
6229            .input
6230            .read_with(&visual, |state, _| state.token_bounds[&0]);
6231        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6232        visual.run_until_parked();
6233        visual.update(|window, cx| window.draw(cx).clear(cx));
6234        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6235
6236        view.window_handle
6237            .update(cx, |_, window, cx| {
6238                view.input.update(cx, |state, cx| {
6239                    state
6240                        .replace_range_with_token(0..6, InlineToken::new("b", "@alice"), window, cx)
6241                        .unwrap();
6242                });
6243            })
6244            .unwrap();
6245        visual.run_until_parked();
6246        visual.update(|window, cx| window.draw(cx).clear(cx));
6247        visual.simulate_mouse_move(
6248            bounds.center() + gpui::point(px(1.), px(0.)),
6249            None,
6250            gpui::Modifiers::default(),
6251        );
6252        visual.run_until_parked();
6253        visual.update(|window, cx| window.draw(cx).clear(cx));
6254        assert_eq!(
6255            events.borrow().as_slice(),
6256            &[("a".into(), true), ("a".into(), false), ("b".into(), true)]
6257        );
6258        // Disabling keeps the token mounted; re-enabling must reset GPUI's
6259        // retained hover state even with a stationary pointer.
6260        view.input
6261            .update(&mut visual, |state, cx| state.set_disabled(true, cx));
6262        visual.update(|window, cx| window.draw(cx).clear(cx));
6263        visual.run_until_parked();
6264        assert_eq!(events.borrow().last(), Some(&("b".into(), false)));
6265        view.input
6266            .update(&mut visual, |state, cx| state.set_disabled(false, cx));
6267        visual.update(|window, cx| window.draw(cx).clear(cx));
6268        visual.run_until_parked();
6269        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6270        visual.run_until_parked();
6271        assert_eq!(
6272            events.borrow().as_slice(),
6273            &[
6274                ("a".into(), true),
6275                ("a".into(), false),
6276                ("b".into(), true),
6277                ("b".into(), false),
6278                ("b".into(), true)
6279            ]
6280        );
6281        visual.simulate_mouse_move(
6282            bounds.bottom_right() + gpui::point(px(10.), px(10.)),
6283            None,
6284            gpui::Modifiers::default(),
6285        );
6286        visual.run_until_parked();
6287        assert_eq!(
6288            events.borrow().as_slice(),
6289            &[
6290                ("a".into(), true),
6291                ("a".into(), false),
6292                ("b".into(), true),
6293                ("b".into(), false),
6294                ("b".into(), true),
6295                ("b".into(), false)
6296            ]
6297        );
6298    }
6299
6300    #[gpui::test]
6301    fn test_inline_token_hover_older_exit_keeps_newer_snapshot(cx: &mut TestAppContext) {
6302        use crate::input::{InlineToken, InlineTokenPresentation};
6303        use gpui::{Bounds, point, px, size};
6304        cx.update(crate::init);
6305        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6306        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6307        view.window_handle
6308            .update(cx, |_, window, cx| {
6309                view.input.update(cx, |state, cx| {
6310                    state
6311                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6312                        .unwrap();
6313                    state
6314                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6315                        .unwrap();
6316                    state.set_token_presentation(
6317                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6318                    );
6319                    // The pointer moves A -> B; GPUI dispatches B's enter
6320                    // before A's exit.
6321                    state
6322                        .token_hover(0, bounds, true, None)
6323                        .expect("hover enters A");
6324                    state
6325                        .token_hover(3, bounds, true, None)
6326                        .expect("hover enters B");
6327                    let (_, exit_a) = state.token_hover(0, bounds, false, None).expect("A exits");
6328                    assert!(!exit_a.is_hovered());
6329                    // B's snapshot must survive A's late exit.
6330                    assert_eq!(
6331                        state
6332                            .hovered_token
6333                            .as_ref()
6334                            .expect("B still hovered")
6335                            .span
6336                            .token()
6337                            .id()
6338                            .as_ref(),
6339                        "b"
6340                    );
6341                    // Removing B afterwards still produces B's reconciled exit.
6342                    state.set_value("no tokens", window, cx);
6343                    state.token_bounds.clear();
6344                    let (listener, exit_b) = state.reconcile_token_hover().expect("B must exit");
6345                    assert!(!exit_b.is_hovered());
6346                    assert_eq!(exit_b.token().id().as_ref(), "b");
6347                    drop(listener);
6348                });
6349            })
6350            .unwrap();
6351    }
6352
6353    #[gpui::test]
6354    fn test_inline_token_hover_late_exit_matches_replaced_token(cx: &mut TestAppContext) {
6355        use crate::input::{InlineToken, InlineTokenPresentation};
6356        cx.update(crate::init);
6357        let view = InputView::build(cx, |state| state.default_value("@a"));
6358        view.window_handle
6359            .update(cx, |_, window, cx| {
6360                view.input.update(cx, |state, cx| {
6361                    let a = InlineToken::new("a", "@a");
6362                    let b = InlineToken::new("b", "@a");
6363                    state
6364                        .replace_range_with_token(0..2, a.clone(), window, cx)
6365                        .unwrap();
6366                    state.set_token_presentation(
6367                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6368                    );
6369                    let bounds = gpui::Bounds::default();
6370                    state.token_hover(0, bounds, true, Some(&a)).unwrap();
6371                    state
6372                        .replace_range_with_token(0..2, b.clone(), window, cx)
6373                        .unwrap();
6374                    state.token_hover(0, bounds, true, Some(&b)).unwrap();
6375                    let (_, exit_a) = state.token_hover(0, bounds, false, Some(&a)).unwrap();
6376                    assert_eq!(exit_a.token().id().as_ref(), "a");
6377                    assert_eq!(state.hovered_token.as_ref().unwrap().span.token(), &b);
6378                    let (_, exit_b) = state.token_hover(0, bounds, false, Some(&b)).unwrap();
6379                    assert_eq!(exit_b.token().id().as_ref(), "b");
6380                    assert!(state.pending_token_hover_exits.is_empty());
6381                });
6382            })
6383            .unwrap();
6384    }
6385
6386    #[gpui::test]
6387    fn test_inline_token_hover_exit_keeps_entry_utf16_after_edit(cx: &mut TestAppContext) {
6388        use crate::input::{InlineToken, InlineTokenPresentation};
6389        use gpui::EntityInputHandler as _;
6390        cx.update(crate::init);
6391        let view = InputView::build(cx, |state| state.default_value("🙂 @a"));
6392        view.window_handle
6393            .update(cx, |_, window, cx| {
6394                view.input.update(cx, |state, cx| {
6395                    state
6396                        .replace_range_with_token(5..7, InlineToken::new("a", "@a"), window, cx)
6397                        .unwrap();
6398                    state.set_token_presentation(
6399                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6400                    );
6401                    let bounds = gpui::Bounds::default();
6402                    let (_, enter) = state.token_hover(5, bounds, true, None).unwrap();
6403                    assert_eq!(enter.range_utf16(), (3, 5));
6404                    state.replace_text_in_range(Some(0..2), "abcd", window, cx);
6405                    assert_eq!(state.token_spans()[0].range(), 5..7);
6406                    let (_, exit) = state.token_hover(5, bounds, false, None).unwrap();
6407                    assert_eq!(exit.range_utf16(), (3, 5));
6408                });
6409            })
6410            .unwrap();
6411    }
6412
6413    #[gpui::test]
6414    fn test_set_selected_text_range(cx: &mut TestAppContext) {
6415        use gpui::EntityInputHandler as _;
6416        cx.update(crate::init);
6417        // "🙂" is 2 UTF-16 units and 4 bytes.
6418        let view = InputView::build(cx, |state| state.default_value("🙂 hello world"));
6419        view.window_handle
6420            .update(cx, |_, window, cx| {
6421                view.input.update(cx, |state, cx| {
6422                    fn selection(
6423                        state: &mut InputBaseState<InputMode>,
6424                        window: &mut Window,
6425                        cx: &mut Context<InputBaseState<InputMode>>,
6426                    ) -> (Range<usize>, bool) {
6427                        let selection = state.selected_text_range(false, window, cx).unwrap();
6428                        (selection.range, selection.reversed)
6429                    }
6430
6431                    state.set_selected_text_range(3..8, window, cx);
6432                    assert_eq!(state.selected_range(), 5..10);
6433                    assert_eq!(selection(state, window, cx), (3..8, false));
6434
6435                    // Dragging the end handle keeps the selection forward.
6436                    state.set_selected_text_range(3..14, window, cx);
6437                    assert_eq!(selection(state, window, cx), (3..14, false));
6438                    assert_eq!(state.cursor(), 16);
6439
6440                    // Dragging the start handle reverses it, so the start is the cursor.
6441                    state.set_selected_text_range(9..14, window, cx);
6442                    assert_eq!(selection(state, window, cx), (9..14, true));
6443                    assert_eq!(state.cursor(), 11);
6444
6445                    // A repeated range keeps its direction.
6446                    state.set_selected_text_range(9..14, window, cx);
6447                    assert_eq!(selection(state, window, cx), (9..14, true));
6448
6449                    // Out of range clamps; a backwards range is normalized.
6450                    state.set_selected_text_range(100..9, window, cx);
6451                    assert_eq!(selection(state, window, cx), (9..14, true));
6452
6453                    // Either handle can cross the stationary end.
6454                    state.set_selected_text_range(3..8, window, cx);
6455                    state.set_selected_text_range(2..3, window, cx);
6456                    assert_eq!(selection(state, window, cx), (2..3, true));
6457                    assert_eq!(state.cursor(), 4);
6458                    state.set_selected_text_range(3..8, window, cx);
6459                    state.set_selected_text_range(8..9, window, cx);
6460                    assert_eq!(selection(state, window, cx), (8..9, false));
6461                    assert_eq!(state.cursor(), 11);
6462
6463                    // Collapsing places a forward cursor and leaves the text alone.
6464                    state.set_selected_text_range(2..2, window, cx);
6465                    assert_eq!(selection(state, window, cx), (2..2, false));
6466                    assert_eq!(state.value(), "🙂 hello world");
6467                });
6468            })
6469            .unwrap();
6470    }
6471
6472    #[gpui::test]
6473    fn test_inline_token_hover_callback_edit_preserves_both_exits(cx: &mut TestAppContext) {
6474        use crate::input::{InlineToken, InlineTokenPresentation};
6475        cx.update(crate::init);
6476        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6477        view.window_handle
6478            .update(cx, |_, window, cx| {
6479                view.input.update(cx, |state, cx| {
6480                    state
6481                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6482                        .unwrap();
6483                    state
6484                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6485                        .unwrap();
6486                    state.set_token_presentation(
6487                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6488                    );
6489                    let bounds = gpui::Bounds::default();
6490                    state.token_hover(0, bounds, true, None).unwrap();
6491                    state.token_hover(3, bounds, true, None).unwrap();
6492                    // Model an edit in B's enter callback before A's queued exit.
6493                    state.set_value("gone", window, cx);
6494                    let (_, exit_a) = state.token_hover(0, bounds, false, None).unwrap();
6495                    assert_eq!(exit_a.token().id().as_ref(), "a");
6496                    let (_, exit_b) = state.reconcile_token_hover().unwrap();
6497                    assert_eq!(exit_b.token().id().as_ref(), "b");
6498                    assert!(state.token_hover(0, bounds, false, None).is_none());
6499                    assert!(state.reconcile_token_hover().is_none());
6500                });
6501            })
6502            .unwrap();
6503    }
6504
6505    #[gpui::test]
6506    fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
6507        let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
6508        view.window_handle
6509            .update(cx, |_, window, cx| {
6510                view.input.update(cx, |state, cx| {
6511                    let token =
6512                        crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
6513                    state
6514                        .replace_range_with_token(4..10, token.clone(), window, cx)
6515                        .unwrap();
6516                    assert_eq!(state.value().as_ref(), "问 @alice!");
6517                    assert_eq!(state.tokens()[0].range(), 4..10);
6518                    assert_eq!(state.next_end_of_word_at(4), 10);
6519                    assert_eq!(state.previous_start_of_word_at(10), 4);
6520                    state.undo(&Undo, window, cx);
6521                    assert!(
6522                        state.tokens().is_empty(),
6523                        "identity-only association is undoable"
6524                    );
6525                    assert_eq!(state.value().as_ref(), "问 @alice!");
6526                    state.redo(&Redo, window, cx);
6527                    assert_eq!(state.tokens()[0].token(), &token);
6528                    state.set_selected_range(6..7, cx);
6529                    assert_eq!(state.selected_range(), 4..10);
6530                    state.replace("", window, cx);
6531                    assert_eq!(state.value().as_ref(), "问 !");
6532                    assert!(state.tokens().is_empty());
6533                    state.undo(&Undo, window, cx);
6534                    assert_eq!(state.tokens()[0].token(), &token);
6535                    state.set_selected_range(0..0, cx);
6536                    state.replace("🙂", window, cx);
6537                    assert_eq!(state.tokens()[0].range(), 8..14);
6538                    state.undo(&Undo, window, cx);
6539                    assert_eq!(state.tokens()[0].range(), 4..10);
6540                    let before = state.content();
6541                    state
6542                        .replace_range_with_token(0..0, token.clone(), window, cx)
6543                        .expect("the same reference may occur twice");
6544                    assert_eq!(state.value().as_ref(), "@alice问 @alice!");
6545                    assert_eq!(state.tokens().len(), 2);
6546                    assert_eq!(state.tokens()[1].token(), &token);
6547                    state.undo(&Undo, window, cx);
6548                    assert_eq!(state.content(), before);
6549                    state.set_value(before.text().clone(), window, cx);
6550                    assert!(state.tokens().is_empty());
6551                    assert!(!state.undo_manager.has_undos());
6552                });
6553            })
6554            .unwrap();
6555    }
6556
6557    #[gpui::test]
6558    fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
6559        use crate::input::{InlineToken, InlineTokenError, InputContent};
6560        let view = InputView::build_textarea(cx, |state| state);
6561        view.window_handle
6562            .update(cx, |_, window, cx| {
6563                view.input.update(cx, |state, cx| {
6564                    let content = InputContent::new("@a@b\n后面")
6565                        .with_token(0..2, InlineToken::new("a", "@a"))
6566                        .unwrap()
6567                        .with_token(2..4, InlineToken::new("b", "@b"))
6568                        .unwrap();
6569                    state.set_value(content.clone(), window, cx);
6570                    state.set_selected_range(2..2, cx);
6571                    assert_eq!(state.previous_boundary(2), 0);
6572                    assert_eq!(state.next_boundary(2), 4);
6573                    state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
6574                    assert_eq!(state.value().as_ref(), "中@b\n后面");
6575                    assert_eq!(state.tokens().len(), 1);
6576                    assert_eq!(
6577                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6578                        Err(InlineTokenError::CompositionActive)
6579                    );
6580                    state.replace_text_in_range(None, "中文", window, cx);
6581                    state.undo(&Undo, window, cx);
6582                    assert_eq!(state.content(), content);
6583                    state.redo(&Redo, window, cx);
6584                    assert_eq!(state.value().as_ref(), "中文@b\n后面");
6585                    state.undo(&Undo, window, cx);
6586                    state.replace_all("plain", window, cx);
6587                    assert!(state.tokens().is_empty());
6588                    state.undo(&Undo, window, cx);
6589                    assert_eq!(state.content(), content);
6590                });
6591            })
6592            .unwrap();
6593        let view = InputView::build(cx, |state| state);
6594        view.window_handle
6595            .update(cx, |_, window, cx| {
6596                view.input.update(cx, |state, cx| {
6597                    assert_eq!(
6598                        InputContent::new("a\u{301}")
6599                            .with_token(0..1, InlineToken::new("bad", "a"))
6600                            .err(),
6601                        Some(InlineTokenError::InvalidBoundary)
6602                    );
6603                    assert_eq!(
6604                        InputContent::new("@a@a")
6605                            .with_token(0..2, InlineToken::new("a", "@a"))
6606                            .unwrap()
6607                            .with_token(1..3, InlineToken::new("x", "a@"))
6608                            .err(),
6609                        Some(InlineTokenError::OverlappingTokens)
6610                    );
6611                    state
6612                        .replace_with_token(InlineToken::new("a", "@a"), window, cx)
6613                        .unwrap();
6614                    let before = state.content();
6615                    state.set_masked(true, window, cx);
6616                    assert!(!state.tokens_visible());
6617                    assert_eq!(
6618                        state.replace_with_token(InlineToken::new("b", "b"), window, cx),
6619                        Err(InlineTokenError::UnsupportedMode)
6620                    );
6621                    assert_eq!(state.content(), before);
6622                    state.undo(&Undo, window, cx);
6623                    assert!(state.tokens().is_empty());
6624                    state.redo(&Redo, window, cx);
6625                    assert_eq!(state.content(), before);
6626                    assert!(!state.tokens_visible());
6627                });
6628            })
6629            .unwrap();
6630    }
6631
6632    use crate::theme::Theme;
6633    use gpui::{TestAppContext, VisualTestContext, size};
6634
6635    use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TabSize, TextareaMode};
6636
6637    fn set_test_syntax_provider(
6638        provider: Rc<dyn crate::input::SyntaxContextProvider>,
6639        cx: &mut App,
6640    ) {
6641        struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
6642        impl crate::input::LanguageProvider for TestLanguages {
6643            fn syntax_context_provider(
6644                &self,
6645                _: &str,
6646            ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
6647                Some(self.0.clone())
6648            }
6649        }
6650        crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
6651    }
6652
6653    struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
6654
6655    impl<M: InputModeKind> Render for TestRoot<M> {
6656        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6657            div().size_full().child(self.0.clone())
6658        }
6659    }
6660
6661    struct InputView<M: InputModeKind> {
6662        input: Entity<InputBaseState<M>>,
6663        window_handle: gpui::WindowHandle<TestRoot<M>>,
6664    }
6665
6666    /// Helper to open a state of one mode in a window for testing.
6667    impl<M: InputModeKind> InputView<M> {
6668        fn build_with(
6669            cx: &mut TestAppContext,
6670            make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
6671            + 'static,
6672        ) -> Self {
6673            let mut input: Option<Entity<InputBaseState<M>>> = None;
6674
6675            let window = cx.update(|cx| {
6676                cx.open_window(Default::default(), |window, cx| {
6677                    // Set up the theme first
6678                    cx.set_global(Theme::default());
6679                    // Initialize input keybindings
6680                    super::super::init(cx);
6681
6682                    input = Some(cx.new(|cx| make(window, cx)));
6683
6684                    cx.new(|_| TestRoot(input.clone().unwrap()))
6685                })
6686                .unwrap()
6687            });
6688
6689            Self {
6690                input: input.unwrap(),
6691                window_handle: window,
6692            }
6693        }
6694    }
6695
6696    impl InputView<EditorMode> {
6697        /// An editor state, for the tests that exercise code-editor behavior.
6698        fn new(cx: &mut TestAppContext) -> Self {
6699            Self::build_editor(cx, |state| state)
6700        }
6701
6702        fn build_editor(
6703            cx: &mut TestAppContext,
6704            f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
6705        ) -> Self {
6706            Self::build_with(cx, move |window, cx| {
6707                f(crate::input::EditorState::new(window, cx).language("sql"))
6708            })
6709        }
6710    }
6711
6712    impl InputView<TextareaMode> {
6713        fn build_textarea(
6714            cx: &mut TestAppContext,
6715            f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
6716        ) -> Self {
6717            Self::build_with(cx, move |window, cx| {
6718                f(crate::input::TextareaState::new(window, cx))
6719            })
6720        }
6721    }
6722
6723    impl InputView<InputMode> {
6724        /// A single-line state, the default these tests were written against.
6725        fn build(
6726            cx: &mut TestAppContext,
6727            f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
6728        ) -> Self {
6729            Self::build_with(cx, move |window, cx| {
6730                f(crate::input::InputState::new(window, cx))
6731            })
6732        }
6733    }
6734
6735    /// Sends one trackpad packet straight to the input.
6736    fn swipe<M: InputModeKind>(
6737        view: &InputView<M>,
6738        cx: &mut VisualTestContext,
6739        dy: f32,
6740        phase: gpui::TouchPhase,
6741    ) {
6742        cx.update(|window, cx| {
6743            view.input.update(cx, |state, cx| {
6744                state.on_scroll_wheel(
6745                    &ScrollEvent {
6746                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(dy))),
6747                        touch_phase: phase,
6748                        ..Default::default()
6749                    },
6750                    window,
6751                    cx,
6752                )
6753            })
6754        });
6755    }
6756
6757    fn long_text() -> String {
6758        (0..60)
6759            .map(|n| format!("line {n}"))
6760            .collect::<Vec<_>>()
6761            .join("\n")
6762    }
6763
6764    #[gpui::test]
6765    fn test_scroll_bounce_stretches_past_the_end_and_springs_back(cx: &mut TestAppContext) {
6766        use gpui::TouchPhase::{Ended, Moved, Started};
6767
6768        let view = InputView::build_textarea(cx, |state| {
6769            state.scroll_bounce(true).default_value(long_text())
6770        });
6771        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6772        cx.update(|window, cx| window.draw(cx).clear(cx));
6773        let drawn_at = |cx: &mut VisualTestContext| {
6774            view.input
6775                .read_with(cx, |state, _| state.last_bounds.unwrap().origin.y)
6776        };
6777
6778        swipe(&view, &mut cx, -20., Started);
6779        swipe(&view, &mut cx, -100_000., Moved);
6780        let (end, stretch) = view.input.read_with(&cx, |state, _| {
6781            (state.scroll_handle.offset().y, state.overscroll.offset())
6782        });
6783        assert!(end < px(0.), "the text scrolled to its end");
6784        assert!(stretch < 0., "the rest stretched the edge: {stretch}");
6785        cx.update(|window, cx| window.draw(cx).clear(cx));
6786        let stretched_at = drawn_at(&mut cx);
6787
6788        swipe(&view, &mut cx, 0., Ended);
6789        for _ in 0..120 {
6790            cx.executor()
6791                .advance_clock(std::time::Duration::from_millis(16));
6792            cx.update(|window, cx| window.draw(cx).clear(cx));
6793        }
6794        view.input.read_with(&cx, |state, _| {
6795            assert_eq!(state.overscroll.offset(), 0., "the edge sprang back");
6796            assert_eq!(
6797                state.scroll_handle.offset().y,
6798                end,
6799                "scrolling stayed exact"
6800            );
6801        });
6802        let moved = (stretched_at - drawn_at(&mut cx)).as_f32();
6803        assert!(
6804            (moved - stretch).abs() < 0.001,
6805            "the stretch only moved where the text was drawn: {moved} vs {stretch}"
6806        );
6807    }
6808
6809    /// Swipes far past the end of the text and returns where the text
6810    /// scrolled to and how far its edge stretched.
6811    fn swipe_past_the_end(
6812        view: &InputView<TextareaMode>,
6813        cx: &mut VisualTestContext,
6814    ) -> (Pixels, f32) {
6815        use gpui::TouchPhase::{Moved, Started};
6816
6817        cx.update(|window, cx| window.draw(cx).clear(cx));
6818        swipe(view, cx, -20., Started);
6819        swipe(view, cx, -100_000., Moved);
6820        view.input.read_with(cx, |state, _| {
6821            (state.scroll_handle.offset().y, state.overscroll.offset())
6822        })
6823    }
6824
6825    #[gpui::test]
6826    fn test_scroll_bounce_stays_put_under_reduced_motion(cx: &mut TestAppContext) {
6827        cx.update(|cx| cx.set_reduce_motion(true));
6828        let view = InputView::build_textarea(cx, |state| {
6829            state.scroll_bounce(true).default_value(long_text())
6830        });
6831        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6832        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6833        assert!(end < px(0.), "the text still scrolls");
6834        assert_eq!(stretch, 0., "the edge does not stretch");
6835    }
6836
6837    #[gpui::test]
6838    fn test_scroll_bounce_follows_the_platform_by_default(cx: &mut TestAppContext) {
6839        let view = InputView::build_textarea(cx, |state| state.default_value(long_text()));
6840        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6841        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6842        assert!(end < px(0.), "the text scrolls");
6843        assert_eq!(
6844            stretch != 0.,
6845            crate::ScrollBounce::enabled_by_default(),
6846            "the edge stretches where the platform's scroll views do"
6847        );
6848    }
6849
6850    #[gpui::test]
6851    fn test_scroll_bounce_leaves_text_that_fits(cx: &mut TestAppContext) {
6852        let view = InputView::build_textarea(cx, |state| {
6853            state.scroll_bounce(true).default_value("one line")
6854        });
6855        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6856        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6857        assert_eq!((end, stretch), (px(0.), 0.));
6858    }
6859
6860    #[gpui::test]
6861    fn test_scroll_bounce_resets_when_replacement_text_fits(cx: &mut TestAppContext) {
6862        let view = InputView::build_textarea(cx, |state| {
6863            state.scroll_bounce(true).default_value(long_text())
6864        });
6865        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6866        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6867        assert!(stretch < 0.);
6868        cx.update(|window, cx| {
6869            view.input
6870                .update(cx, |state, cx| state.set_value("short", window, cx));
6871            window.draw(cx).clear(cx);
6872        });
6873        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
6874        view.input.read_with(&cx, |state, _| {
6875            assert_eq!(state.overscroll.offset(), 0.);
6876            assert_eq!(state.scroll_handle.offset().y, px(0.));
6877        });
6878    }
6879
6880    #[gpui::test]
6881    fn test_scroll_bounce_releases_when_the_end_packet_is_horizontal(cx: &mut TestAppContext) {
6882        let view = InputView::build_textarea(cx, |state| {
6883            state.scroll_bounce(true).default_value(long_text())
6884        });
6885        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6886        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6887        assert!(stretch < 0.);
6888        cx.update(|window, cx| {
6889            view.input.update(cx, |state, cx| {
6890                state.on_scroll_wheel(
6891                    &ScrollEvent {
6892                        delta: gpui::ScrollDelta::Pixels(point(px(1.), px(0.))),
6893                        touch_phase: gpui::TouchPhase::Ended,
6894                        ..Default::default()
6895                    },
6896                    window,
6897                    cx,
6898                );
6899            });
6900        });
6901        for _ in 0..120 {
6902            cx.executor()
6903                .advance_clock(std::time::Duration::from_millis(16));
6904            cx.update(|window, cx| window.draw(cx).clear(cx));
6905        }
6906        assert_eq!(
6907            view.input
6908                .read_with(&cx, |state, _| state.overscroll.offset()),
6909            0.
6910        );
6911    }
6912
6913    #[gpui::test]
6914    fn test_scroll_bounce_ordinary_mouse_wheel_does_not_stretch(cx: &mut TestAppContext) {
6915        let view = InputView::build_textarea(cx, |state| {
6916            state.scroll_bounce(true).default_value(long_text())
6917        });
6918        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6919        cx.update(|window, cx| {
6920            window.draw(cx).clear(cx);
6921            view.input.update(cx, |state, cx| {
6922                state.on_scroll_wheel(
6923                    &ScrollEvent {
6924                        delta: gpui::ScrollDelta::Lines(point(0., -100_000.)),
6925                        touch_phase: gpui::TouchPhase::Moved,
6926                        ..Default::default()
6927                    },
6928                    window,
6929                    cx,
6930                );
6931                assert!(state.scroll_handle.offset().y < px(0.));
6932                assert_eq!(state.overscroll.offset(), 0.);
6933            });
6934        });
6935    }
6936
6937    #[gpui::test]
6938    fn test_scroll_bounce_new_wheel_input_interrupts_the_return(cx: &mut TestAppContext) {
6939        let view = InputView::build_textarea(cx, |state| {
6940            state.scroll_bounce(true).default_value(long_text())
6941        });
6942        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6943        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
6944        assert!(stretch < 0.);
6945        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
6946        cx.executor()
6947            .advance_clock(std::time::Duration::from_millis(16));
6948        cx.update(|window, cx| {
6949            window.draw(cx).clear(cx);
6950            view.input.update(cx, |state, cx| {
6951                state.on_scroll_wheel(
6952                    &ScrollEvent {
6953                        delta: gpui::ScrollDelta::Lines(point(0., 2.)),
6954                        touch_phase: gpui::TouchPhase::Moved,
6955                        ..Default::default()
6956                    },
6957                    window,
6958                    cx,
6959                );
6960                assert!(state.scroll_handle.offset().y > end);
6961                assert_eq!(state.overscroll.offset(), 0.);
6962            });
6963        });
6964    }
6965
6966    #[gpui::test]
6967    fn test_turning_scroll_bounce_off_drops_the_stretch(cx: &mut TestAppContext) {
6968        let view = InputView::build_textarea(cx, |state| {
6969            state.scroll_bounce(true).default_value(long_text())
6970        });
6971        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6972        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
6973        assert!(stretch < 0., "the edge stretched: {stretch}");
6974        view.input
6975            .update(&mut cx, |state, cx| state.set_scroll_bounce(false, cx));
6976        assert_eq!(
6977            view.input
6978                .read_with(&cx, |state, _| state.overscroll.offset()),
6979            0.
6980        );
6981    }
6982
6983    /// The frame is laid out by the application, which should not have to
6984    /// center a single line inside it.
6985    #[gpui::test]
6986    fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
6987        struct Frame(Entity<InputBaseState<InputMode>>);
6988        impl Render for Frame {
6989            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6990                crate::input::InputBase::new("frame")
6991                    .h(px(60.))
6992                    .child(crate::input::Input::new(&self.0))
6993            }
6994        }
6995
6996        cx.update(crate::init);
6997        let mut input = None;
6998        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6999            let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
7000            input = Some(state.clone());
7001            Frame(state)
7002        });
7003        let input = input.unwrap();
7004        let mut cx = VisualTestContext::from_window(window.into(), cx);
7005        cx.update(|window, cx| window.draw(cx).clear(cx));
7006
7007        input.read_with(&cx, |state, _| {
7008            let line = state.input_bounds;
7009            assert_eq!(line.center().y, px(30.), "line {line:?}");
7010        });
7011    }
7012
7013    #[gpui::test]
7014    fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
7015        use std::{cell::Cell, rc::Rc};
7016
7017        cx.update(crate::init);
7018        let mut input = None;
7019        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7020            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7021            gpui::EmptyView
7022        });
7023        let input = input.unwrap();
7024        input.update(cx, |state, cx| {
7025            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7026            state.scroll_size = size(px(100.), px(20.));
7027            state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
7028        });
7029        let notifications = Rc::new(Cell::new(0));
7030        let count = notifications.clone();
7031        let _subscription =
7032            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7033
7034        window
7035            .update(cx, |_, window, cx| {
7036                input.update(cx, |state, cx| {
7037                    state.on_scroll_wheel(
7038                        &ScrollEvent {
7039                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7040                            ..Default::default()
7041                        },
7042                        window,
7043                        cx,
7044                    );
7045                    assert_eq!(state.scroll_handle.offset(), Point::default());
7046                    assert!(state.diagnostic_popover().is_none());
7047                });
7048            })
7049            .unwrap();
7050        assert_eq!(
7051            notifications.get(),
7052            1,
7053            "clearing a diagnostic must notify even when scrolling is clamped"
7054        );
7055        window
7056            .update(cx, |_, window, cx| {
7057                input.update(cx, |state, cx| {
7058                    state.on_scroll_wheel(
7059                        &ScrollEvent {
7060                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7061                            ..Default::default()
7062                        },
7063                        window,
7064                        cx,
7065                    );
7066                });
7067            })
7068            .unwrap();
7069        assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
7070    }
7071
7072    /// Hover must reach the whole visible editor after scrolling, not only
7073    /// the part that overlaps the unscrolled text bounds.
7074    #[gpui::test]
7075    fn test_hover_reaches_bottom_of_scrolled_editor(cx: &mut TestAppContext) {
7076        use crate::input::{Diagnostic, Position};
7077        struct Frame(Entity<crate::input::EditorState>);
7078        impl Render for Frame {
7079            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7080                crate::input::InputBase::new("frame")
7081                    .h(px(100.))
7082                    .child(crate::input::Editor::new(&self.0))
7083            }
7084        }
7085
7086        cx.update(crate::init);
7087        let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
7088        let mut input = None;
7089        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7090            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
7091            input = Some(state.clone());
7092            Frame(state)
7093        });
7094        let input = input.unwrap();
7095        let mut cx = VisualTestContext::from_window(window.into(), cx);
7096        input.update(&mut cx, |state, _| {
7097            state.diagnostics_mut().unwrap().push(Diagnostic::new(
7098                Position::new(0, 0)..Position::new(100, 0),
7099                "everywhere",
7100            ));
7101        });
7102        cx.update(|window, cx| window.draw(cx).clear(cx));
7103        cx.update(|window, cx| {
7104            input.update(cx, |state, cx| {
7105                state.on_scroll_wheel(
7106                    &ScrollEvent {
7107                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-400.))),
7108                        ..Default::default()
7109                    },
7110                    window,
7111                    cx,
7112                );
7113            })
7114        });
7115        cx.update(|window, cx| window.draw(cx).clear(cx));
7116
7117        let bounds = input.read_with(&cx, |state, _| state.input_bounds);
7118        cx.simulate_mouse_move(
7119            point(bounds.center().x, bounds.bottom() - px(5.)),
7120            None,
7121            gpui::Modifiers::default(),
7122        );
7123        assert!(
7124            input.read_with(&cx, |state, _| state.diagnostic_popover().is_some()),
7125            "no hover at the bottom of a scrolled editor, bounds {bounds:?}"
7126        );
7127    }
7128
7129    #[gpui::test]
7130    fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
7131        use std::{cell::Cell, rc::Rc};
7132        struct Panel {
7133            input: Entity<crate::input::EditorState>,
7134            observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
7135        }
7136        impl Render for Panel {
7137            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7138                self.observed.set(self.input.read(cx).cursor_layout());
7139                div().size_full().child(self.input.clone())
7140            }
7141        }
7142        struct Root(Entity<Panel>);
7143        impl Render for Root {
7144            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7145                div().size_full().child(
7146                    self.0
7147                        .clone()
7148                        .cached(gpui::StyleRefinement::default().size_full()),
7149                )
7150            }
7151        }
7152        cx.update(crate::init);
7153        let observed = Rc::new(Cell::new(None));
7154        let mut input = None;
7155        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7156            let state = cx.new(|cx| {
7157                let mut state = crate::input::EditorState::new(window, cx);
7158                state.set_value("abcdefgh", window, cx);
7159                state
7160            });
7161            input = Some(state.clone());
7162            Root(cx.new(|_| Panel {
7163                input: state,
7164                observed: observed.clone(),
7165            }))
7166        });
7167        cx.run_until_parked();
7168        let input = input.unwrap();
7169        let before = input.read_with(cx, |state, _| state.cursor_layout());
7170        // The caret geometry only exists once the input has painted, and a
7171        // notify sent from inside a draw marks the view dirty without asking
7172        // for another frame, so the consumer reads the geometry on the next
7173        // invalidation rather than during the paint that produced it.
7174        input.update(cx, |_, cx| cx.notify());
7175        cx.run_until_parked();
7176        assert_eq!(observed.get(), before);
7177        window
7178            .update(cx, |_, _, cx| {
7179                input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
7180            })
7181            .unwrap();
7182        cx.run_until_parked();
7183        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7184        let after = input.read_with(cx, |state, _| state.cursor_layout());
7185        assert_ne!(after, before, "the caret must actually move");
7186        assert_eq!(
7187            observed.get(),
7188            after,
7189            "render consumers must receive the newly painted caret geometry"
7190        );
7191    }
7192
7193    #[gpui::test]
7194    fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
7195        use std::{cell::Cell, rc::Rc};
7196
7197        cx.update(crate::init);
7198        let mut input = None;
7199        let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7200            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7201            gpui::EmptyView
7202        });
7203        let input = input.unwrap();
7204        let notifications = Rc::new(Cell::new(0));
7205        let count = notifications.clone();
7206        let _subscription =
7207            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7208
7209        input.update(cx, |state, _| {
7210            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7211            state.scroll_size = size(px(300.), px(20.));
7212        });
7213        for target in [
7214            None,
7215            Some(point(px(0.), px(0.))),
7216            Some(point(px(20.), px(50.))),
7217        ] {
7218            input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
7219            assert_eq!(
7220                notifications.get(),
7221                0,
7222                "an unchanged clamped offset must stay quiet"
7223            );
7224        }
7225        input.update(cx, |state, cx| {
7226            state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
7227            assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
7228        });
7229        assert_eq!(notifications.get(), 1, "a scroll must notify");
7230        input.update(cx, |state, cx| {
7231            state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
7232            assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
7233        });
7234        assert_eq!(notifications.get(), 2);
7235        input.update(cx, |state, cx| {
7236            state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
7237        });
7238        assert_eq!(
7239            notifications.get(),
7240            2,
7241            "clamping to the current offset must stay quiet"
7242        );
7243        input.update(cx, |state, cx| {
7244            state.scroll_size.width = px(110.);
7245            state.update_scroll_offset(None, cx);
7246            assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
7247        });
7248        assert_eq!(
7249            notifications.get(),
7250            3,
7251            "a smaller scroll range must clamp and notify"
7252        );
7253    }
7254
7255    #[gpui::test]
7256    fn test_set_line_number_notifies_only_on_change(cx: &mut TestAppContext) {
7257        use std::{cell::Cell, rc::Rc};
7258
7259        cx.update(crate::init);
7260        let mut input = None;
7261        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7262            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7263            gpui::EmptyView
7264        });
7265        let input = input.unwrap();
7266        let shown = input.read_with(cx, |state, _| state.mode.line_number());
7267        let notifications = Rc::new(Cell::new(0));
7268        let count = notifications.clone();
7269        let _subscription =
7270            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7271
7272        window
7273            .update(cx, |_, window, cx| {
7274                input.update(cx, |state, cx| state.set_line_number(shown, window, cx))
7275            })
7276            .unwrap();
7277        assert_eq!(notifications.get(), 0);
7278
7279        window
7280            .update(cx, |_, window, cx| {
7281                input.update(cx, |state, cx| state.set_line_number(!shown, window, cx))
7282            })
7283            .unwrap();
7284        assert_eq!(notifications.get(), 1);
7285        assert_eq!(
7286            input.read_with(cx, |state, _| state.mode.line_number()),
7287            !shown
7288        );
7289    }
7290
7291    #[gpui::test]
7292    fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
7293        use std::{cell::Cell, rc::Rc};
7294
7295        cx.update(crate::init);
7296        let mut input = None;
7297        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7298            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7299            gpui::EmptyView
7300        });
7301        let input = input.unwrap();
7302        cx.run_until_parked();
7303
7304        let notifications = Rc::new(Cell::new(0));
7305        let count = notifications.clone();
7306        let _subscription =
7307            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7308        cx.run_until_parked();
7309
7310        // Seeding a form is a write, so it notifies once. The input is not
7311        // focused and draws no caret, so nothing may notify after that.
7312        window
7313            .update(cx, |_, window, cx| {
7314                input.update(cx, |state, cx| state.set_value("seeded", window, cx));
7315            })
7316            .unwrap();
7317        cx.run_until_parked();
7318        let settled = notifications.get();
7319
7320        cx.executor()
7321            .advance_clock(std::time::Duration::from_secs(3));
7322        cx.run_until_parked();
7323
7324        assert_eq!(
7325            notifications.get(),
7326            settled,
7327            "an unfocused input is blinking, and every blink repaints the view it is in"
7328        );
7329    }
7330
7331    #[gpui::test]
7332    fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
7333        use std::{cell::Cell, rc::Rc};
7334
7335        struct Panel {
7336            input: Entity<crate::input::InputState>,
7337            renders: Rc<Cell<usize>>,
7338        }
7339        impl Render for Panel {
7340            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7341                self.renders.set(self.renders.get() + 1);
7342                div().size_full().child(self.input.clone())
7343            }
7344        }
7345        struct Root(Entity<Panel>);
7346        impl Render for Root {
7347            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7348                div().size_full().child(
7349                    self.0
7350                        .clone()
7351                        .cached(gpui::StyleRefinement::default().size_full()),
7352                )
7353            }
7354        }
7355
7356        cx.update(crate::init);
7357        let renders = Rc::new(Cell::new(0));
7358        let mut input = None;
7359        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7360            let state = cx.new(|cx| crate::input::InputState::new(window, cx));
7361            input = Some(state.clone());
7362            Root(cx.new(|_| Panel {
7363                input: state,
7364                renders: renders.clone(),
7365            }))
7366        });
7367        cx.run_until_parked();
7368        let before = renders.get();
7369        assert!(before > 0);
7370        for _ in 0..60 {
7371            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7372        }
7373        assert_eq!(
7374            renders.get(),
7375            before,
7376            "an idle input must not invalidate its cached parent"
7377        );
7378
7379        let input = input.unwrap();
7380        window
7381            .update(cx, |_, window, cx| {
7382                input.update(cx, |state, cx| state.set_value("changed", window, cx));
7383            })
7384            .unwrap();
7385        assert!(
7386            renders.get() > before,
7387            "text changes must invalidate the parent"
7388        );
7389        // The first paint reports the changed text extent to layout consumers.
7390        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7391        let before = renders.get();
7392        for _ in 0..60 {
7393            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7394        }
7395        assert_eq!(renders.get(), before, "the edited input must settle again");
7396
7397        cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
7398        cx.run_until_parked();
7399        assert!(renders.get() > before, "resizing must invalidate layout");
7400    }
7401
7402    #[gpui::test]
7403    fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
7404        cx.update(crate::init);
7405        let view = InputView::build_textarea(cx, |state| state);
7406        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7407        cx.update(|window, cx| {
7408            view.input.update(cx, |state, cx| {
7409                for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
7410                    state.set_value(original, window, cx);
7411                    let newline = original.find('\n').unwrap();
7412                    let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
7413                        newline - 1
7414                    } else {
7415                        newline
7416                    };
7417                    state.end(&MoveEnd, window, cx);
7418                    assert_eq!(state.cursor(), end);
7419                    state.right(&MoveRight, window, cx);
7420                    assert_eq!(state.cursor(), newline + 1);
7421                    state.left(&MoveLeft, window, cx);
7422                    assert_eq!(state.cursor(), end);
7423                    state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
7424                    assert_eq!(state.selected_range(), end..end);
7425                    state.move_to_end(&MoveToEnd, window, cx);
7426                    assert_eq!(state.cursor(), original.len());
7427                    state.move_to_start(&MoveToStart, window, cx);
7428                    assert_eq!(state.cursor(), 0);
7429                    assert_eq!(state.value().as_bytes(), original.as_bytes());
7430                }
7431                // A lone CR is an ordinary character; it must not skip its neighbour.
7432                state.set_value("a\rb", window, cx);
7433                state.right(&MoveRight, window, cx);
7434                assert_eq!(state.cursor(), 1);
7435                state.right(&MoveRight, window, cx);
7436                assert_eq!(state.cursor(), 2);
7437            })
7438        });
7439    }
7440
7441    #[gpui::test]
7442    fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
7443        cx.update(crate::init);
7444
7445        // A single-line input keeps its caret in view by moving its own offset;
7446        // it has no viewport to drag, so a scrollbar in a text field is a
7447        // control that does not exist.
7448        let single = InputView::build(cx, |state| state);
7449        single
7450            .input
7451            .update(cx, |state, _| assert!(!state.shows_scrollbar()));
7452
7453        let multi = InputView::build_textarea(cx, |state| state);
7454        multi
7455            .input
7456            .update(cx, |state, _| assert!(state.shows_scrollbar()));
7457    }
7458
7459    #[gpui::test]
7460    fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
7461        use std::{cell::Cell, rc::Rc};
7462        cx.update(crate::init);
7463        let input_view = InputView::new(cx);
7464        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7465        let input = input_view.input;
7466        let calls = Rc::new(Cell::new(0usize));
7467        let items = Rc::new(Cell::new(0usize));
7468        let menu_focus = cx.update(|_, cx| cx.focus_handle());
7469
7470        cx.update(|window, cx| {
7471            input.update(cx, |state, cx| {
7472                let calls2 = calls.clone();
7473                let items2 = items.clone();
7474                let menu_focus = menu_focus.clone();
7475                state.on_context_menu(Rc::new(move |menu, _, _, window, cx| {
7476                    calls2.set(calls2.get() + 1);
7477                    items2.set(menu.items.len());
7478                    menu_focus.focus(window, cx);
7479                }));
7480                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7481            })
7482        });
7483        assert_eq!(calls.get(), 1);
7484        assert_eq!(items.get(), 0);
7485        input.read_with(&cx, |state, _| {
7486            assert_eq!(
7487                state
7488                    .selection_focus
7489                    .as_ref()
7490                    .and_then(WeakFocusHandle::upgrade)
7491                    .as_ref(),
7492                Some(&menu_focus),
7493                "the menu callback must retain selection without reborrowing its input"
7494            );
7495        });
7496
7497        // A custom handler may keep using the same, already-focused menu.
7498        cx.update(|window, cx| {
7499            input.update(cx, |state, cx| {
7500                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7501            });
7502        });
7503        assert_eq!(calls.get(), 2);
7504        cx.update(|window, cx| {
7505            assert!(input.read(cx).has_selection_focus(window, cx));
7506        });
7507
7508        cx.update(|window, cx| {
7509            input.update(cx, |state, cx| {
7510                state.disabled = true;
7511                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7512            })
7513        });
7514        assert_eq!(calls.get(), 2);
7515    }
7516
7517    #[gpui::test]
7518    fn context_menu_handler_can_read_its_input(cx: &mut TestAppContext) {
7519        use std::{cell::Cell, rc::Rc};
7520        cx.update(crate::init);
7521        let input_view = InputView::new(cx);
7522        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7523        let input = input_view.input;
7524        let cursor = Rc::new(Cell::new(None));
7525
7526        cx.update(|window, cx| {
7527            input.update(cx, |state, cx| {
7528                state.set_value("hello", window, cx);
7529                let weak = cx.weak_entity();
7530                let cursor = cursor.clone();
7531                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7532                    cursor.set(weak.upgrade().map(|input| input.read(cx).cursor()));
7533                }));
7534                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7535            })
7536        });
7537        assert_eq!(cursor.get(), Some(2));
7538    }
7539
7540    #[gpui::test]
7541    fn context_menu_handler_can_read_the_offset_under_the_pointer(cx: &mut TestAppContext) {
7542        use std::{cell::Cell, rc::Rc};
7543        cx.update(crate::init);
7544        let input_view = InputView::new(cx);
7545        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7546        let input = input_view.input;
7547        let seen = Rc::new(Cell::new(None));
7548
7549        cx.update(|window, cx| {
7550            input.update(cx, |state, cx| {
7551                state.set_value("hello world", window, cx);
7552                assert_eq!(state.context_menu_offset(), None);
7553                state.select_all(window, cx);
7554                let weak = cx.weak_entity();
7555                let seen = seen.clone();
7556                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7557                    seen.set(weak.upgrade().map(|input| {
7558                        let input = input.read(cx);
7559                        (input.cursor(), input.context_menu_offset())
7560                    }));
7561                }));
7562                // A right-click inside the selection keeps the cursor at its end.
7563                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7564            })
7565        });
7566        assert_eq!(seen.get(), Some((11, Some(2))));
7567    }
7568
7569    #[gpui::test]
7570    fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
7571        let input_view = InputView::new(cx);
7572        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7573        let input = input_view.input;
7574
7575        cx.update(|window, cx| {
7576            input.update(cx, |state, cx| {
7577                state.set_value("hello", window, cx);
7578                state.set_readonly(true, cx);
7579            });
7580        });
7581
7582        cx.update(|_, cx| {
7583            input.read_with(cx, |state, _| {
7584                assert!(!state.is_editable());
7585                assert!(!state.is_replaceable());
7586            });
7587        });
7588
7589        // Typing (and IME) goes through the input handler, it must be rejected.
7590        cx.update(|window, cx| {
7591            input.update(cx, |state, cx| {
7592                state.replace_text_in_range(None, " world", window, cx);
7593                state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
7594            });
7595        });
7596        cx.update(|_, cx| {
7597            input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
7598        });
7599
7600        // The programmatic APIs are not limited by the readonly mode.
7601        cx.update(|window, cx| {
7602            input.update(cx, |state, cx| {
7603                state.insert(" world", window, cx);
7604                state.set_value("changed", window, cx);
7605            });
7606        });
7607        cx.update(|_, cx| {
7608            input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
7609        });
7610
7611        // And the user can edit again after leaving the readonly mode.
7612        // The caret is at the start, because `set_value` has reset the selection.
7613        cx.update(|window, cx| {
7614            input.update(cx, |state, cx| {
7615                state.set_readonly(false, cx);
7616                state.replace_text_in_range(None, "!", window, cx);
7617            });
7618        });
7619        cx.update(|_, cx| {
7620            input.read_with(cx, |state, _| {
7621                assert!(state.is_editable());
7622                assert_eq!(state.value(), "!changed");
7623            });
7624        });
7625    }
7626
7627    /// Regression test: editing at a caret that sits far outside the viewport
7628    /// must reveal it in one frame. The cursor-follow in `layout_cursors` runs
7629    /// only on the frame the selection changes, so its old one-line step left
7630    /// the caret offscreen after typing at the end of a long paste.
7631    #[gpui::test]
7632    fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
7633        let mut input = None;
7634        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7635            cx.set_global(Theme::default());
7636            super::super::init(cx);
7637            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
7638            input = Some(state.clone());
7639            TestRoot(state)
7640        });
7641        let mut cx = VisualTestContext::from_window(window.into(), cx);
7642        let input = input.unwrap();
7643
7644        let text: String = (1..=100)
7645            .map(|i| format!("line {i}"))
7646            .collect::<Vec<_>>()
7647            .join("\n");
7648        cx.update(|window, cx| {
7649            input.update(cx, |state, cx| {
7650                state.set_value(text, window, cx);
7651                let end = state.text.len();
7652                state.set_selection(end, end);
7653            });
7654        });
7655        cx.run_until_parked();
7656
7657        // The user scrolled back to the top to read the pasted text.
7658        cx.update(|_, cx| {
7659            input.update(cx, |state, cx| {
7660                state.scroll_handle.set_offset(point(px(0.), px(0.)));
7661                cx.notify();
7662            });
7663        });
7664        cx.run_until_parked();
7665
7666        cx.update(|window, cx| {
7667            input.update(cx, |state, cx| {
7668                state.replace_text_in_range(None, "X", window, cx);
7669            });
7670        });
7671        cx.run_until_parked();
7672
7673        cx.update(|_, cx| {
7674            input.read_with(cx, |state, _| {
7675                assert!(state.value().ends_with("line 100X"));
7676                let (caret, _) = state.cursor_layout().expect("caret painted");
7677                let viewport = state.input_bounds();
7678                let scroll_y = state.scroll_handle.offset().y;
7679                let top = caret.origin.y - viewport.origin.y + scroll_y;
7680                assert!(
7681                    top >= px(0.) && top + caret.size.height <= viewport.size.height,
7682                    "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
7683                    viewport.size.height,
7684                );
7685            });
7686        });
7687    }
7688
7689    /// Regression test: changing the auto-grow limits keeps the rows fitted to
7690    /// the text. `set_auto_grow` used to start over at `min_rows`, and the rows
7691    /// were counted again only on the next edit or wrap width change.
7692    #[gpui::test]
7693    fn test_set_auto_grow_keeps_rows_fitted(cx: &mut TestAppContext) {
7694        let mut input = None;
7695        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7696            cx.set_global(Theme::default());
7697            super::super::init(cx);
7698            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 10));
7699            input = Some(state.clone());
7700            TestRoot(state)
7701        });
7702        let mut cx = VisualTestContext::from_window(window.into(), cx);
7703        let input = input.unwrap();
7704
7705        let text: String = (1..=8)
7706            .map(|i| format!("line {i}"))
7707            .collect::<Vec<_>>()
7708            .join("\n");
7709        cx.update(|window, cx| {
7710            input.update(cx, |state, cx| state.set_value(text, window, cx));
7711        });
7712        cx.run_until_parked();
7713        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7714
7715        // A larger maximum keeps all eight rows.
7716        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 12, cx)));
7717        cx.run_until_parked();
7718        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7719
7720        // A smaller maximum caps them.
7721        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 4, cx)));
7722        cx.run_until_parked();
7723        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 4)));
7724    }
7725
7726    /// Regression test: `scroll_to` at end-of-buffer must produce a deferred
7727    /// scroll target within the safe scroll range, so the painted frame
7728    /// matches what `update_scroll_offset` persists (no jitter). A small
7729    /// `cursor_surrounding_lines` override used to mismatch the hardcoded
7730    /// 3-line edge clearance in `scroll_to`, overshooting `safe_y_min`.
7731    #[gpui::test]
7732    fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
7733        let input_view = InputView::new(cx);
7734        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7735        let input = input_view.input;
7736
7737        // JetBrains-style: 1 trailing empty row + 1-line cursor surrounding.
7738        cx.update(|window, cx| {
7739            input.update(cx, |state, cx| {
7740                state.set_scroll_beyond_last_line(Some(1), window, cx);
7741                state.set_cursor_surrounding_lines(Some(1), window, cx);
7742                let text: String = (1..=50)
7743                    .map(|i| format!("line {i}"))
7744                    .collect::<Vec<_>>()
7745                    .join("\n");
7746                state.set_value(text, window, cx);
7747            });
7748        });
7749        cx.run_until_parked();
7750
7751        // Sanity: paint populated `scroll_size` and `input_bounds` — without
7752        // these, `safe_y_min` below collapses to 0 and the assertion is vacuous.
7753        cx.update(|_, cx| {
7754            input.read_with(cx, |state, _| {
7755                assert!(
7756                    state.scroll_size.height > px(0.),
7757                    "scroll_size not populated by initial paint"
7758                );
7759                assert!(
7760                    state.input_bounds.size.height > px(0.),
7761                    "input_bounds not populated by initial paint"
7762                );
7763            });
7764        });
7765
7766        // Move cursor to end with downward direction — same code path as a
7767        // `Down` keystroke at EOB. `scroll_to` runs synchronously inside
7768        // `move_to`; inspect `deferred_scroll_offset` in the same closure
7769        // before the next paint consumes and clears it.
7770        cx.update(|_, cx| {
7771            input.update(cx, |state, cx| {
7772                let end = state.text.len();
7773                state.move_to(end, Some(MoveDirection::Down), cx);
7774
7775                let deferred = state
7776                    .deferred_scroll_offset
7777                    .expect("scroll_to should populate deferred_scroll_offset");
7778                let safe_y_min =
7779                    (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
7780
7781                assert!(
7782                    deferred.y >= safe_y_min,
7783                    "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
7784                     — paint would jitter (Bug C regression)",
7785                    deferred.y,
7786                    safe_y_min,
7787                );
7788            });
7789        });
7790    }
7791
7792    #[gpui::test]
7793    fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
7794        assert_search_reveals_with_padding_after_manual_scroll(false, cx);
7795    }
7796
7797    #[gpui::test]
7798    fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
7799        cx: &mut TestAppContext,
7800    ) {
7801        assert_search_reveals_with_padding_after_manual_scroll(true, cx);
7802    }
7803
7804    fn assert_search_reveals_with_padding_after_manual_scroll(
7805        previous: bool,
7806        cx: &mut TestAppContext,
7807    ) {
7808        let input_view = InputView::new(cx);
7809        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7810        let input = input_view.input;
7811        let text = (0..160)
7812            .map(|row| {
7813                if matches!(row, 20 | 60 | 100) {
7814                    format!("match on row {row}")
7815                } else {
7816                    format!("line {row}")
7817                }
7818            })
7819            .collect::<Vec<_>>()
7820            .join("\n");
7821        let start = text.match_indices("match").nth(1).unwrap().0;
7822        let expected_match = start..start + "match".len();
7823        cx.update(|window, cx| {
7824            input.update(cx, |state, cx| {
7825                state.set_cursor_surrounding_lines(Some(3), window, cx);
7826                state.set_value(text, window, cx);
7827                state.set_search_query("match", true, cx);
7828                if previous {
7829                    state.search_session.matcher.next();
7830                    state.search_session.matcher.next();
7831                }
7832            });
7833        });
7834        cx.run_until_parked();
7835        cx.update(|_, cx| {
7836            input.update(cx, |state, cx| {
7837                let line_height = state.last_layout.as_ref().unwrap().line_height;
7838                let y = if previous { px(0.) } else { -line_height * 80. };
7839                state.set_scroll_offset(point(px(0.), y), cx);
7840            });
7841        });
7842        cx.run_until_parked();
7843        input.read_with(&cx, |state, _| {
7844            let visible = state.visible_row_range().unwrap();
7845            if previous {
7846                assert!(visible.end <= 60, "target must be below the viewport");
7847            } else {
7848                assert!(visible.start > 60, "target must be above the viewport");
7849            }
7850        });
7851        cx.update(|_, cx| {
7852            input.update(cx, |state, cx| {
7853                let range = if previous {
7854                    state.previous_search_match(cx)
7855                } else {
7856                    state.next_search_match(cx)
7857                };
7858                assert_eq!(range, Some(expected_match));
7859                assert_eq!(state.search_session.matcher.label(), "2/3");
7860            });
7861        });
7862        cx.run_until_parked();
7863        input.read_with(&cx, |state, _| {
7864            assert!(state.visible_row_range().unwrap().contains(&60));
7865            let line_height = state.last_layout.as_ref().unwrap().line_height;
7866            let target_y = line_height * 60. + state.scroll_handle.offset().y;
7867            // Three lines of edge clearance include the matched line itself.
7868            assert!(target_y >= line_height * 2. - px(0.1));
7869            assert!(
7870                target_y + line_height * 3.
7871                    <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
7872                "search must preserve the configured surrounding-line padding"
7873            );
7874        });
7875    }
7876
7877    /// A host that wants the search shortcut for its own search UI.
7878    struct SearchHost {
7879        editor: Entity<InputBaseState<EditorMode>>,
7880        search_requests: Rc<Cell<usize>>,
7881    }
7882
7883    impl Render for SearchHost {
7884        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7885            let search_requests = self.search_requests.clone();
7886            div()
7887                .size_full()
7888                .on_action(cx.listener(move |_, _: &Search, _, _| {
7889                    search_requests.set(search_requests.get() + 1);
7890                }))
7891                .child(self.editor.clone())
7892        }
7893    }
7894
7895    /// Opens an editor inside [`SearchHost`], focused, and presses the search
7896    /// shortcut once. Returns the editor and the host's request count.
7897    fn press_search_shortcut(
7898        cx: &mut TestAppContext,
7899        searchable: bool,
7900    ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
7901        let search_requests = Rc::new(Cell::new(0));
7902        let mut editor = None;
7903        let window = cx.update(|cx| {
7904            cx.open_window(Default::default(), |window, cx| {
7905                cx.set_global(Theme::default());
7906                super::super::init(cx);
7907                let state =
7908                    cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
7909                editor = Some(state.clone());
7910                cx.new(|_| SearchHost {
7911                    editor: state,
7912                    search_requests: search_requests.clone(),
7913                })
7914            })
7915            .unwrap()
7916        });
7917        let editor = editor.unwrap();
7918        let mut cx = VisualTestContext::from_window(window.into(), cx);
7919        cx.update(|window, cx| {
7920            editor.update(cx, |state, cx| state.focus(window, cx));
7921        });
7922        cx.run_until_parked();
7923        #[cfg(target_os = "macos")]
7924        cx.simulate_keystrokes("cmd-f");
7925        #[cfg(not(target_os = "macos"))]
7926        cx.simulate_keystrokes("ctrl-f");
7927        cx.run_until_parked();
7928        (editor, search_requests)
7929    }
7930
7931    #[gpui::test]
7932    fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
7933        let (editor, search_requests) = press_search_shortcut(cx, false);
7934        assert_eq!(search_requests.get(), 1);
7935        editor.read_with(cx, |state, _| {
7936            assert!(!state.search_session().open);
7937            assert!(!state.search_session().is_active());
7938        });
7939    }
7940
7941    #[gpui::test]
7942    fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
7943        let (editor, search_requests) = press_search_shortcut(cx, true);
7944        assert_eq!(search_requests.get(), 0);
7945        editor.read_with(cx, |state, _| {
7946            assert!(state.search_session().open);
7947            assert!(state.search_session().is_active());
7948        });
7949    }
7950
7951    #[gpui::test]
7952    fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
7953        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7954        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7955        let input = input_view.input;
7956        cx.update(|window, cx| {
7957            input.update(cx, |state, cx| {
7958                state.set_value("foo bar foo", window, cx);
7959                state.set_search_query("foo", true, cx);
7960            });
7961        });
7962        cx.run_until_parked();
7963        input.read_with(&cx, |state, _| {
7964            let session = state.search_session();
7965            assert!(session.is_active());
7966            assert!(!session.open);
7967            assert_eq!(session.matcher.len(), 2);
7968        });
7969        cx.update(|_, cx| {
7970            input.update(cx, |state, cx| state.close_search(cx));
7971        });
7972        input.read_with(&cx, |state, _| {
7973            assert!(!state.search_session().is_active());
7974        });
7975    }
7976
7977    /// A closed search skips rescanning on edits, so every path that reads
7978    /// the matches again must see the edited text, not the text at close.
7979    #[gpui::test]
7980    fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
7981        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
7982        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7983        let input = input_view.input;
7984        cx.update(|window, cx| {
7985            input.update(cx, |state, cx| {
7986                state.set_value("foo bar foo", window, cx);
7987                state.set_search_query("foo", true, cx);
7988                state.close_search(cx);
7989
7990                state.set_value("bar foo", window, cx);
7991                assert_eq!(state.next_search_match(cx), Some(4..7));
7992
7993                state.set_value("foo foo foo", window, cx);
7994                state.set_search_query("foo", true, cx);
7995                assert_eq!(state.search_session().matcher.len(), 3);
7996            });
7997        });
7998    }
7999
8000    #[gpui::test]
8001    fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
8002        let input_view = InputView::new(cx);
8003        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8004        let input = input_view.input;
8005        let text = format!(
8006            "match\n{}\n{}match\n{}",
8007            "line\n".repeat(80),
8008            "wrapped text ".repeat(500),
8009            "line\n".repeat(80)
8010        );
8011        cx.update(|window, cx| {
8012            input.update(cx, |state, cx| {
8013                state.set_cursor_surrounding_lines(Some(3), window, cx);
8014                state.set_value(text, window, cx);
8015                state.set_search_query("match", true, cx);
8016            });
8017        });
8018        cx.run_until_parked();
8019        cx.update(|_, cx| {
8020            input.update(cx, |state, cx| {
8021                state.next_search_match(cx).unwrap();
8022            });
8023        });
8024        cx.run_until_parked();
8025        input.read_with(&cx, |state, _| {
8026            let range = state.search_session.matcher.matched_ranges()[1].clone();
8027            let layout = state.last_layout.as_ref().unwrap();
8028            let (_, _, position) = state.line_and_position_for_offset(range.end);
8029            let y = position.expect("wrapped match must be laid out").y
8030                + state.scroll_handle.offset().y;
8031            assert!(y >= layout.line_height * 2. - px(0.1));
8032            assert!(
8033                y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
8034                "wrapped match must retain surrounding display rows"
8035            );
8036        });
8037    }
8038
8039    #[gpui::test]
8040    fn test_number_step(cx: &mut TestAppContext) {
8041        let input = InputView::build(cx, |state| state).input;
8042
8043        cx.update(|cx| {
8044            input.update(cx, |_state, cx| {
8045                assert_eq!(
8046                    NumberStep::from(5.).value(123., StepAction::Increment, cx),
8047                    5.
8048                );
8049
8050                // The step can differ by direction at a boundary: at 1.0 it
8051                // is 0.1 going down and 0.5 going up.
8052                let step = NumberStep::by_value(|value, action, _cx| {
8053                    let below = match action {
8054                        StepAction::Increment => value < 1.0,
8055                        StepAction::Decrement => value <= 1.0,
8056                    };
8057                    if below { 0.1 } else { 0.5 }
8058                });
8059                assert_eq!(step.value(0.5, StepAction::Increment, cx), 0.1);
8060                assert_eq!(step.value(1.0, StepAction::Increment, cx), 0.5);
8061                assert_eq!(step.value(1.0, StepAction::Decrement, cx), 0.1);
8062                assert_eq!(step.value(2.0, StepAction::Decrement, cx), 0.5);
8063            });
8064        });
8065    }
8066
8067    #[gpui::test]
8068    fn test_number_input_normalization(cx: &mut TestAppContext) {
8069        let input_view = InputView::build(cx, |state| {
8070            state.mask_pattern(MaskPattern::Number {
8071                separator: None,
8072                fraction: None,
8073            })
8074        });
8075        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8076        let input = input_view.input;
8077
8078        // Full-width digits and the ideographic full stop are normalized,
8079        // and the cursor is at the end (in normalized bytes, not the
8080        // original 12 bytes).
8081        cx.update(|window, cx| {
8082            input.update(cx, |state, cx| {
8083                state.replace_text_in_range(None, "12。5", window, cx);
8084            });
8085        });
8086        cx.run_until_parked();
8087        cx.update(|_, cx| {
8088            input.read_with(cx, |state, _| {
8089                assert_eq!(state.value(), "12.5");
8090                let cursor: Range<usize> = state.selected_range();
8091                assert_eq!(cursor, 4..4);
8092            });
8093        });
8094
8095        // Non-numeric input is rejected.
8096        cx.update(|window, cx| {
8097            input.update(cx, |state, cx| {
8098                state.replace_text_in_range(None, "abc", window, cx);
8099            });
8100        });
8101        cx.run_until_parked();
8102        cx.update(|_, cx| {
8103            input.read_with(cx, |state, _| {
8104                assert_eq!(state.value(), "12.5");
8105            });
8106        });
8107
8108        // A bare leading dot is kept as-is (normalized from the ideographic
8109        // full stop), not completed to "0.", so it stays editable.
8110        cx.update(|window, cx| {
8111            input.update(cx, |state, cx| {
8112                let range = state.range_to_utf16(&(0..state.text.len()));
8113                state.replace_text_in_range(Some(range), "。", window, cx);
8114            });
8115        });
8116        cx.run_until_parked();
8117        cx.update(|_, cx| {
8118            input.read_with(cx, |state, _| {
8119                assert_eq!(state.value(), ".");
8120                let cursor: Range<usize> = state.selected_range();
8121                assert_eq!(cursor, 1..1);
8122            });
8123        });
8124    }
8125
8126    #[gpui::test]
8127    fn test_mask_pattern_accepts_non_ascii_text(cx: &mut TestAppContext) {
8128        let input_view = InputView::build(cx, |state| state.mask_pattern("9999年99月"));
8129        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8130        let input = input_view.input;
8131
8132        cx.update(|window, cx| {
8133            input.update(cx, |state, cx| {
8134                state.replace_text_in_range(None, "2024年12月", window, cx);
8135            });
8136        });
8137        cx.run_until_parked();
8138        cx.update(|_, cx| {
8139            input.read_with(cx, |state, _| {
8140                assert_eq!(state.value(), "2024年12月");
8141            });
8142        });
8143    }
8144
8145    #[gpui::test]
8146    fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
8147        let input_view = InputView::build(cx, |state| {
8148            state.mask_pattern(MaskPattern::Number {
8149                separator: Some(','),
8150                fraction: Some(2),
8151            })
8152        });
8153        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8154        let input = input_view.input;
8155
8156        cx.update(|window, cx| {
8157            input.update(cx, |state, cx| {
8158                state.replace_text_in_range(None, "1234", window, cx);
8159            });
8160        });
8161        cx.run_until_parked();
8162        cx.update(|_, cx| {
8163            input.read_with(cx, |state, _| {
8164                assert_eq!(state.value(), "1,234");
8165                assert_eq!(state.unmask_value(), "1234");
8166            });
8167        });
8168    }
8169
8170    #[gpui::test]
8171    fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
8172        let input_view = InputView::build(cx, |state| {
8173            state
8174                .mask_pattern(MaskPattern::Number {
8175                    separator: None,
8176                    fraction: None,
8177                })
8178                .min(10.)
8179                .max(100.)
8180        });
8181        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8182        let input = input_view.input;
8183
8184        // Out-of-range values are allowed while typing, and clamped on blur.
8185        cx.update(|window, cx| {
8186            input.update(cx, |state, cx| {
8187                state.replace_text_in_range(None, "1000", window, cx);
8188                assert_eq!(state.value(), "1000");
8189                state.clamp_number_value(window, cx);
8190                assert_eq!(state.value(), "100");
8191
8192                let range = state.range_to_utf16(&(0..state.text.len()));
8193                state.replace_text_in_range(Some(range), "1", window, cx);
8194                assert_eq!(state.value(), "1");
8195                state.clamp_number_value(window, cx);
8196                assert_eq!(state.value(), "10");
8197            });
8198        });
8199    }
8200
8201    #[gpui::test]
8202    fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
8203        let input_view = InputView::build(cx, |state| {
8204            state.mask_pattern(MaskPattern::Number {
8205                separator: Some(','),
8206                fraction: None,
8207            })
8208        });
8209        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8210        let input = input_view.input;
8211
8212        // When the mask changes the text (regrouping separators), a
8213        // whole-document change is recorded, so undo/redo can restore it.
8214        cx.update(|window, cx| {
8215            input.update(cx, |state, cx| {
8216                state.replace_text_in_range(None, "1234", window, cx);
8217                assert_eq!(state.value(), "1,234");
8218                state.replace_text_in_range(None, "5", window, cx);
8219                assert_eq!(state.value(), "12,345");
8220
8221                // Each whole-document mask rewrite is an atomic undo step.
8222                // Before the whole-document history fix, undo produced a
8223                // corrupted value like "1,2344".
8224                state.undo(&Undo, window, cx);
8225                assert_eq!(state.value(), "1,234");
8226                state.undo(&Undo, window, cx);
8227                assert_eq!(state.value(), "");
8228                state.redo(&Redo, window, cx);
8229                assert_eq!(state.value(), "1,234");
8230                state.redo(&Redo, window, cx);
8231                assert_eq!(state.value(), "12,345");
8232            });
8233        });
8234    }
8235
8236    #[gpui::test]
8237    fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
8238        let input_view = InputView::build(cx, |state| state);
8239        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8240        let input = input_view.input;
8241
8242        cx.update(|window, cx| {
8243            input.update(cx, |state, cx| {
8244                state.replace_text_in_range(None, "a", window, cx);
8245                state.replace_text_in_range(None, "b", window, cx);
8246                assert_eq!(state.value(), "ab");
8247
8248                state.undo(&Undo, window, cx);
8249                assert_eq!(state.value(), "");
8250            });
8251        });
8252    }
8253
8254    #[gpui::test]
8255    fn test_undo_manager_cursor_movement_splits_typing(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.replace_text_in_range(None, "b", window, cx);
8264                state.left(&MoveLeft, window, cx);
8265                state.replace_text_in_range(None, "x", window, cx);
8266                assert_eq!(state.value(), "axb");
8267
8268                state.undo(&Undo, window, cx);
8269                assert_eq!(state.value(), "ab");
8270                state.undo(&Undo, window, cx);
8271                assert_eq!(state.value(), "");
8272            });
8273        });
8274    }
8275
8276    #[gpui::test]
8277    fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
8278        let input_view = InputView::build(cx, |state| state);
8279        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8280        let input = input_view.input;
8281
8282        cx.update(|window, cx| {
8283            input.update(cx, |state, cx| {
8284                state.set_value("abcd", window, cx);
8285                state.set_selected_range(2..2, cx);
8286                state.backspace(&Backspace, window, cx);
8287                state.delete(&Delete, window, cx);
8288                assert_eq!(state.value(), "ad");
8289
8290                state.undo(&Undo, window, cx);
8291                assert_eq!(state.value(), "acd");
8292                state.undo(&Undo, window, cx);
8293                assert_eq!(state.value(), "abcd");
8294            });
8295        });
8296    }
8297
8298    #[gpui::test]
8299    fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
8300        let input_view = InputView::build(cx, |state| state);
8301        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8302        let input = input_view.input;
8303
8304        cx.update(|window, cx| {
8305            input.update(cx, |state, cx| {
8306                state.set_value("abcd", window, cx);
8307                state.backspace(&Backspace, window, cx);
8308                state.backspace(&Backspace, window, cx);
8309                assert_eq!(state.value(), "ab");
8310                state.undo(&Undo, window, cx);
8311                assert_eq!(state.value(), "abcd");
8312                assert_eq!(state.selected_range(), 4..4);
8313
8314                state.set_value("abcd", window, cx);
8315                state.set_selected_range(1..1, cx);
8316                state.delete(&Delete, window, cx);
8317                state.delete(&Delete, window, cx);
8318                assert_eq!(state.value(), "ad");
8319                state.undo(&Undo, window, cx);
8320                assert_eq!(state.value(), "abcd");
8321                assert_eq!(state.selected_range(), 1..1);
8322            });
8323        });
8324    }
8325
8326    #[gpui::test]
8327    fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
8328        let input_view = InputView::build(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            cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
8334            input.update(cx, |state, cx| {
8335                state.replace_text_in_range(None, "a", window, cx);
8336                state.paste(&Paste, window, cx);
8337                state.replace_text_in_range(None, "b", window, cx);
8338                assert_eq!(state.value(), "aPb");
8339
8340                state.undo(&Undo, window, cx);
8341                assert_eq!(state.value(), "aP");
8342                state.undo(&Undo, window, cx);
8343                assert_eq!(state.value(), "a");
8344                state.undo(&Undo, window, cx);
8345                assert_eq!(state.value(), "");
8346            });
8347        });
8348    }
8349
8350    #[gpui::test]
8351    fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
8352        let input_view = InputView::build(cx, |state| state);
8353        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8354        let input = input_view.input;
8355
8356        cx.update(|window, cx| {
8357            input.update(cx, |state, cx| {
8358                state.replace_text_in_range(None, "a", window, cx);
8359                state.insert("P", window, cx);
8360                state.replace_text_in_range(None, "b", window, cx);
8361                assert_eq!(state.value(), "aPb");
8362
8363                state.undo(&Undo, window, cx);
8364                assert_eq!(state.value(), "aP");
8365                state.undo(&Undo, window, cx);
8366                assert_eq!(state.value(), "a");
8367            });
8368        });
8369    }
8370
8371    #[gpui::test]
8372    fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
8373        let input_view = InputView::build(cx, |state| state);
8374        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8375        let input = input_view.input;
8376
8377        cx.update(|window, cx| {
8378            input.update(cx, |state, cx| {
8379                state.replace_text_in_range(None, "a", window, cx);
8380                state.replace_text_in_range(None, "b", window, cx);
8381                state.select_all(window, cx);
8382                state.unselect(window, cx);
8383                state.replace_text_in_range(None, "c", window, cx);
8384
8385                state.undo(&Undo, window, cx);
8386                assert_eq!(state.value(), "ab");
8387                state.undo(&Undo, window, cx);
8388                assert_eq!(state.value(), "");
8389            });
8390        });
8391    }
8392
8393    #[gpui::test]
8394    fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
8395        let input_view = InputView::build_textarea(cx, |state| state);
8396        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8397        let input = input_view.input;
8398
8399        cx.update(|window, cx| {
8400            input.update(cx, |state, cx| {
8401                state.replace_text_in_range(None, "a", window, cx);
8402                state.enter(
8403                    &Enter {
8404                        secondary: false,
8405                        shift: false,
8406                    },
8407                    window,
8408                    cx,
8409                );
8410                state.replace_text_in_range(None, "b", window, cx);
8411
8412                state.undo(&Undo, window, cx);
8413                assert_eq!(state.value(), "a\n");
8414                state.undo(&Undo, window, cx);
8415                assert_eq!(state.value(), "a");
8416                state.undo(&Undo, window, cx);
8417                assert_eq!(state.value(), "");
8418            });
8419        });
8420    }
8421
8422    #[gpui::test]
8423    fn test_textarea_secondary_enter_does_not_insert_newline(cx: &mut TestAppContext) {
8424        let input_view = InputView::build_textarea(cx, |state| state);
8425        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8426        let input = input_view.input;
8427
8428        cx.update(|window, cx| {
8429            input.update(cx, |state, cx| {
8430                state.replace_text_in_range(None, "hello", window, cx);
8431                state.set_selection(0, 0);
8432                state.enter(
8433                    &Enter {
8434                        secondary: true,
8435                        shift: false,
8436                    },
8437                    window,
8438                    cx,
8439                );
8440                assert_eq!(state.value(), "hello");
8441            });
8442        });
8443    }
8444
8445    #[gpui::test]
8446    fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
8447        let input_view = InputView::build(cx, |state| state);
8448        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8449        let input = input_view.input;
8450
8451        cx.update(|window, cx| {
8452            input.update(cx, |state, cx| {
8453                for part in ["a", "b", "c"] {
8454                    state.replace_text_in_range(None, part, window, cx);
8455                }
8456                state.enter(
8457                    &Enter {
8458                        secondary: false,
8459                        shift: false,
8460                    },
8461                    window,
8462                    cx,
8463                );
8464                for part in ["d", "e", "f"] {
8465                    state.replace_text_in_range(None, part, window, cx);
8466                }
8467                assert_eq!(state.value(), "abcdef");
8468
8469                state.undo(&Undo, window, cx);
8470                assert_eq!(state.value(), "abc");
8471                state.undo(&Undo, window, cx);
8472                assert_eq!(state.value(), "");
8473            });
8474        });
8475    }
8476
8477    #[gpui::test]
8478    fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
8479        let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
8480        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8481        let input = input_view.input;
8482
8483        cx.update(|window, cx| {
8484            input.update(cx, |state, cx| {
8485                state.replace_text_in_range(None, "before submit", window, cx);
8486                state.enter(
8487                    &Enter {
8488                        secondary: false,
8489                        shift: false,
8490                    },
8491                    window,
8492                    cx,
8493                );
8494                state.replace_text_in_range(None, " after submit", window, cx);
8495                assert_eq!(state.value(), "before submit after submit");
8496
8497                state.undo(&Undo, window, cx);
8498                assert_eq!(state.value(), "before submit");
8499                state.undo(&Undo, window, cx);
8500                assert_eq!(state.value(), "");
8501            });
8502        });
8503    }
8504
8505    #[gpui::test]
8506    fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
8507        let input_view = InputView::build(cx, |state| state);
8508        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8509        let input = input_view.input;
8510
8511        cx.update(|window, cx| {
8512            input.update(cx, |state, cx| {
8513                state.replace_text_in_range(None, "before blur", window, cx);
8514                state.on_blur(window, cx);
8515                state.on_focus(window, cx);
8516                state.replace_text_in_range(None, " after focus", window, cx);
8517                assert_eq!(state.value(), "before blur after focus");
8518
8519                state.undo(&Undo, window, cx);
8520                assert_eq!(state.value(), "before blur");
8521                state.undo(&Undo, window, cx);
8522                assert_eq!(state.value(), "");
8523            });
8524        });
8525    }
8526
8527    #[gpui::test]
8528    fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
8529        let input_view = InputView::build_textarea(cx, |state| state);
8530        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8531        let input = input_view.input;
8532
8533        cx.update(|window, cx| {
8534            input.update(cx, |state, cx| {
8535                let enter = Enter {
8536                    secondary: false,
8537                    shift: false,
8538                };
8539                state.replace_text_in_range(None, "a", window, cx);
8540                state.enter(&enter, window, cx);
8541                state.replace_text_in_range(None, "b", window, cx);
8542                state.enter(&enter, window, cx);
8543                state.replace_text_in_range(None, "c", window, cx);
8544                assert_eq!(state.value(), "a\nb\nc");
8545
8546                for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
8547                    state.undo(&Undo, window, cx);
8548                    assert_eq!(state.value(), expected);
8549                }
8550            });
8551        });
8552    }
8553
8554    #[gpui::test]
8555    fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
8556        let input_view = InputView::build_textarea(cx, |state| state);
8557        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8558        let input = input_view.input;
8559        let parts = [
8560            "The ",
8561            "quick ",
8562            "brown fox, ",
8563            "你好,世界 ",
8564            "🦀 jumps over 13 lazy dogs.",
8565        ];
8566        let expected = parts.concat();
8567
8568        cx.update(|window, cx| {
8569            input.update(cx, |state, cx| {
8570                for part in parts {
8571                    state.replace_text_in_range(None, part, window, cx);
8572                }
8573                assert_eq!(state.value(), expected);
8574
8575                state.undo(&Undo, window, cx);
8576                assert_eq!(state.value(), "");
8577                state.redo(&Redo, window, cx);
8578                assert_eq!(state.value(), expected);
8579            });
8580        });
8581    }
8582
8583    #[gpui::test]
8584    fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
8585        cx: &mut TestAppContext,
8586    ) {
8587        let input_view = InputView::build_textarea(cx, |state| state);
8588        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8589        let input = input_view.input;
8590        let enter = Enter {
8591            secondary: false,
8592            shift: false,
8593        };
8594
8595        cx.update(|window, cx| {
8596            input.update(cx, |state, cx| {
8597                for (index, line) in [
8598                    "first line with punctuation!",
8599                    "第二行包含 Unicode 🦀",
8600                    "third line has several words",
8601                ]
8602                .into_iter()
8603                .enumerate()
8604                {
8605                    for chunk in line.split_inclusive(' ') {
8606                        state.replace_text_in_range(None, chunk, window, cx);
8607                    }
8608                    if index < 2 {
8609                        state.enter(&enter, window, cx);
8610                    }
8611                }
8612
8613                assert_eq!(
8614                    state.value(),
8615                    "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
8616                );
8617                state.undo(&Undo, window, cx);
8618                assert_eq!(
8619                    state.value(),
8620                    "first line with punctuation!\n第二行包含 Unicode 🦀\n"
8621                );
8622                state.undo(&Undo, window, cx);
8623                assert_eq!(
8624                    state.value(),
8625                    "first line with punctuation!\n第二行包含 Unicode 🦀"
8626                );
8627                state.undo(&Undo, window, cx);
8628                assert_eq!(state.value(), "first line with punctuation!\n");
8629            });
8630        });
8631    }
8632
8633    #[gpui::test]
8634    fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
8635        let input_view = InputView::build(cx, |state| state);
8636        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8637        let input = input_view.input;
8638
8639        cx.update(|window, cx| {
8640            input.update(cx, |state, cx| {
8641                state.set_value("hunter2", window, cx);
8642                state.set_masked(true, window, cx);
8643                state.select_all(window, cx);
8644                cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
8645
8646                state.copy(&Copy, window, cx);
8647                assert_eq!(
8648                    cx.read_from_clipboard().and_then(|item| item.text()),
8649                    Some("sentinel".to_string())
8650                );
8651
8652                // Cut neither copies nor deletes.
8653                state.cut(&Cut, window, cx);
8654                assert_eq!(state.value(), "hunter2");
8655                assert_eq!(
8656                    cx.read_from_clipboard().and_then(|item| item.text()),
8657                    Some("sentinel".to_string())
8658                );
8659
8660                // Revealing the value restores both.
8661                state.set_masked(false, window, cx);
8662                state.copy(&Copy, window, cx);
8663                assert_eq!(
8664                    cx.read_from_clipboard().and_then(|item| item.text()),
8665                    Some("hunter2".to_string())
8666                );
8667            });
8668        });
8669    }
8670
8671    #[gpui::test]
8672    fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
8673        let input_view = InputView::build(cx, |state| state);
8674        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8675        let input = input_view.input;
8676
8677        cx.update(|window, cx| {
8678            input.update(cx, |state, cx| {
8679                state.set_value("aaa bbb ccc", window, cx);
8680                state.set_masked(true, window, cx);
8681                state.set_selected_range(7..7, cx);
8682
8683                // The mask hides word boundaries, so a word delete takes
8684                // everything before the caret and leaves the rest.
8685                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8686                assert_eq!(state.value(), " ccc");
8687                assert_eq!(state.selected_range(), 0..0);
8688
8689                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
8690                assert_eq!(state.value(), "");
8691
8692                // A double click takes the whole value, not one word.
8693                state.set_value("aaa bbb ccc", window, cx);
8694                state.select_word(9, window, cx);
8695                assert_eq!(state.selected_range(), 0..11);
8696
8697                // Unmasked, the same delete only takes one word.
8698                state.set_masked(false, window, cx);
8699                state.set_value("aaa bbb ccc", window, cx);
8700                state.set_selected_range(11..11, cx);
8701                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8702                assert_eq!(state.value(), "aaa bbb ");
8703
8704                state.set_value("aaa bbb ccc", window, cx);
8705                state.select_word(9, window, cx);
8706                assert_eq!(state.selected_range(), 8..11);
8707            });
8708        });
8709    }
8710
8711    #[gpui::test]
8712    fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
8713        let input_view = InputView::build(cx, |state| state);
8714        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8715        let input = input_view.input;
8716
8717        cx.update(|window, cx| {
8718            input.update(cx, |state, cx| {
8719                state.set_value("hunter2", window, cx);
8720                state.select_all(window, cx);
8721                assert!(state.context_menu_capabilities().is_copyable());
8722
8723                state.set_masked(true, window, cx);
8724                let capabilities = state.context_menu_capabilities();
8725                assert!(capabilities.is_masked());
8726                assert!(capabilities.has_selection());
8727                assert!(!capabilities.is_copyable());
8728            });
8729        });
8730    }
8731
8732    #[gpui::test]
8733    fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
8734        cx: &mut TestAppContext,
8735    ) {
8736        let input_view = InputView::build(cx, |state| state);
8737        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8738        let input = input_view.input;
8739
8740        cx.update(|window, cx| {
8741            input.update(cx, |state, cx| {
8742                state.replace_text_in_range(None, "alpha beta gamma", window, cx);
8743                state.set_selected_range(6..10, cx);
8744                state.cut(&Cut, window, cx);
8745                assert_eq!(state.value(), "alpha  gamma");
8746
8747                state.paste(&Paste, window, cx);
8748                state.paste(&Paste, window, cx);
8749                assert_eq!(state.value(), "alpha betabeta gamma");
8750
8751                state.undo(&Undo, window, cx);
8752                assert_eq!(state.value(), "alpha beta gamma");
8753                state.undo(&Undo, window, cx);
8754                assert_eq!(state.value(), "alpha  gamma");
8755                state.undo(&Undo, window, cx);
8756                assert_eq!(state.value(), "alpha beta gamma");
8757            });
8758        });
8759    }
8760
8761    #[gpui::test]
8762    fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
8763        let input_view = InputView::build_textarea(cx, |state| state);
8764        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8765        let input = input_view.input;
8766
8767        cx.update(|window, cx| {
8768            input.update(cx, |state, cx| {
8769                state.set_value("one two three\nfour five", window, cx);
8770                state.set_selected_range(13..13, cx);
8771                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8772                assert_eq!(state.value(), "one two \nfour five");
8773                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
8774                assert_eq!(state.value(), "one two four five");
8775
8776                state.undo(&Undo, window, cx);
8777                assert_eq!(state.value(), "one two \nfour five");
8778                state.undo(&Undo, window, cx);
8779                assert_eq!(state.value(), "one two three\nfour five");
8780            });
8781        });
8782    }
8783
8784    #[gpui::test]
8785    fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
8786        let input_view = InputView::build_textarea(cx, |state| state);
8787        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8788        let input = input_view.input;
8789
8790        cx.update(|window, cx| {
8791            input.update(cx, |state, cx| {
8792                state.replace_text_in_range(None, "before", window, cx);
8793                state.set_selected_range(0..6, cx);
8794                state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
8795                assert_eq!(state.value(), "line one\nline two\n第三行");
8796
8797                state.undo(&Undo, window, cx);
8798                assert_eq!(state.value(), "before");
8799                assert_eq!(state.selected_range(), 0..6);
8800                state.redo(&Redo, window, cx);
8801                assert_eq!(state.value(), "line one\nline two\n第三行");
8802            });
8803        });
8804    }
8805
8806    #[gpui::test]
8807    fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
8808        let input_view = InputView::build(cx, |state| state);
8809        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8810        let input = input_view.input;
8811
8812        cx.update(|window, cx| {
8813            input.update(cx, |state, cx| {
8814                state.replace_text_in_range(None, "prefix ", window, cx);
8815                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
8816                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
8817                state.replace_and_mark_text_in_range(None, "你", None, window, cx);
8818                state.unmark_text(window, cx);
8819                state.replace_text_in_range(None, " suffix", window, cx);
8820                assert_eq!(state.value(), "prefix 你 suffix");
8821
8822                state.undo(&Undo, window, cx);
8823                assert_eq!(state.value(), "prefix 你");
8824                state.undo(&Undo, window, cx);
8825                assert_eq!(state.value(), "prefix ");
8826                state.undo(&Undo, window, cx);
8827                assert_eq!(state.value(), "");
8828            });
8829        });
8830    }
8831
8832    #[gpui::test]
8833    fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
8834        let input_view = InputView::build(cx, |state| state);
8835        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8836        let input = input_view.input;
8837
8838        cx.update(|window, cx| {
8839            input.update(cx, |state, cx| {
8840                state.replace_text_in_range(None, "abc", window, cx);
8841                state.set_selected_range(1..2, cx);
8842                state.replace_text_in_range(None, "X", window, cx);
8843                state.replace_text_in_range(None, "z", window, cx);
8844                assert_eq!(state.value(), "aXzc");
8845
8846                state.undo(&Undo, window, cx);
8847                assert_eq!(state.value(), "aXc");
8848                state.undo(&Undo, window, cx);
8849                assert_eq!(state.value(), "abc");
8850                state.undo(&Undo, window, cx);
8851                assert_eq!(state.value(), "");
8852            });
8853        });
8854    }
8855
8856    #[gpui::test]
8857    fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
8858        let input_view = InputView::build(cx, |state| {
8859            state.mask_pattern(MaskPattern::Number {
8860                separator: None,
8861                fraction: None,
8862            })
8863        });
8864        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8865        let input = input_view.input;
8866
8867        cx.update(|window, cx| {
8868            input.update(cx, |state, cx| {
8869                state.replace_text_in_range(None, "1.2", window, cx);
8870
8871                // Delete the integer part "1": the value keeps the leading dot
8872                // (".2"), not completed to "0.2", so the digits before the dot
8873                // stay editable.
8874                let range = state.range_to_utf16(&(0..1));
8875                state.replace_text_in_range(Some(range), "", window, cx);
8876                assert_eq!(state.value(), ".2");
8877                let cursor: Range<usize> = state.selected_range();
8878                assert_eq!(cursor, 0..0);
8879
8880                // The user can type a new integer part.
8881                state.replace_text_in_range(Some(0..0), "3", window, cx);
8882                assert_eq!(state.value(), "3.2");
8883            });
8884        });
8885    }
8886
8887    #[gpui::test]
8888    fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
8889        // A pre-existing invalid text (e.g. a `default_value` that does not
8890        // conform) must not trap the user, the edit is allowed to fix it.
8891        let input_view = InputView::build(cx, |state| {
8892            state
8893                .mask_pattern(MaskPattern::Number {
8894                    separator: None,
8895                    fraction: None,
8896                })
8897                .default_value("1,234")
8898        });
8899        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8900        let input = input_view.input;
8901
8902        cx.update(|window, cx| {
8903            input.update(cx, |state, cx| {
8904                // Delete the last char, the pending text "1,23" is still
8905                // invalid, but the edit is allowed since the old text was
8906                // already invalid.
8907                let range = state.range_to_utf16(&(4..5));
8908                state.replace_text_in_range(Some(range), "", window, cx);
8909                assert_eq!(state.value(), "1,23");
8910
8911                // Once the text becomes valid, the validation works as usual.
8912                let range = state.range_to_utf16(&(1..2));
8913                state.replace_text_in_range(Some(range), "", window, cx);
8914                assert_eq!(state.value(), "123");
8915                state.replace_text_in_range(None, "a", window, cx);
8916                assert_eq!(state.value(), "123");
8917            });
8918        });
8919    }
8920
8921    /// After `set_value` on a single-line input the caret sits at the end (like
8922    /// HTML `<input>`), yet the view is scrolled back to the start so a long
8923    /// value shows its beginning instead of its tail.
8924    #[gpui::test]
8925    fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
8926        let input_view = InputView::build(cx, |state| state);
8927        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8928        let input = input_view.input;
8929
8930        // Long enough to overflow any reasonable single-line input width.
8931        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8932        let len = value.len();
8933
8934        // Right after `set_value`, before the next paint consumes the deferred
8935        // offset: caret is at the end, and the view is forced back to the start.
8936        cx.update(|window, cx| {
8937            input.update(cx, |state, cx| {
8938                state.set_value(value.clone(), window, cx);
8939
8940                assert_eq!(
8941                    state.selected_range(),
8942                    len..len,
8943                    "single-line caret should be at the end after set_value"
8944                );
8945                assert_eq!(
8946                    state.deferred_scroll_offset,
8947                    Some(point(px(0.), px(0.))),
8948                    "the view should be forced back to the start"
8949                );
8950            });
8951        });
8952
8953        // After a paint, the steady-state view stays at the start (x == 0) even
8954        // though the caret is at the far end.
8955        cx.run_until_parked();
8956        cx.update(|_, cx| {
8957            input.read_with(cx, |state, _| {
8958                assert!(
8959                    state.scroll_size.width > state.input_bounds.size.width,
8960                    "value must overflow the input width or this test is vacuous"
8961                );
8962                assert_eq!(
8963                    state.scroll_handle.offset().x,
8964                    px(0.),
8965                    "long value should display from its start, not its tail"
8966                );
8967            });
8968        });
8969    }
8970
8971    /// `replace_all` on a single-line input replaces the text, puts the
8972    /// caret at the end, and — like `set_value` — snaps the view back to the
8973    /// start so a long value shows its beginning instead of its tail.
8974    #[gpui::test]
8975    fn test_replace_all_single_line(cx: &mut TestAppContext) {
8976        let input_view = InputView::build(cx, |state| state);
8977        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8978        let input = input_view.input;
8979
8980        // Long enough to overflow any reasonable single-line input width.
8981        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
8982        let len = value.len();
8983
8984        // Right after `replace_all`, before the next paint consumes the
8985        // deferred offset: caret is at the end, and the view is forced back
8986        // to the start.
8987        cx.update(|window, cx| {
8988            input.update(cx, |state, cx| {
8989                state.set_value("hello", window, cx);
8990                state.replace_all(value.clone(), window, cx);
8991                assert_eq!(state.value(), value);
8992                assert_eq!(
8993                    state.selected_range(),
8994                    len..len,
8995                    "single-line caret should be at the end after replace_all"
8996                );
8997                assert_eq!(
8998                    state.scroll_handle.offset(),
8999                    point(px(0.), px(0.)),
9000                    "the scroll offset should be reset to the start"
9001                );
9002                assert_eq!(
9003                    state.deferred_scroll_offset,
9004                    Some(point(px(0.), px(0.))),
9005                    "single-line should set a deferred scroll offset to keep the start visible"
9006                );
9007            });
9008        });
9009
9010        // After a paint, the steady-state view stays at the start (x == 0)
9011        // even though the caret is at the far end.
9012        cx.run_until_parked();
9013        cx.update(|_, cx| {
9014            input.read_with(cx, |state, _| {
9015                assert!(
9016                    state.scroll_size.width > state.input_bounds.size.width,
9017                    "value must overflow the input width or this test is vacuous"
9018                );
9019                assert_eq!(
9020                    state.scroll_handle.offset().x,
9021                    px(0.),
9022                    "long value should display from its start, not its tail"
9023                );
9024            });
9025        });
9026    }
9027
9028    /// Pasting past the right edge of a single-line input scrolls the caret
9029    /// into view in the paint that lays the pasted text out.
9030    #[gpui::test]
9031    fn test_paste_reveals_caret_single_line(cx: &mut TestAppContext) {
9032        let input_view = InputView::build(cx, |state| state);
9033        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9034        let input = input_view.input;
9035        cx.run_until_parked();
9036
9037        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9038        cx.update(|window, cx| {
9039            cx.write_to_clipboard(ClipboardItem::new_string(value.clone()));
9040            input.update(cx, |state, cx| state.paste(&Paste, window, cx));
9041        });
9042        cx.run_until_parked();
9043
9044        cx.update(|_, cx| {
9045            input.read_with(cx, |state, _| {
9046                assert!(
9047                    state.scroll_size.width > state.input_bounds.size.width,
9048                    "value must overflow the input width or this test is vacuous"
9049                );
9050                let caret = state
9051                    .last_layout
9052                    .as_ref()
9053                    .and_then(|layout| layout.cursor_bounds)
9054                    .expect("a caret");
9055                assert!(
9056                    caret.left() >= state.input_bounds.left()
9057                        && caret.right() <= state.input_bounds.right(),
9058                    "the caret at {caret:?} should be inside {:?}",
9059                    state.input_bounds
9060                );
9061            });
9062        });
9063    }
9064
9065    #[gpui::test]
9066    fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
9067        let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
9068        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9069        let input = input_view.input;
9070
9071        cx.update(|window, cx| {
9072            input.update(cx, |state, cx| {
9073                assert_eq!(state.value(), "defaultvalue");
9074
9075                state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
9076                assert_eq!(state.value(), "firstsecondthirdfourth");
9077
9078                state.set_value("", window, cx);
9079                state.insert("a\nb", window, cx);
9080                assert_eq!(state.value(), "ab");
9081            });
9082
9083            cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
9084            input.update(cx, |state, cx| {
9085                state.set_value("", window, cx);
9086                state.paste(&Paste, window, cx);
9087                assert_eq!(state.value(), "abcd");
9088            });
9089        });
9090
9091        cx.run_until_parked();
9092    }
9093
9094    /// `replace_all` on a multi-line (non-code-editor) input clears the
9095    /// selection to `0..0` and resets the scroll offset, but does not set a
9096    /// deferred scroll offset (single-line only).
9097    #[gpui::test]
9098    fn test_replace_all_multi_line(cx: &mut TestAppContext) {
9099        let input_view = InputView::build_textarea(cx, |state| state);
9100        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9101        let input = input_view.input;
9102
9103        cx.update(|window, cx| {
9104            input.update(cx, |state, cx| {
9105                state.set_value("foo\nbar", window, cx);
9106                state.replace_all("baz\nqux", window, cx);
9107                assert_eq!(state.value(), "baz\nqux");
9108                assert_eq!(
9109                    state.selected_range(),
9110                    0..0,
9111                    "multi-line selection should be cleared after replace_all"
9112                );
9113                assert_eq!(
9114                    state.scroll_handle.offset(),
9115                    point(px(0.), px(0.)),
9116                    "the scroll offset should be reset to the start"
9117                );
9118                assert!(
9119                    state.deferred_scroll_offset.is_none(),
9120                    "multi-line should not set a deferred scroll offset"
9121                );
9122            });
9123        });
9124    }
9125
9126    /// Unlike `set_value`, `replace_all` records the change so the user can
9127    /// undo it back to the previous text and redo to the new text.
9128    #[gpui::test]
9129    fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
9130        let input_view = InputView::build(cx, |state| state);
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                // Seed with a value and clear history so the baseline is clean.
9137                state.set_value("first", window, cx);
9138                assert!(
9139                    !state.undo_manager.has_undos(),
9140                    "history should be empty after set_value"
9141                );
9142
9143                // replace_all records a single undoable change.
9144                state.replace_all("second", window, cx);
9145                assert_eq!(state.value(), "second");
9146                assert!(
9147                    state.undo_manager.has_undos(),
9148                    "replace_all should record an undo step"
9149                );
9150
9151                // Undo restores the previous text.
9152                state.undo(&Undo, window, cx);
9153                assert_eq!(state.value(), "first");
9154
9155                // Redo reapplies the replacement.
9156                state.redo(&Redo, window, cx);
9157                assert_eq!(state.value(), "second");
9158            });
9159        });
9160    }
9161
9162    /// `replace_all` on a code editor marks a pending update and resets LSP
9163    /// state, so diagnostics/completions refresh against the new text.
9164    #[gpui::test]
9165    fn test_replace_all_code_editor(cx: &mut TestAppContext) {
9166        let input_view = InputView::new(cx);
9167        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9168        let input = input_view.input;
9169
9170        cx.update(|window, cx| {
9171            input.update(cx, |state, cx| {
9172                // Plant a pending-update flag and some LSP state to verify reset.
9173                state.set_value("select 1", window, cx);
9174                state._pending_update = false;
9175
9176                state.replace_all("select 2", window, cx);
9177                assert_eq!(state.value(), "select 2");
9178                assert!(
9179                    state._pending_update,
9180                    "replace_all on a code editor should request a pending update"
9181                );
9182            });
9183        });
9184    }
9185
9186    #[gpui::test]
9187    fn test_set_selected_range(cx: &mut TestAppContext) {
9188        let input_view = InputView::build(cx, |state| state.default_value("hello world"));
9189        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9190        let input = input_view.input;
9191
9192        cx.update(|_, cx| {
9193            input.update(cx, |s, cx| {
9194                s.set_selected_range(0..5, cx);
9195                assert_eq!(s.selected_range(), 0..5);
9196                assert_eq!(s.selected_text().to_string(), "hello");
9197
9198                s.set_selected_range(6..11, cx);
9199                assert_eq!(s.selected_text().to_string(), "world");
9200
9201                // clamped + collapsed
9202                s.set_selected_range(100..100, cx);
9203                assert_eq!(s.selected_range(), 11..11);
9204            });
9205        });
9206    }
9207
9208    /// A single-edit batch round-trips through undo/redo.
9209    #[gpui::test]
9210    fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
9211        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9212        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9213        let input = input_view.input;
9214
9215        cx.update(|window, cx| {
9216            input.update(cx, |s, cx| {
9217                s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
9218                assert_eq!(s.value(), "HELLO world");
9219
9220                s.undo(&Undo, window, cx);
9221                assert_eq!(s.value(), "hello world");
9222
9223                s.redo(&Redo, window, cx);
9224                assert_eq!(s.value(), "HELLO world");
9225            });
9226        });
9227    }
9228
9229    /// A single undo restores the exact original text and a single redo
9230    /// re-applies all edits, verifying the back-to-front application ordering.
9231    #[gpui::test]
9232    fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
9233        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9234        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9235        let input = input_view.input;
9236
9237        cx.update(|window, cx| {
9238            input.update(cx, |s, cx| {
9239                // Two edits at different positions, given in pre-edit
9240                // coordinates and in arbitrary (non-sorted) order.
9241                s.replace_text_in_ranges(
9242                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9243                    window,
9244                    cx,
9245                );
9246                assert_eq!(s.value(), "X bbb Y");
9247
9248                // One collapsed cursor per edit, at the end of each inserted text.
9249                let cursors: Vec<usize> =
9250                    s.selections.iter().map(|sel| sel.cursor_offset()).collect();
9251                assert_eq!(cursors, vec![1, 7]);
9252
9253                // The whole batch is a single undo transaction.
9254                assert_eq!(s.undo_manager.undo_count(), 1);
9255
9256                // One undo restores the exact original text.
9257                s.undo(&Undo, window, cx);
9258                assert_eq!(s.value(), "aaa bbb ccc");
9259
9260                // One redo re-applies all edits.
9261                s.redo(&Redo, window, cx);
9262                assert_eq!(s.value(), "X bbb Y");
9263            });
9264        });
9265    }
9266
9267    /// A multi-edit change reaches the highlighter once, with every edit in
9268    /// application order and the text right after each, which is what the
9269    /// default `update_batch` replays through `update` one edit at a time.
9270    #[gpui::test]
9271    fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
9272        use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
9273        use gpui::HighlightStyle;
9274        use std::cell::RefCell;
9275
9276        struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
9277
9278        impl InputHighlighter for RecordingHighlighter {
9279            fn language(&self) -> SharedString {
9280                "recording".into()
9281            }
9282
9283            fn update(
9284                &mut self,
9285                _: Option<InputEdit>,
9286                text: &Rope,
9287                _: bool,
9288                _: &mut Window,
9289                _: &mut Context<EditorState>,
9290            ) {
9291                self.0.borrow_mut().push(vec![text.to_string()]);
9292            }
9293
9294            fn update_batch(
9295                &mut self,
9296                edits: &[(InputEdit, Rope)],
9297                _: bool,
9298                _: &mut Window,
9299                _: &mut Context<EditorState>,
9300            ) {
9301                let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
9302                self.0.borrow_mut().push(texts);
9303            }
9304
9305            fn styles(
9306                &self,
9307                range: &Range<usize>,
9308                _: &dyn HighlightStyleResolver,
9309            ) -> Vec<(Range<usize>, HighlightStyle)> {
9310                vec![(range.clone(), HighlightStyle::default())]
9311            }
9312
9313            fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
9314                Vec::new()
9315            }
9316        }
9317
9318        let updates = Rc::new(RefCell::new(Vec::new()));
9319        let input_view = InputView::new(cx);
9320        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9321        let input = input_view.input;
9322
9323        cx.update(|window, cx| {
9324            input.update(cx, |s, cx| {
9325                s.set_value("aaa bbb ccc", window, cx);
9326                let recorded = updates.clone();
9327                s.set_highlighter_factory(
9328                    Rc::new(move |_: &str| {
9329                        let highlighter: Box<dyn InputHighlighter> =
9330                            Box::new(RecordingHighlighter(recorded.clone()));
9331                        Some(highlighter)
9332                    }),
9333                    cx,
9334                );
9335                s.replace_text_in_ranges(
9336                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9337                    window,
9338                    cx,
9339                );
9340            });
9341        });
9342
9343        assert_eq!(
9344            *updates.borrow(),
9345            vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
9346        );
9347    }
9348
9349    /// One keypress records a single edit with the text right after it.
9350    #[gpui::test]
9351    fn test_last_input_edits_single_insert(cx: &mut TestAppContext) {
9352        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9353        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9354        let input = input_view.input;
9355
9356        cx.update(|window, cx| {
9357            input.update(cx, |state, cx| {
9358                state.replace_text_in_ranges(&[(5..5, " big".to_string())], window, cx);
9359
9360                let edits = state.last_input_edits.as_slice();
9361                assert_eq!(edits.len(), 1);
9362                let (edit, text_after) = &edits[0];
9363                assert_eq!(edit.start_byte, 5);
9364                assert_eq!(edit.old_end_byte, 5);
9365                assert_eq!(edit.new_end_byte, 9);
9366                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9367                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9368                assert_eq!(edit.new_end_position, crate::input::Point::new(0, 9));
9369                assert_eq!(text_after.to_string(), "hello big world");
9370            });
9371        });
9372    }
9373
9374    /// Deletion and a multi-line paste each describe their whole replacement.
9375    #[gpui::test]
9376    fn test_last_input_edits_delete_and_paste(cx: &mut TestAppContext) {
9377        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9378        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9379        let input = input_view.input;
9380
9381        cx.update(|window, cx| {
9382            input.update(cx, |state, cx| {
9383                state.replace_text_in_ranges(&[(5..11, String::new())], window, cx);
9384                assert_eq!(state.value(), "hello");
9385
9386                let edits = state.last_input_edits.as_slice();
9387                assert_eq!(edits.len(), 1);
9388                let (edit, text_after) = &edits[0];
9389                assert_eq!(edit.start_byte, 5);
9390                assert_eq!(edit.old_end_byte, 11);
9391                assert_eq!(edit.new_end_byte, 5);
9392                assert_eq!(text_after.to_string(), "hello");
9393
9394                state.replace_text_in_ranges(&[(5..5, "\nnext".to_string())], window, cx);
9395                assert_eq!(state.value(), "hello\nnext");
9396
9397                let edits = state.last_input_edits.as_slice();
9398                assert_eq!(edits.len(), 1);
9399                let (edit, text_after) = &edits[0];
9400                assert_eq!(edit.start_byte, 5);
9401                assert_eq!(edit.old_end_byte, 5);
9402                assert_eq!(edit.new_end_byte, 10);
9403                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9404                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9405                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 4));
9406                assert_eq!(text_after.to_string(), "hello\nnext");
9407            });
9408        });
9409    }
9410
9411    /// A grouped change records every applied edit in application order.
9412    #[gpui::test]
9413    fn test_last_input_edits_grouped_change(cx: &mut TestAppContext) {
9414        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9415        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9416        let input = input_view.input;
9417
9418        cx.update(|window, cx| {
9419            input.update(cx, |state, cx| {
9420                state.replace_text_in_ranges(
9421                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9422                    window,
9423                    cx,
9424                );
9425                assert_eq!(state.value(), "X bbb Y");
9426
9427                let edits = state.last_input_edits.as_slice();
9428                assert_eq!(edits.len(), 2);
9429                // The higher offset is applied first, before the lower one.
9430                assert_eq!(edits[0].0.start_byte, 8);
9431                assert_eq!(edits[0].0.old_end_byte, 11);
9432                assert_eq!(edits[0].0.new_end_byte, 9);
9433                assert_eq!(edits[0].0.start_position, crate::input::Point::new(0, 8));
9434                assert_eq!(edits[0].0.old_end_position, crate::input::Point::new(0, 11));
9435                assert_eq!(edits[0].0.new_end_position, crate::input::Point::new(0, 9));
9436                assert_eq!(edits[0].1.to_string(), "aaa bbb Y");
9437
9438                assert_eq!(edits[1].0.start_byte, 0);
9439                assert_eq!(edits[1].0.old_end_byte, 3);
9440                assert_eq!(edits[1].0.new_end_byte, 1);
9441                assert_eq!(edits[1].0.start_position, crate::input::Point::new(0, 0));
9442                assert_eq!(edits[1].0.old_end_position, crate::input::Point::new(0, 3));
9443                assert_eq!(edits[1].0.new_end_position, crate::input::Point::new(0, 1));
9444                assert_eq!(edits[1].1.to_string(), "X bbb Y");
9445            });
9446        });
9447    }
9448
9449    /// Edits are recorded even when no highlighter can be installed.
9450    #[gpui::test]
9451    fn test_last_input_edits_without_a_highlighter(cx: &mut TestAppContext) {
9452        let input_view = InputView::new(cx);
9453        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9454        let input = input_view.input;
9455
9456        cx.update(|window, cx| {
9457            input.update(cx, |state, cx| {
9458                state.set_value("fn main() {}", window, cx);
9459                let no_highlighter: InputHighlighterFactory = Rc::new(|_: &str| None);
9460                state.set_highlighter_factory(no_highlighter, cx);
9461                assert!(state.last_input_edits.as_slice().is_empty());
9462
9463                state.replace_text_in_ranges(&[(12..12, "\n".to_string())], window, cx);
9464                assert_eq!(state.value(), "fn main() {}\n");
9465
9466                let edits = state.last_input_edits.as_slice();
9467                assert_eq!(edits.len(), 1);
9468                let (edit, text_after) = &edits[0];
9469                assert_eq!(edit.start_byte, 12);
9470                assert_eq!(edit.old_end_byte, 12);
9471                assert_eq!(edit.new_end_byte, 13);
9472                assert_eq!(edit.start_position, crate::input::Point::new(0, 12));
9473                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 12));
9474                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 0));
9475                assert_eq!(text_after.to_string(), "fn main() {}\n");
9476            });
9477        });
9478    }
9479
9480    /// `set_value` is silent and leaves no edits behind for the next change.
9481    #[gpui::test]
9482    fn test_last_input_edits_cleared_by_set_value(cx: &mut TestAppContext) {
9483        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9484        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9485        let input = input_view.input;
9486
9487        cx.update(|window, cx| {
9488            input.update(cx, |state, cx| {
9489                state.replace_text_in_ranges(&[(5..5, "!".to_string())], window, cx);
9490                assert_eq!(state.last_input_edits.as_slice().len(), 1);
9491
9492                state.set_value("replaced", window, cx);
9493                assert!(state.last_input_edits.as_slice().is_empty());
9494
9495                state.replace_text_in_ranges(&[(8..8, "?".to_string())], window, cx);
9496                let edits = state.last_input_edits.as_slice();
9497                assert_eq!(edits.len(), 1);
9498                assert_eq!(edits[0].1.to_string(), "replaced?");
9499            });
9500        });
9501    }
9502
9503    /// Apply an emitted batch as an incremental consumer would and verify every snapshot.
9504    fn replay_input_edits(text: &mut String, event: &InputEditsEvent) {
9505        for (edit, after) in event.edits() {
9506            let replacement = after.slice(edit.start_byte..edit.new_end_byte).to_string();
9507            text.replace_range(edit.start_byte..edit.old_end_byte, &replacement);
9508            assert_eq!(*text, after.to_string());
9509        }
9510    }
9511
9512    #[gpui::test]
9513    fn input_edits_events_preserve_queued_changes_and_undo(cx: &mut TestAppContext) {
9514        let view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9515        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9516        let input = view.input;
9517        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9518        let seen = observed.clone();
9519        let _subscription = cx.update(|_, cx| {
9520            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9521                seen.borrow_mut().push(event.clone());
9522            })
9523        });
9524        cx.update(|window, cx| {
9525            input.update(cx, |state, cx| {
9526                state.replace_text_in_ranges(&[(5..5, "!".into())], window, cx);
9527                state.replace_text_in_ranges(&[(6..6, "?".into())], window, cx);
9528                state.undo(&Undo, window, cx);
9529            });
9530        });
9531        let events = observed.borrow();
9532        assert!(events.len() >= 3);
9533        let mut text = "hello".to_string();
9534        for event in events.iter() {
9535            replay_input_edits(&mut text, event);
9536        }
9537        assert_eq!(
9538            text,
9539            input.read_with(&cx, |state, _| state.value().to_string())
9540        );
9541        assert_eq!(events[0].edits()[0].1.to_string(), "hello!");
9542        assert_eq!(events[1].edits()[0].1.to_string(), "hello!?");
9543    }
9544
9545    #[gpui::test]
9546    fn input_edits_event_replays_ime_commit(cx: &mut TestAppContext) {
9547        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9548        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9549        let input = view.input;
9550        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9551        let seen = observed.clone();
9552        let _subscription = cx.update(|_, cx| {
9553            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9554                seen.borrow_mut().push(event.clone());
9555            })
9556        });
9557        cx.update(|window, cx| {
9558            input.update(cx, |state, cx| {
9559                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9560                state.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
9561                state.replace_text_in_range(None, "你", window, cx);
9562            });
9563        });
9564        let events = observed.borrow();
9565        assert_eq!(events.len(), 1);
9566        let mut text = String::new();
9567        replay_input_edits(&mut text, &events[0]);
9568        assert_eq!(text, "你");
9569    }
9570
9571    #[gpui::test]
9572    fn input_edits_event_replays_after_cancelled_composition(cx: &mut TestAppContext) {
9573        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9574        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9575        let input = view.input;
9576        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9577        let seen = observed.clone();
9578        let _subscription = cx.update(|_, cx| {
9579            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9580                seen.borrow_mut().push(event.clone());
9581            })
9582        });
9583        cx.update(|window, cx| {
9584            input.update(cx, |state, cx| {
9585                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9586                state.replace_and_mark_text_in_range(None, "", None, window, cx);
9587                state.replace_text_in_range(None, "x", window, cx);
9588            });
9589        });
9590        let events = observed.borrow();
9591        assert_eq!(events.len(), 1);
9592        let mut text = String::new();
9593        replay_input_edits(&mut text, &events[0]);
9594        assert_eq!(text, "x");
9595    }
9596
9597    #[gpui::test]
9598    fn input_edits_event_replays_mask_rewrite(cx: &mut TestAppContext) {
9599        let view = InputView::build(cx, |state| {
9600            state
9601                .mask_pattern(MaskPattern::Number {
9602                    separator: Some(','),
9603                    fraction: None,
9604                })
9605                .default_value("999")
9606        });
9607        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9608        let input = view.input;
9609        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9610        let seen = observed.clone();
9611        let _subscription = cx.update(|_, cx| {
9612            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9613                seen.borrow_mut().push(event.clone());
9614            })
9615        });
9616        cx.update(|window, cx| {
9617            input.update(cx, |state, cx| {
9618                state.set_cursor_to(3);
9619                state.replace_text_in_range(None, "9", window, cx)
9620            });
9621        });
9622        let events = observed.borrow();
9623        assert_eq!(events.len(), 1);
9624        let mut text = "999".to_string();
9625        replay_input_edits(&mut text, &events[0]);
9626        assert_eq!(text, "9,999");
9627    }
9628
9629    /// An IME composition (marking then commit) undoes as a single unit.
9630    #[gpui::test]
9631    fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
9632        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
9633        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9634        let input = input_view.input;
9635
9636        cx.update(|window, cx| {
9637            input.update(cx, |s, cx| {
9638                // Simulate an IME composition: mark, refine, then commit.
9639                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9640                s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
9641                s.replace_text_in_range(None, "你", window, cx);
9642                assert_eq!(s.value(), "你");
9643
9644                // The entire composition is one undo transaction.
9645                assert_eq!(s.undo_manager.undo_count(), 1);
9646
9647                s.undo(&Undo, window, cx);
9648                assert_eq!(s.value(), "");
9649
9650                s.redo(&Redo, window, cx);
9651                assert_eq!(s.value(), "你");
9652            });
9653        });
9654    }
9655
9656    /// A keystroke right after a committed composition must be its own undo
9657    /// entry, not merged into the (finalized) composition transaction.
9658    #[gpui::test]
9659    fn test_edit_after_composition_is_separate_undo(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                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9667                s.replace_text_in_range(None, "你", window, cx);
9668                assert_eq!(s.value(), "你");
9669                assert_eq!(s.undo_manager.undo_count(), 1);
9670
9671                // Typing after the commit is a distinct transaction.
9672                s.replace_text_in_range(None, "x", window, cx);
9673                assert_eq!(s.value(), "你x");
9674                assert_eq!(s.undo_manager.undo_count(), 2);
9675
9676                s.undo(&Undo, window, cx);
9677                assert_eq!(s.value(), "你");
9678                s.undo(&Undo, window, cx);
9679                assert_eq!(s.value(), "");
9680            });
9681        });
9682    }
9683
9684    /// Canceling a composition via `unmark_text` closes its transaction so it
9685    /// does not leak and swallow a later edit.
9686    #[gpui::test]
9687    fn test_composition_cancel_via_unmark_does_not_leak(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                // Start a composition, then cancel it via unmark.
9695                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9696                s.unmark_text(window, cx);
9697                let after_cancel = s.undo_manager.undo_count();
9698
9699                // A later edit is recorded independently.
9700                s.replace_text_in_range(None, "x", window, cx);
9701                assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
9702            });
9703        });
9704    }
9705
9706    #[gpui::test]
9707    fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
9708        let input_view = InputView::build(cx, |state| state.default_value("éx"));
9709        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9710        let input = input_view.input;
9711
9712        cx.update(|window, cx| {
9713            input.update(cx, |state, cx| {
9714                state.set_selected_range(0..1, cx);
9715                assert_eq!(state.selected_range(), 0..2);
9716                state.copy(&Copy, window, cx);
9717
9718                state.set_selected_range(1..1, cx);
9719                assert_eq!(state.selected_range(), 0..0);
9720            });
9721        });
9722    }
9723
9724    #[gpui::test]
9725    fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
9726        let input_view = InputView::build(cx, |state| state.default_value("你好 "));
9727        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9728        let input = input_view.input;
9729
9730        cx.update(|window, cx| {
9731            input.update(cx, |state, cx| {
9732                state.set_selected_range(7..7, cx);
9733                state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
9734                state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
9735
9736                assert_eq!(state.value(), "你好 sh");
9737                assert_eq!(state.selected_range(), 9..9);
9738                assert_eq!(state.ime_marked_range, Some((7..9).into()));
9739            });
9740        });
9741    }
9742
9743    #[gpui::test]
9744    fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
9745        let input_view = InputView::build(cx, |state| state);
9746        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9747        let input = input_view.input;
9748
9749        cx.update(|window, cx| {
9750            input.update(cx, |state, cx| {
9751                state.set_value("a", window, cx);
9752                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
9753                state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
9754                state.replace_text_in_range(None, "是", window, cx);
9755                assert_eq!(state.value(), "a是");
9756
9757                state.undo(&Undo, window, cx);
9758                assert_eq!(state.value(), "a");
9759                state.redo(&Redo, window, cx);
9760                assert_eq!(state.value(), "a是");
9761            });
9762        });
9763    }
9764
9765    #[gpui::test]
9766    fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
9767        let input_view = InputView::build(cx, |state| state);
9768        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9769        let input = input_view.input;
9770
9771        cx.update(|window, cx| {
9772            input.update(cx, |state, cx| {
9773                // First composition: "jin" -> "今天"
9774                state.replace_and_mark_text_in_range(None, "j", None, window, cx);
9775                state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
9776                state.replace_text_in_range(None, "今天", window, cx);
9777                // Second composition: "wo" -> "我们"
9778                state.replace_and_mark_text_in_range(None, "w", None, window, cx);
9779                state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
9780                state.replace_text_in_range(None, "我们", window, cx);
9781                assert_eq!(state.value(), "今天我们");
9782                assert_eq!(state.selected_range(), 12..12);
9783
9784                state.undo(&Undo, window, cx);
9785                assert_eq!(state.value(), "今天");
9786                assert_eq!(state.selected_range(), 6..6);
9787
9788                state.undo(&Undo, window, cx);
9789                assert_eq!(state.value(), "");
9790                assert_eq!(state.selected_range(), 0..0);
9791
9792                state.redo(&Redo, window, cx);
9793                assert_eq!(state.value(), "今天");
9794                assert_eq!(state.selected_range(), 6..6);
9795
9796                state.redo(&Redo, window, cx);
9797                assert_eq!(state.value(), "今天我们");
9798                assert_eq!(state.selected_range(), 12..12);
9799            });
9800        });
9801    }
9802
9803    #[gpui::test]
9804    fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
9805        let input_view = InputView::build(cx, |state| state);
9806        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9807        let input = input_view.input;
9808
9809        cx.update(|window, cx| {
9810            input.update(cx, |state, cx| {
9811                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
9812                state.replace_text_in_range(None, "你", window, cx);
9813                state.undo_manager.set_pending_intent(EditIntent::Typing);
9814                state.replace_text_in_range(None, "a", window, cx);
9815                state.undo_manager.set_pending_intent(EditIntent::Typing);
9816                state.replace_text_in_range(None, "b", window, cx);
9817                assert_eq!(state.value(), "你ab");
9818
9819                state.undo(&Undo, window, cx);
9820                assert_eq!(state.value(), "你");
9821
9822                state.undo(&Undo, window, cx);
9823                assert_eq!(state.value(), "");
9824            });
9825        });
9826    }
9827
9828    #[gpui::test]
9829    fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
9830        let input_view = InputView::build(cx, |state| state);
9831        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9832        let input = input_view.input;
9833
9834        cx.update(|window, cx| {
9835            input.update(cx, |state, cx| {
9836                state.set_value("a", window, cx);
9837                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
9838                state.replace_and_mark_text_in_range(None, "", None, window, cx);
9839
9840                assert_eq!(state.value(), "a");
9841                assert!(!state.undo_manager.has_undos());
9842            });
9843        });
9844    }
9845
9846    /// The macOS Korean IME rewrites the character it just inserted.
9847    #[gpui::test]
9848    fn test_undo_manager_ime_rewrites_of_typed_char_are_one_group(cx: &mut TestAppContext) {
9849        let input_view = InputView::build(cx, |state| state);
9850        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9851        let input = input_view.input;
9852
9853        cx.update(|window, cx| {
9854            input.update(cx, |state, cx| {
9855                state.set_value("é ", window, cx);
9856                state.set_selected_range(3..3, cx);
9857                // g k s r m f: "ㅎ" -> "하" -> "한", then "ㄱ" -> "그" -> "글"
9858                state.replace_text_in_range(None, "ㅎ", window, cx);
9859                state.replace_text_in_range(Some(2..3), "하", window, cx);
9860                state.replace_text_in_range(Some(2..3), "한", window, cx);
9861                state.replace_text_in_range(None, "ㄱ", window, cx);
9862                state.replace_text_in_range(Some(3..4), "그", window, cx);
9863                state.replace_text_in_range(Some(3..4), "글", window, cx);
9864                assert_eq!(state.value(), "é 한글");
9865                assert_eq!(state.undo_manager.undo_count(), 1);
9866
9867                state.undo(&Undo, window, cx);
9868                assert_eq!(state.value(), "é ");
9869                assert_eq!(state.selected_range(), 3..3);
9870
9871                state.redo(&Redo, window, cx);
9872                assert_eq!(state.value(), "é 한글");
9873                assert_eq!(state.selected_range(), 9..9);
9874            });
9875        });
9876    }
9877
9878    #[gpui::test]
9879    fn test_undo_manager_rewrite_after_cursor_movement_is_separate(cx: &mut TestAppContext) {
9880        let input_view = InputView::build(cx, |state| state);
9881        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9882        let input = input_view.input;
9883
9884        cx.update(|window, cx| {
9885            input.update(cx, |state, cx| {
9886                state.replace_text_in_range(None, "c", window, cx);
9887                state.replace_text_in_range(None, "e", window, cx);
9888                state.left(&MoveLeft, window, cx);
9889                state.right(&MoveRight, window, cx);
9890                state.replace_text_in_range(Some(1..2), "é", window, cx);
9891                assert_eq!(state.value(), "cé");
9892
9893                state.undo(&Undo, window, cx);
9894                assert_eq!(state.value(), "ce");
9895                state.undo(&Undo, window, cx);
9896                assert_eq!(state.value(), "");
9897            });
9898        });
9899    }
9900
9901    #[gpui::test]
9902    fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
9903        let input_view = InputView::build(cx, |state| state);
9904        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9905        let input = input_view.input;
9906
9907        cx.update(|window, cx| {
9908            input.update(cx, |state, cx| {
9909                state.set_value("abc", window, cx);
9910                state.set_selected_range(1..2, cx);
9911                state.replace_text_in_range(None, "X", window, cx);
9912
9913                state.undo(&Undo, window, cx);
9914                assert_eq!(state.value(), "abc");
9915                assert_eq!(state.selected_range(), 1..2);
9916
9917                state.redo(&Redo, window, cx);
9918                assert_eq!(state.value(), "aXc");
9919                assert_eq!(state.selected_range(), 2..2);
9920            });
9921        });
9922    }
9923
9924    #[gpui::test]
9925    fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
9926        let input_view = InputView::build(cx, |state| state);
9927        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9928        let input = input_view.input;
9929
9930        cx.update(|window, cx| {
9931            input.update(cx, |state, cx| {
9932                state.set_value("abc", window, cx);
9933                state.set_selected_range(1..1, cx);
9934                state.delete(&Delete, window, cx);
9935
9936                state.undo(&Undo, window, cx);
9937                assert_eq!(state.value(), "abc");
9938                assert_eq!(state.selected_range(), 1..1);
9939            });
9940        });
9941    }
9942
9943    #[gpui::test]
9944    fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
9945        let input_view = InputView::build(cx, |state| state);
9946        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9947        let input = input_view.input;
9948
9949        cx.update(|window, cx| {
9950            input.update(cx, |state, cx| {
9951                state.replace_text_in_range(None, "ab", window, cx);
9952                state.undo(&Undo, window, cx);
9953                state.set_selected_range(0..0, cx);
9954                state.redo(&Redo, window, cx);
9955                assert_eq!(state.value(), "ab");
9956
9957                state.undo(&Undo, window, cx);
9958                state.replace_text_in_range(None, "x", window, cx);
9959                state.redo(&Redo, window, cx);
9960                assert_eq!(state.value(), "x");
9961            });
9962        });
9963    }
9964
9965    #[gpui::test]
9966    fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
9967        let input_view = InputView::build(cx, |state| state);
9968        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9969        let input = input_view.input;
9970
9971        cx.update(|window, cx| {
9972            input.update(cx, |state, cx| {
9973                state.replace_text_in_range(None, "a", window, cx);
9974                state.move_to(0, None, cx);
9975                state.replace_text_in_range(None, "", window, cx);
9976                state.undo(&Undo, window, cx);
9977                assert_eq!(state.value(), "");
9978                state.redo(&Redo, window, cx);
9979                assert_eq!(state.value(), "a");
9980                assert_eq!(state.cursor(), 1);
9981            });
9982        });
9983    }
9984
9985    #[gpui::test]
9986    fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
9987        let input_view = InputView::build(cx, |state| state);
9988        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9989        let input = input_view.input;
9990
9991        cx.update(|window, cx| {
9992            input.update(cx, |state, cx| {
9993                state.replace_text_in_range(None, "a", window, cx);
9994                state.left(&MoveLeft, window, cx);
9995                state.right(&MoveRight, window, cx);
9996                state.replace_text_in_range(None, "b", window, cx);
9997
9998                state.undo(&Undo, window, cx);
9999                assert_eq!(state.value(), "a");
10000                state.undo(&Undo, window, cx);
10001                assert_eq!(state.value(), "");
10002            });
10003        });
10004    }
10005
10006    #[gpui::test]
10007    fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
10008        cx: &mut TestAppContext,
10009    ) {
10010        let input_view = InputView::build(cx, |state| state);
10011        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10012        let input = input_view.input;
10013
10014        cx.update(|window, cx| {
10015            input.update(cx, |state, cx| {
10016                state.replace_text_in_range(None, "alpha", window, cx);
10017                state.replace_text_in_range(None, "", window, cx);
10018                state.replace_text_in_range(None, "beta", window, cx);
10019                assert_eq!(state.value(), "alphabeta");
10020
10021                state.undo(&Undo, window, cx);
10022                assert_eq!(state.value(), "alpha");
10023                state.undo(&Undo, window, cx);
10024                assert_eq!(state.value(), "");
10025            });
10026        });
10027    }
10028
10029    #[gpui::test]
10030    fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
10031        let input_view = InputView::build(cx, |state| {
10032            state.mask_pattern(MaskPattern::Number {
10033                separator: Some(','),
10034                fraction: None,
10035            })
10036        });
10037        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10038        let input = input_view.input;
10039
10040        cx.update(|window, cx| {
10041            input.update(cx, |state, cx| {
10042                state.set_value("12345", window, cx);
10043                state.set_selected_range(2..2, cx);
10044                state.replace_text_in_range(None, "9", window, cx);
10045                let selection_after_edit = state.selected_range();
10046                assert_ne!(selection_after_edit.end, state.value().len());
10047
10048                state.undo(&Undo, window, cx);
10049                state.redo(&Redo, window, cx);
10050                assert_eq!(state.selected_range(), selection_after_edit);
10051            });
10052        });
10053    }
10054
10055    /// Unfolding at a position opens exactly the folds hiding it.
10056    ///
10057    /// A fold keeps its own first and last line visible, so a position on
10058    /// either of them opens nothing. Nested folds all open at once, sibling
10059    /// folds stay closed, and the opened ranges stay fold candidates.
10060    #[gpui::test]
10061    fn test_unfold_at(cx: &mut TestAppContext) {
10062        use crate::input::{FoldRange, Position};
10063
10064        let view = InputView::<EditorMode>::new(cx);
10065        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10066        let input = view.input;
10067
10068        // An outer fold over lines 0..=5, a fold nested inside it, and a
10069        // sibling fold that must never be touched.
10070        cx.update(|window, cx| {
10071            input.update(cx, |state, cx| {
10072                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
10073                state.apply_highlighter_fold_candidates(
10074                    vec![
10075                        FoldRange::new(0, 5),
10076                        FoldRange::new(2, 4),
10077                        FoldRange::new(7, 10),
10078                    ],
10079                    cx,
10080                );
10081                state.display_map.set_folded(0, true);
10082                state.display_map.set_folded(2, true);
10083                state.display_map.set_folded(7, true);
10084            });
10085        });
10086
10087        // The outer fold's own first and last line stay visible, so neither
10088        // position opens anything.
10089        for line in [0, 5] {
10090            cx.update(|_, cx| {
10091                input.update(cx, |state, cx| {
10092                    assert!(!state.display_map.is_buffer_line_hidden(line));
10093                    assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
10094                });
10095                input.read_with(cx, |state, _| {
10096                    assert!(state.display_map.is_folded_at(0));
10097                    assert!(state.display_map.is_folded_at(2));
10098                    assert!(state.display_map.is_folded_at(7));
10099                });
10100            });
10101        }
10102
10103        // Line 3 is hidden by both the outer and the nested fold, so both
10104        // open; the sibling fold does not.
10105        cx.update(|_, cx| {
10106            input.update(cx, |state, cx| {
10107                assert!(state.unfold_at(Position::new(3, 0), cx));
10108            });
10109            input.read_with(cx, |state, _| {
10110                assert!(!state.display_map.is_buffer_line_hidden(3));
10111                assert!(!state.display_map.is_folded_at(0));
10112                assert!(!state.display_map.is_folded_at(2));
10113                assert!(state.display_map.is_folded_at(7));
10114                // The opened ranges are still candidates for refolding.
10115                assert!(state.display_map.is_fold_candidate(0));
10116                assert!(state.display_map.is_fold_candidate(2));
10117            });
10118        });
10119
10120        // Nothing is hidden there any more, so a second call is a no-op.
10121        cx.update(|_, cx| {
10122            input.update(cx, |state, cx| {
10123                assert!(!state.unfold_at(Position::new(3, 0), cx));
10124            });
10125        });
10126    }
10127
10128    /// Losing focus hides the hover popover but keeps the decorations.
10129    ///
10130    /// Both used to be dropped by one call, so clicking away threw away
10131    /// decorations the application had installed and never asked to remove.
10132    #[gpui::test]
10133    fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
10134        let view = InputView::<EditorMode>::new(cx);
10135        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10136        let input = view.input;
10137
10138        cx.update(|window, cx| {
10139            input.update(cx, |state, cx| {
10140                state.set_value("select 1", window, cx);
10141                let _collection = state.create_decorations_collection(
10142                    vec![crate::input::TextDecoration::new(
10143                        0..6,
10144                        gpui::HighlightStyle {
10145                            font_weight: Some(gpui::FontWeight::BOLD),
10146                            ..Default::default()
10147                        },
10148                    )],
10149                    cx,
10150                );
10151                state.present_hover(
10152                    0..6,
10153                    lsp_types::Hover {
10154                        contents: lsp_types::HoverContents::Scalar(
10155                            lsp_types::MarkedString::String("docs".into()),
10156                        ),
10157                        range: None,
10158                    },
10159                    cx,
10160                );
10161                assert!(state.hover_popover().is_some());
10162
10163                state.on_blur(window, cx);
10164
10165                assert!(
10166                    state.hover_popover().is_none(),
10167                    "blur should hide the hover popover"
10168                );
10169                let decorations = state.extras.decoration_layers();
10170                assert!(
10171                    decorations.iter().any(|layer| !layer.is_empty()),
10172                    "blur must not discard decorations"
10173                );
10174            });
10175        });
10176    }
10177
10178    /// The mode marker is the only source of truth for the kind of input.
10179    ///
10180    /// An auto-growing textarea capped at one row used to report itself as
10181    /// single-line, because the answer was derived from the row counts.
10182    #[gpui::test]
10183    fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
10184        let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
10185        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10186        view.input.read_with(&mut cx, |state, _| {
10187            assert!(state.is_multi_line());
10188            assert!(!state.is_single_line());
10189            assert!(!state.is_code_editor());
10190        });
10191    }
10192
10193    #[gpui::test]
10194    fn test_textarea_prewrap_prepares_content_rows_before_layout(cx: &mut TestAppContext) {
10195        cx.update(crate::init);
10196        for (value, expected_rows) in [("", 1), ("one\ntwo", 2)] {
10197            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10198                let font = window.text_style().font();
10199                cx.new(|cx| {
10200                    let mut state = crate::input::TextareaState::new(window, cx)
10201                        .rows(12)
10202                        .default_value(value);
10203                    assert_eq!(state.display_map().wrap_row_count(), 0);
10204                    state.prewrap(font, px(14.), px(120.), cx);
10205                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10206                    assert_eq!(state.value(), value);
10207                    state
10208                });
10209                gpui::EmptyView
10210            });
10211        }
10212    }
10213
10214    #[gpui::test]
10215    fn test_textarea_prewrap_respects_soft_wrap_before_layout(cx: &mut TestAppContext) {
10216        cx.update(crate::init);
10217        let value = "select id, name, email, phone from users where active\nlimit 10";
10218        for soft_wrap in [true, false] {
10219            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10220                let font = window.text_style().font();
10221                cx.new(|cx| {
10222                    let mut state = crate::input::TextareaState::new(window, cx)
10223                        .rows(1)
10224                        .soft_wrap(soft_wrap)
10225                        .default_value(value);
10226                    state.prewrap(font, px(14.), px(120.), cx);
10227                    let rows = state.display_map().wrap_row_count();
10228                    if soft_wrap {
10229                        assert!(rows > 2, "the first logical line must wrap");
10230                    } else {
10231                        assert_eq!(rows, 2);
10232                    }
10233                    assert_eq!(state.value(), value);
10234                    state
10235                });
10236                gpui::EmptyView
10237            });
10238        }
10239    }
10240
10241    #[gpui::test]
10242    fn test_prewrap_counts_wrapped_rows_before_the_first_paint(cx: &mut TestAppContext) {
10243        cx.update(crate::init);
10244        let text = "select id, name, email, phone from users where active\nlimit 10";
10245        for (soft_wrap, wraps) in [(true, true), (false, false)] {
10246            let mut input = None;
10247            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10248                let font = window.text_style().font();
10249                let editor = cx.new(|cx| {
10250                    let mut state = crate::input::EditorState::new(window, cx)
10251                        .soft_wrap(soft_wrap)
10252                        .default_value(text);
10253                    state.prewrap(font, px(14.), px(120.), cx);
10254                    state
10255                });
10256                input = Some(editor);
10257                gpui::EmptyView
10258            });
10259            let rows = input
10260                .unwrap()
10261                .read_with(cx, |state, _| state.display_map().wrap_row_count());
10262            // Two lines; at 120px the first wraps unless soft wrap is off.
10263            assert_eq!(rows > 2, wraps, "soft_wrap({soft_wrap}): {rows} rows");
10264            if !wraps {
10265                assert_eq!(rows, 2);
10266            }
10267        }
10268    }
10269
10270    #[gpui::test]
10271    fn test_prewrap_uses_the_configured_tab_stops(cx: &mut TestAppContext) {
10272        cx.update(crate::init);
10273        cx.open_window(size(px(400.), px(100.)), |window, cx| {
10274            let font = window.text_style().font();
10275            let font_size = px(14.);
10276            let font_id = window.text_system().resolve_font(&font);
10277            let space_width = window.text_system().layout_width(font_id, font_size, ' ');
10278            cx.new(|cx| {
10279                let mut state = crate::input::EditorState::new(window, cx)
10280                    .tab_size(TabSize {
10281                        tab_size: 4,
10282                        hard_tabs: true,
10283                    })
10284                    .default_value("\t\t");
10285                for (tab_size, expected_rows) in [(4, 2), (2, 1), (8, 2)] {
10286                    state.set_tab_size(
10287                        TabSize {
10288                            tab_size,
10289                            hard_tabs: true,
10290                        },
10291                        cx,
10292                    );
10293                    state.prewrap(font.clone(), font_size, space_width * 5. + RIGHT_MARGIN, cx);
10294                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10295                }
10296                state
10297            });
10298            gpui::EmptyView
10299        });
10300    }
10301
10302    /// Prewrap counts with the state's wrapping indent, as the first layout
10303    /// does: continuation rows indented as deep as their line take more rows.
10304    #[gpui::test]
10305    fn test_prewrap_wraps_with_the_wrapping_indent(cx: &mut TestAppContext) {
10306        cx.update(crate::init);
10307        let text = "            select id, name, email, phone from users where active";
10308        let mut rows = Vec::new();
10309        for indent in [WrappingIndent::Same, WrappingIndent::None] {
10310            let mut input = None;
10311            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10312                let font = window.text_style().font();
10313                input = Some(cx.new(|cx| {
10314                    let mut state = crate::input::EditorState::new(window, cx)
10315                        .wrapping_indent(indent)
10316                        .default_value(text);
10317                    state.prewrap(font, px(14.), px(200.), cx);
10318                    state
10319                }));
10320                gpui::EmptyView
10321            });
10322            rows.push(
10323                input
10324                    .unwrap()
10325                    .read_with(cx, |state, _| state.display_map().wrap_row_count()),
10326            );
10327        }
10328        assert!(rows[0] > rows[1], "rows with Same, None: {rows:?}");
10329    }
10330
10331    /// Once the editor is laid out, layout owns the wrap and prewrap leaves it.
10332    #[gpui::test]
10333    fn test_prewrap_does_nothing_once_laid_out(cx: &mut TestAppContext) {
10334        struct Frame(Entity<crate::input::EditorState>);
10335        impl Render for Frame {
10336            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10337                crate::input::InputBase::new("frame")
10338                    .h(px(100.))
10339                    .child(crate::input::Editor::new(&self.0))
10340            }
10341        }
10342
10343        cx.update(crate::init);
10344        let text = "select id, name, email, phone from users where active\nlimit 10";
10345        let mut input = None;
10346        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
10347            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
10348            input = Some(state.clone());
10349            Frame(state)
10350        });
10351        let input = input.unwrap();
10352        let mut cx = VisualTestContext::from_window(window.into(), cx);
10353        cx.update(|window, cx| window.draw(cx).clear(cx));
10354
10355        let laid_out = input.read_with(&cx, |state, _| state.display_map().wrap_row_count());
10356        assert!(laid_out >= 2, "laid out to {laid_out} rows");
10357        let font = cx.update(|window, _| window.text_style().font());
10358        input.update(&mut cx, |state, cx| {
10359            state.prewrap(font, px(14.), px(60.), cx)
10360        });
10361        assert_eq!(
10362            input.read_with(&cx, |state, _| state.display_map().wrap_row_count()),
10363            laid_out
10364        );
10365    }
10366
10367    /// Soft wrap is on by default, for every mode that can wrap.
10368    ///
10369    /// The default lives in the shared constructor, where a mode-specific
10370    /// `new` can silently fail to restore it; this pins it down.
10371    #[gpui::test]
10372    fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
10373        let textarea = InputView::build_textarea(cx, |state| state);
10374        let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
10375        textarea
10376            .input
10377            .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
10378
10379        let editor = InputView::<EditorMode>::new(cx);
10380        let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
10381        editor
10382            .input
10383            .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
10384    }
10385
10386    /// Parse a cursor spec into `(text, cursor_offsets)`. Non-empty lines are
10387    /// joined with `\n` plus a trailing `\n`. `|` marks a cursor. Leading
10388    /// whitespace is kept, so a spec can express indentation.
10389    fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
10390        let mut full_text = String::new();
10391        let mut cursor_offsets = Vec::new();
10392        let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
10393
10394        for (line_idx, line) in non_empty_lines.iter().enumerate() {
10395            let mut positions = Vec::new();
10396            let mut text = String::new();
10397            for ch in line.chars() {
10398                if ch == '|' {
10399                    positions.push(text.len());
10400                } else {
10401                    text.push(ch);
10402                }
10403            }
10404
10405            if line_idx > 0 {
10406                full_text.push('\n');
10407            }
10408            let line_start = full_text.len();
10409            for pos in positions {
10410                cursor_offsets.push(line_start + pos);
10411            }
10412            full_text.push_str(&text);
10413        }
10414        full_text.push('\n');
10415
10416        (full_text, cursor_offsets)
10417    }
10418
10419    /// Build a multi-line input for multi-cursor tests.
10420    fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
10421        InputView::build_textarea(cx, |state| state)
10422    }
10423
10424    /// Set the text and cursor positions from a spec (see [`parse_cursor_spec`]).
10425    fn setup_cursors<M: InputModeKind>(
10426        cx: &mut VisualTestContext,
10427        input: &Entity<InputBaseState<M>>,
10428        spec: &str,
10429    ) {
10430        let (full_text, offsets) = parse_cursor_spec(spec);
10431        cx.update(|window, cx| {
10432            input.update(cx, |state, cx| {
10433                state.set_value(&full_text, window, cx);
10434                let selections = offsets
10435                    .into_iter()
10436                    .map(|offset| {
10437                        CursorSelection::new(state.selections.generate_id(), offset, offset)
10438                    })
10439                    .collect();
10440                state.selections.replace_all(selections);
10441                cx.notify();
10442            });
10443        });
10444    }
10445
10446    /// Assert the text and cursor positions match a spec.
10447    #[track_caller]
10448    fn assert_cursors<M: InputModeKind>(
10449        cx: &mut VisualTestContext,
10450        input: &Entity<InputBaseState<M>>,
10451        spec: &str,
10452    ) {
10453        let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
10454        expected_cursors.sort();
10455
10456        let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
10457            (
10458                state.text.to_string(),
10459                state
10460                    .selections
10461                    .iter()
10462                    .map(|s| s.cursor_offset())
10463                    .collect::<Vec<_>>(),
10464            )
10465        });
10466        actual_cursors.sort();
10467
10468        assert_eq!(
10469            actual_text, expected_text,
10470            "Text mismatch:\nExpected: {expected_text:?}\nActual:   {actual_text:?}"
10471        );
10472        assert_eq!(
10473            actual_cursors, expected_cursors,
10474            "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual:   {actual_cursors:?}"
10475        );
10476    }
10477
10478    #[gpui::test]
10479    fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
10480        cx.update(crate::init);
10481        let view = InputView::<EditorMode>::new(cx);
10482        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10483        for modifiers in [
10484            gpui::Modifiers {
10485                alt: true,
10486                ..Default::default()
10487            },
10488            gpui::Modifiers {
10489                alt: true,
10490                shift: true,
10491                ..Default::default()
10492            },
10493            #[cfg(target_os = "linux")]
10494            gpui::Modifiers {
10495                alt: true,
10496                control: true,
10497                ..Default::default()
10498            },
10499        ] {
10500            setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
10501            cx.update(|window, cx| {
10502                view.input.update(cx, |state, cx| state.focus(window, cx));
10503            });
10504            let (start, end) = view.input.read_with(&cx, |state, _| {
10505                let layout = state.last_layout.as_ref().unwrap();
10506                let origin = state.last_bounds.unwrap().origin;
10507                let position = |row: usize, col| {
10508                    let local = layout.lines[row]
10509                        .position_for_index(col, layout, false)
10510                        .unwrap();
10511                    origin
10512                        + point(
10513                            layout.line_number_width + local.x,
10514                            layout.line_height * (row as f32 + 0.5),
10515                        )
10516                };
10517                (position(0, 1), position(2, 3))
10518            });
10519            // Land inside the third column instead of exactly on its trailing
10520            // glyph boundary, where pixel rounding can select the next column.
10521            let end = point(end.x - px(0.5), end.y);
10522            // A cached Ctrl-hover definition must not steal a column gesture.
10523            cx.update(|_, cx| {
10524                view.input.update(cx, |state, _| {
10525                    state.extras.hover_definition.update(
10526                        0..4,
10527                        vec![lsp_types::LocationLink {
10528                            origin_selection_range: None,
10529                            target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
10530                            target_range: Default::default(),
10531                            target_selection_range: Default::default(),
10532                        }],
10533                    );
10534                });
10535            });
10536            cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10537            cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10538            cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10539            view.input.read_with(&cx, |state, _| {
10540                let ranges: Vec<_> = state
10541                    .selections
10542                    .iter()
10543                    .map(|sel| sel.start..sel.end)
10544                    .collect();
10545                assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
10546            });
10547            // Moving after release must leave the block intact.
10548            cx.simulate_mouse_move(start, None, modifiers);
10549            cx.simulate_keystrokes("x");
10550            assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
10551        }
10552    }
10553
10554    #[gpui::test]
10555    fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
10556        cx.update(crate::init);
10557        let view = InputView::<EditorMode>::new(cx);
10558        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10559        setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
10560        cx.update(|window, cx| {
10561            view.input.update(cx, |state, cx| state.focus(window, cx));
10562        });
10563        let (start, end) = view.input.read_with(&cx, |state, _| {
10564            let layout = state.last_layout.as_ref().unwrap();
10565            let origin = state.last_bounds.unwrap().origin;
10566            let local = layout.lines[0]
10567                .position_for_index(1, layout, false)
10568                .unwrap();
10569            let x = layout.line_number_width + local.x;
10570            (
10571                origin + point(x, layout.line_height * 2.5),
10572                origin + point(x, layout.line_height * 0.5),
10573            )
10574        });
10575        let modifiers = gpui::Modifiers {
10576            alt: true,
10577            ..Default::default()
10578        };
10579        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10580        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10581        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10582        assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
10583    }
10584
10585    #[gpui::test]
10586    fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
10587        cx.update(crate::init);
10588        let view = InputView::<EditorMode>::new(cx);
10589        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10590        setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
10591        cx.update(|window, cx| {
10592            view.input.update(cx, |state, cx| state.focus(window, cx));
10593        });
10594        // Drag from row 0 column 1 down to row 1, at the x of row 0's column 5. Row 1
10595        // only has two characters, so the pointer ends past its end.
10596        let (start, end) = view.input.read_with(&cx, |state, _| {
10597            let layout = state.last_layout.as_ref().unwrap();
10598            let origin = state.last_bounds.unwrap().origin;
10599            let x_of = |index| {
10600                layout.line_number_width
10601                    + layout.lines[0]
10602                        .position_for_index(index, layout, false)
10603                        .unwrap()
10604                        .x
10605            };
10606            (
10607                origin + point(x_of(1), layout.line_height * 0.5),
10608                origin + point(x_of(5), layout.line_height * 1.5),
10609            )
10610        });
10611        let modifiers = gpui::Modifiers {
10612            alt: true,
10613            shift: true,
10614            ..Default::default()
10615        };
10616        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10617        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10618        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10619
10620        // The short row is clipped to its own end; the long row keeps the full span.
10621        view.input.read_with(&cx, |state, _| {
10622            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
10623            assert_eq!(ranges, vec![(1, 5), (8, 9)]);
10624        });
10625    }
10626
10627    #[gpui::test]
10628    fn test_lost_mouse_release_ends_selection_on_plain_motion(cx: &mut TestAppContext) {
10629        cx.update(crate::init);
10630        let view = InputView::<EditorMode>::new(cx);
10631        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10632        setup_cursors(&mut cx, &view.input, "|alpha bravo charlie delta");
10633        let (start, end, beyond) = view.input.read_with(&cx, |state, _| {
10634            (
10635                state.range_to_bounds(&(0..1)).unwrap().center(),
10636                state.range_to_bounds(&(6..7)).unwrap().center(),
10637                state.range_to_bounds(&(18..19)).unwrap().center(),
10638            )
10639        });
10640        cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
10641        cx.simulate_mouse_move(end, MouseButton::Left, gpui::Modifiers::default());
10642        let selected = view.input.read_with(&cx, |state, _| {
10643            assert!(state.selecting);
10644            let text = state.selected_value();
10645            assert!(!text.is_empty());
10646            text
10647        });
10648        cx.simulate_mouse_move(beyond, None, gpui::Modifiers::default());
10649        view.input.read_with(&cx, |state, _| {
10650            assert!(!state.selecting);
10651            assert_eq!(state.selected_value(), selected);
10652        });
10653    }
10654
10655    #[gpui::test]
10656    fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
10657        cx.update(crate::init);
10658        let view = InputView::<EditorMode>::new(cx);
10659        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10660        setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
10661        let position = view.input.read_with(&cx, |state, _| {
10662            let layout = state.last_layout.as_ref().unwrap();
10663            state.last_bounds.unwrap().origin
10664                + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
10665        });
10666        let modifiers = gpui::Modifiers {
10667            alt: true,
10668            ..Default::default()
10669        };
10670        cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
10671        cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
10672        view.input.read_with(&cx, |state, _| {
10673            assert!(!state.selecting);
10674            assert!(state.column_select_start.is_none());
10675        });
10676    }
10677
10678    #[gpui::test]
10679    fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
10680        let view = InputView::<EditorMode>::new(cx);
10681        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10682        setup_cursors(&mut cx, &view.input, "a|b");
10683        cx.update(|window, cx| {
10684            view.input.update(cx, |state, cx| {
10685                state.focus(window, cx);
10686                state.pause_blink_cursor(cx);
10687            });
10688        });
10689        cx.run_until_parked();
10690        cx.executor()
10691            .advance_clock(std::time::Duration::from_millis(300));
10692        cx.run_until_parked();
10693        view.input.read_with(&cx, |state, cx| {
10694            assert!(!state.blink_cursor.read(cx).visible());
10695        });
10696        // Copy consumes its shortcut without editing text or moving selections.
10697        for _ in 0..5 {
10698            #[cfg(target_os = "macos")]
10699            cx.simulate_keystrokes("cmd-c");
10700            #[cfg(not(target_os = "macos"))]
10701            cx.simulate_keystrokes("ctrl-c");
10702            cx.run_until_parked();
10703            cx.executor()
10704                .advance_clock(std::time::Duration::from_millis(200));
10705            cx.run_until_parked();
10706            view.input.read_with(&cx, |state, cx| {
10707                assert!(state.blink_cursor.read(cx).visible());
10708            });
10709        }
10710    }
10711
10712    #[gpui::test]
10713    fn test_mouse_down_shows_cursor_like_a_cursor_move(cx: &mut TestAppContext) {
10714        cx.update(crate::init);
10715        let view = InputView::<EditorMode>::new(cx);
10716        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10717        setup_cursors(&mut cx, &view.input, "abcd|efgh");
10718        let position = |offset: Pixels, cx: &mut VisualTestContext| {
10719            view.input.read_with(cx, |state, _| {
10720                let layout = state.last_layout.as_ref().unwrap();
10721                state.last_bounds.unwrap().origin
10722                    + point(layout.line_number_width + offset, layout.line_height * 0.5)
10723            })
10724        };
10725        let visible = |cx: &mut VisualTestContext| {
10726            view.input
10727                .read_with(cx, |state, cx| state.blink_cursor.read(cx).visible())
10728        };
10729
10730        // The press itself shows the caret, without waiting for the focus
10731        // observer, and the idle delay holds it there like a cursor move.
10732        let first = position(px(2.), &mut cx);
10733        cx.simulate_mouse_down(first, MouseButton::Left, Default::default());
10734        assert!(visible(&mut cx));
10735        cx.simulate_mouse_up(first, MouseButton::Left, Default::default());
10736        cx.run_until_parked();
10737
10738        // Pressing elsewhere in the focused input, in the hidden phase of the
10739        // blink, shows the caret again at the press.
10740        cx.executor()
10741            .advance_clock(std::time::Duration::from_millis(400));
10742        cx.run_until_parked();
10743        assert!(!visible(&mut cx));
10744        let second = position(px(30.), &mut cx);
10745        cx.simulate_mouse_down(second, MouseButton::Left, Default::default());
10746        assert!(visible(&mut cx));
10747        cx.executor()
10748            .advance_clock(std::time::Duration::from_millis(250));
10749        cx.run_until_parked();
10750        assert!(visible(&mut cx));
10751        cx.simulate_mouse_up(second, MouseButton::Left, Default::default());
10752    }
10753
10754    #[gpui::test]
10755    fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
10756        let view = InputView::<EditorMode>::new(cx);
10757        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10758        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
10759        // Start each action in the hidden phase without depending on a
10760        // key-down listener: actions and text input also arrive directly.
10761        for action in 0..6 {
10762            cx.update(|_, cx| {
10763                view.input.update(cx, |state, cx| {
10764                    state.blink_cursor = cx.new(BlinkCursor::new);
10765                    state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
10766                });
10767            });
10768            cx.run_until_parked();
10769            cx.executor()
10770                .advance_clock(std::time::Duration::from_millis(500));
10771            cx.run_until_parked();
10772            view.input.read_with(&cx, |state, cx| {
10773                assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
10774            });
10775
10776            cx.update(|window, cx| {
10777                view.input.update(cx, |state, cx| {
10778                    match action {
10779                        0 => state.add_cursor_above(&AddCursorAbove, window, cx),
10780                        1 => state.add_cursor_below(&AddCursorBelow, window, cx),
10781                        2 => state.select_up(&SelectUp, window, cx),
10782                        3 => state.select_down(&SelectDown, window, cx),
10783                        4 => state.replace_text_in_range(None, "x", window, cx),
10784                        _ => state.backspace(&Backspace, window, cx),
10785                    }
10786                    assert!(state.blink_cursor.read(cx).visible(), "action {action}");
10787                });
10788            });
10789        }
10790    }
10791
10792    #[gpui::test]
10793    fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
10794        let view = InputView::<EditorMode>::new(cx);
10795        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10796        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
10797        cx.update(|window, cx| {
10798            view.input.update(cx, |state, cx| state.focus(window, cx));
10799        });
10800        #[cfg(target_os = "macos")]
10801        cx.simulate_keystrokes("cmd-alt-up");
10802        #[cfg(target_os = "windows")]
10803        cx.simulate_keystrokes("ctrl-alt-up");
10804        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
10805        cx.simulate_keystrokes("alt-shift-up");
10806        view.input
10807            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
10808        #[cfg(target_os = "macos")]
10809        cx.simulate_keystrokes("cmd-alt-down");
10810        #[cfg(target_os = "windows")]
10811        cx.simulate_keystrokes("ctrl-alt-down");
10812        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
10813        cx.simulate_keystrokes("alt-shift-down");
10814        view.input
10815            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
10816        cx.simulate_keystrokes("x");
10817        assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
10818    }
10819
10820    #[gpui::test]
10821    fn test_multi_cursor_platform_word_selection_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, "one |two\none |two");
10825        cx.update(|window, cx| {
10826            view.input.update(cx, |state, cx| state.focus(window, cx));
10827        });
10828        #[cfg(any(target_os = "macos", target_os = "linux"))]
10829        cx.simulate_keystrokes("alt-shift-right");
10830        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
10831        cx.simulate_keystrokes("ctrl-shift-right");
10832        cx.simulate_keystrokes("x");
10833        assert_cursors(&mut cx, &view.input, "one x|\none x|");
10834        setup_cursors(&mut cx, &view.input, "one two|\none two|");
10835        #[cfg(any(target_os = "macos", target_os = "linux"))]
10836        cx.simulate_keystrokes("alt-shift-left");
10837        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
10838        cx.simulate_keystrokes("ctrl-shift-left");
10839        cx.simulate_keystrokes("x");
10840        assert_cursors(&mut cx, &view.input, "one x|\none x|");
10841    }
10842
10843    #[cfg(not(target_os = "macos"))]
10844    #[gpui::test]
10845    fn test_multi_cursor_horizontal_selection_dispatch(cx: &mut TestAppContext) {
10846        let view = InputView::<EditorMode>::new(cx);
10847        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10848        setup_cursors(&mut cx, &view.input, "ab\na|b");
10849        cx.update(|window, cx| {
10850            view.input.update(cx, |state, cx| state.focus(window, cx));
10851        });
10852        #[cfg(target_os = "windows")]
10853        cx.simulate_keystrokes("ctrl-alt-up");
10854        #[cfg(not(target_os = "windows"))]
10855        cx.simulate_keystrokes("alt-shift-up");
10856        #[cfg(target_os = "linux")]
10857        cx.simulate_keystrokes("shift-right");
10858        #[cfg(not(target_os = "linux"))]
10859        cx.simulate_keystrokes("alt-shift-right");
10860        view.input.read_with(&cx, |state, _| {
10861            assert_eq!(
10862                state
10863                    .selections
10864                    .iter()
10865                    .map(|s| s.start..s.end)
10866                    .collect::<Vec<_>>(),
10867                vec![4..5, 1..2]
10868            );
10869        });
10870        #[cfg(target_os = "linux")]
10871        cx.simulate_keystrokes("shift-left shift-left");
10872        #[cfg(not(target_os = "linux"))]
10873        cx.simulate_keystrokes("alt-shift-left alt-shift-left");
10874        view.input.read_with(&cx, |state, _| {
10875            assert_eq!(
10876                state
10877                    .selections
10878                    .iter()
10879                    .map(|s| s.start..s.end)
10880                    .collect::<Vec<_>>(),
10881                vec![3..4, 0..1]
10882            );
10883        });
10884        cx.simulate_keystrokes("x");
10885        assert_cursors(&mut cx, &view.input, "x|b\nx|b");
10886    }
10887
10888    #[gpui::test]
10889    fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
10890        cx.update(crate::init);
10891        let view = InputView::<EditorMode>::new(cx);
10892        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10893        setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
10894        cx.update(|window, cx| {
10895            view.input.update(cx, |state, cx| state.focus(window, cx));
10896        });
10897        let position = view.input.read_with(&cx, |state, _| {
10898            let bounds = state.last_bounds.unwrap();
10899            let layout = state.last_layout.as_ref().unwrap();
10900            bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
10901        });
10902        cx.simulate_click(
10903            position,
10904            gpui::Modifiers {
10905                alt: true,
10906                ..Default::default()
10907            },
10908        );
10909        view.input
10910            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
10911    }
10912
10913    #[gpui::test]
10914    fn test_add_selection(cx: &mut TestAppContext) {
10915        let view = InputView::<EditorMode>::new(cx);
10916        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10917        cx.update(|window, cx| {
10918            view.input.update(cx, |state, cx| {
10919                state.focus(window, cx);
10920                state.set_value("foo bar foo", window, cx);
10921                state.set_selected_range(0..3, cx);
10922                // The programmatic second cursor: the next occurrence.
10923                state.add_selection(8..11, cx);
10924                // Adding a range that is already selected changes nothing.
10925                state.add_selection(0..3, cx);
10926            });
10927        });
10928        view.input.read_with(&cx, |state, _| {
10929            let mut ranges: Vec<Range<usize>> =
10930                state.selections.iter().map(|s| s.start..s.end).collect();
10931            ranges.sort_by_key(|r| r.start);
10932            assert_eq!(ranges, vec![0..3, 8..11]);
10933        });
10934        // Typing replaces every selection at once.
10935        cx.simulate_keystrokes("x");
10936        view.input.read_with(&cx, |state, _| {
10937            assert_eq!(state.text.to_string(), "x bar x")
10938        });
10939    }
10940
10941    #[gpui::test]
10942    fn test_add_selection_preserves_crlf_boundaries(cx: &mut TestAppContext) {
10943        let view = InputView::build_textarea(cx, |state| state.default_value("a\r\nb"));
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_selected_range(4..4, cx);
10949                state.add_selection(2..2, cx);
10950                let ranges: Vec<_> = state.selections.iter().map(|s| s.start..s.end).collect();
10951                assert_eq!(ranges, vec![4..4, 1..1]);
10952            });
10953        });
10954        cx.simulate_keystrokes("x");
10955        view.input.read_with(&cx, |state, _| {
10956            assert_eq!(state.value(), "ax\r\nbx");
10957        });
10958        cx.update(|window, cx| {
10959            view.input.update(cx, |state, cx| {
10960                state.set_value("a\r\nb", window, cx);
10961                state.set_selected_range(4..4, cx);
10962                state.add_selection(2..3, cx);
10963                state.cut(&Cut, window, cx);
10964                assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "\r\n");
10965                assert_eq!(state.value(), "ab");
10966            });
10967        });
10968    }
10969
10970    #[gpui::test]
10971    fn test_add_selection_merges_overlaps_before_copy_and_cut(cx: &mut TestAppContext) {
10972        let view = InputView::<EditorMode>::new(cx);
10973        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10974        cx.update(|window, cx| {
10975            view.input.update(cx, |state, cx| {
10976                // Cover partial overlaps, a containing range, and a bridge
10977                // between two previously disjoint selections.
10978                for additions in [vec![2..5], vec![0..5], vec![4..5, 2..4]] {
10979                    state.set_value("abcdef", window, cx);
10980                    state.set_selected_range(0..3, cx);
10981                    let active_id = state.active_selection().id;
10982                    for range in additions {
10983                        state.add_selection(range, cx);
10984                    }
10985                    assert_eq!(state.active_selection().id, active_id);
10986                    assert_eq!(state.selected_range(), 0..5);
10987                    assert_eq!(state.selections.len(), 1);
10988                    state.copy(&Copy, window, cx);
10989                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
10990                    state.cut(&Cut, window, cx);
10991                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
10992                    assert_eq!(state.value(), "f");
10993                    state.undo(&Undo, window, cx);
10994                    assert_eq!(state.value(), "abcdef");
10995                    assert_eq!(state.selected_range(), 0..5);
10996                }
10997            });
10998        });
10999    }
11000
11001    #[gpui::test]
11002    fn test_add_selection_clears_inline_completion(cx: &mut TestAppContext) {
11003        use crate::input::CompletionProvider;
11004        use gpui::Task;
11005        use lsp_types::{
11006            CompletionContext, CompletionResponse, InlineCompletionContext, InlineCompletionItem,
11007            InlineCompletionResponse,
11008        };
11009        use std::time::Duration;
11010
11011        struct Provider(Rc<Cell<usize>>);
11012
11013        impl CompletionProvider for Provider {
11014            fn is_completion_trigger(&self, _: usize, _: &str, _: &mut App) -> bool {
11015                false
11016            }
11017
11018            fn completions(
11019                &self,
11020                _: &Rope,
11021                _: usize,
11022                _: CompletionContext,
11023                _: &mut Window,
11024                _: &mut App,
11025            ) -> Task<anyhow::Result<CompletionResponse>> {
11026                Task::ready(Ok(CompletionResponse::Array(vec![])))
11027            }
11028
11029            fn inline_completion(
11030                &self,
11031                _: &Rope,
11032                _: usize,
11033                _: InlineCompletionContext,
11034                _: &mut Window,
11035                _: &mut App,
11036            ) -> Task<anyhow::Result<InlineCompletionResponse>> {
11037                self.0.set(self.0.get() + 1);
11038                Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
11039            }
11040        }
11041
11042        let view = InputView::<EditorMode>::new(cx);
11043        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11044        let calls = Rc::new(Cell::new(0));
11045        cx.update(|window, cx| {
11046            view.input.update(cx, |state, cx| {
11047                state.focus(window, cx);
11048                state.set_value("aa\naa", window, cx);
11049                state.set_selected_range(2..2, cx);
11050                state.extras.inline_completion.item = Some(InlineCompletionItem {
11051                    insert_text: "suggestion".into(),
11052                    filter_text: None,
11053                    range: None,
11054                    command: None,
11055                    insert_text_format: None,
11056                });
11057                state.add_selection(5..5, cx);
11058                assert!(!state.has_inline_completion());
11059                state.indent_inline(&IndentInline, window, cx);
11060                assert_eq!(state.value(), "aa  \naa  ");
11061                assert_eq!(state.selections.len(), 2);
11062
11063                // The active cursor stays put, so only canceling the task
11064                // prevents this pending request from fetching a suggestion.
11065                state.set_value("aa\naa", window, cx);
11066                state.set_selected_range(2..2, cx);
11067                state.extras.lsp.completion_provider = Some(Rc::new(Provider(calls.clone())));
11068                state.schedule_inline_completion(window, cx);
11069            });
11070        });
11071        cx.run_until_parked();
11072        cx.update(|_, cx| {
11073            view.input
11074                .update(cx, |state, cx| state.add_selection(5..5, cx));
11075        });
11076        cx.executor().advance_clock(Duration::from_secs(1));
11077        cx.run_until_parked();
11078        assert_eq!(calls.get(), 0);
11079        view.input.read_with(&cx, |state, _| {
11080            assert!(!state.has_inline_completion());
11081            assert_eq!(state.selections.len(), 2);
11082            assert_eq!(state.value(), "aa\naa");
11083        });
11084    }
11085
11086    #[gpui::test]
11087    fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
11088        let view = multi_line(cx);
11089        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11090        setup_cursors(&mut cx, &view.input, "hello|");
11091        cx.update(|window, cx| {
11092            view.input.update(cx, |state, cx| {
11093                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
11094                state.undo(&Undo, window, cx);
11095                assert_eq!(state.selected_range(), 5..5);
11096            });
11097        });
11098    }
11099
11100    #[gpui::test]
11101    fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
11102        let view = multi_line(cx);
11103        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11104        setup_cursors(&mut cx, &view.input, "a|b|c");
11105        cx.update(|window, cx| {
11106            view.input.update(cx, |state, cx| {
11107                state.backspace(&Backspace, window, cx);
11108                state.undo(&Undo, window, cx);
11109            });
11110        });
11111        assert_cursors(&mut cx, &view.input, "a|b|c");
11112    }
11113
11114    #[gpui::test]
11115    fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
11116        let view = InputView::<EditorMode>::new(cx);
11117        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11118        cx.update(|window, cx| {
11119            view.input.update(cx, |state, cx| {
11120                state.set_value("abcdef ".repeat(30), window, cx);
11121                state.display_map.on_layout_changed(Some(px(60.)), cx);
11122                let line = state.display_map.line(0).unwrap();
11123                assert!(line.wrapped_lines.len() > 1);
11124                let boundary = line.wrapped_lines[0].end;
11125                state.move_to_with_affinity(boundary, None, true, cx);
11126                state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
11127                assert_eq!(state.selected_range(), boundary..state.text.len());
11128            });
11129        });
11130    }
11131
11132    #[gpui::test]
11133    fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
11134        let view = multi_line(cx);
11135        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11136        setup_cursors(&mut cx, &view.input, "|你好\n|世界");
11137        cx.update(|window, cx| {
11138            view.input.update(cx, |state, cx| {
11139                state.outdent(false, window, cx);
11140                state.outdent(true, window, cx);
11141            });
11142        });
11143        assert_cursors(&mut cx, &view.input, "|你好\n|世界");
11144    }
11145
11146    #[gpui::test]
11147    fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
11148        let view = multi_line(cx);
11149        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11150        setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
11151        cx.update(|window, cx| {
11152            view.input.update(cx, |state, cx| {
11153                state.build_columnar_selection(
11154                    ColumnarPoint::new(1, 0),
11155                    ColumnarPoint::new(11, 0),
11156                    cx,
11157                );
11158                let text = state.value();
11159                for sel in state.selections.iter() {
11160                    assert!(text.is_char_boundary(sel.start));
11161                    assert!(text.is_char_boundary(sel.end));
11162                }
11163                state.replace_text_in_range(None, "X", window, cx);
11164            });
11165        });
11166    }
11167
11168    #[gpui::test]
11169    fn test_cursor_moves_and_deletes_whole_graphemes(cx: &mut TestAppContext) {
11170        let input_view = InputView::build(cx, |state| state);
11171        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
11172        let input = input_view.input;
11173
11174        let graphemes = ["a", "\u{267B}\u{FE0F}", "👍🏽", "👨‍👩‍👧", "🇸🇪", "e\u{301}", "b"];
11175        let text = graphemes.concat();
11176        let ends: Vec<usize> = graphemes
11177            .iter()
11178            .scan(0, |end, g| {
11179                *end += g.len();
11180                Some(*end)
11181            })
11182            .collect();
11183
11184        cx.update(|window, cx| {
11185            input.update(cx, |state, cx| {
11186                state.set_value(text.clone(), window, cx);
11187                state.set_selected_range(0..0, cx);
11188                for &end in &ends {
11189                    state.right(&MoveRight, window, cx);
11190                    assert_eq!(state.cursor(), end);
11191                }
11192                for &end in ends.iter().rev().skip(1).chain([&0]) {
11193                    state.left(&MoveLeft, window, cx);
11194                    assert_eq!(state.cursor(), end);
11195                }
11196
11197                state.set_selected_range(ends[3]..ends[3], cx);
11198                state.backspace(&Backspace, window, cx);
11199                assert_eq!(
11200                    state.value(),
11201                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[4..].concat()
11202                );
11203                state.delete(&Delete, window, cx);
11204                assert_eq!(
11205                    state.value(),
11206                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[5..].concat()
11207                );
11208            });
11209        });
11210    }
11211
11212    #[gpui::test]
11213    fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
11214        let view = InputView::<EditorMode>::new(cx);
11215        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11216        cx.update(|window, cx| {
11217            view.input.update(cx, |state, cx| {
11218                state.set_value("abc def", window, cx);
11219                state.create_decorations_collection(
11220                    vec![crate::input::TextDecoration::new(
11221                        4..7,
11222                        gpui::HighlightStyle::default(),
11223                    )],
11224                    cx,
11225                );
11226                state.set_selected_range(0..0, cx);
11227                state.replace_text_in_range(None, "X", window, cx);
11228                let layers = state.extras.decoration_layers();
11229                assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
11230            });
11231        });
11232    }
11233
11234    #[gpui::test]
11235    fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
11236        let view = InputView::<EditorMode>::new(cx);
11237        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11238        setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
11239        cx.update(|window, cx| {
11240            view.input.update(cx, |state, cx| {
11241                set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
11242                state.backspace(&Backspace, window, cx);
11243            });
11244        });
11245        assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
11246    }
11247
11248    #[gpui::test]
11249    fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
11250        struct UnexpectedQuery;
11251        impl crate::input::SyntaxContextProvider for UnexpectedQuery {
11252            fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
11253                panic!("ordinary typing must not query syntax");
11254            }
11255        }
11256        let view = InputView::<EditorMode>::new(cx);
11257        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11258        setup_cursors(&mut cx, &view.input, "|");
11259        cx.update(|window, cx| {
11260            view.input.update(cx, |state, cx| {
11261                set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
11262                for c in ["a", "b", "c"] {
11263                    state.replace_text_in_range(None, c, window, cx);
11264                }
11265            });
11266        });
11267        assert_cursors(&mut cx, &view.input, "abc|");
11268    }
11269
11270    #[gpui::test]
11271    fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
11272        let view = InputView::<EditorMode>::new(cx);
11273        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11274        setup_cursors(&mut cx, &view.input, "|");
11275        cx.update(|window, cx| {
11276            view.input.update(cx, |state, cx| {
11277                for _ in 0..999 {
11278                    state.replace_text_in_range(None, "a", window, cx);
11279                }
11280                state.replace_text_in_range(None, "(", window, cx);
11281                state.undo(&Undo, window, cx);
11282                assert!(!state.text.to_string().contains('('));
11283                assert!(!state.text.to_string().contains(')'));
11284                state.redo(&Redo, window, cx);
11285            });
11286        });
11287        assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
11288    }
11289
11290    #[gpui::test]
11291    fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
11292        let view = InputView::<EditorMode>::new(cx);
11293        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11294        setup_cursors(&mut cx, &view.input, "// (|)");
11295        cx.update(|window, cx| {
11296            view.input.update(cx, |state, cx| {
11297                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11298                state.replace_text_in_range(None, ")", window, cx);
11299            });
11300        });
11301        assert_cursors(&mut cx, &view.input, "// ()|)");
11302    }
11303
11304    #[gpui::test]
11305    fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
11306        let view = InputView::<EditorMode>::new(cx);
11307        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11308        setup_cursors(&mut cx, &view.input, "(a|)");
11309        let before = view.input.read_with(&cx, |state, _| state.text.to_string());
11310        cx.update(|window, cx| {
11311            view.input.update(cx, |state, cx| {
11312                state.replace_text_in_range(Some(2..2), ")", window, cx);
11313            });
11314        });
11315        assert_cursors(&mut cx, &view.input, "(a)|");
11316        cx.update(|window, cx| {
11317            view.input
11318                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11319        });
11320        view.input.read_with(&cx, |state, _| {
11321            assert_eq!(
11322                state.text.to_string(),
11323                before,
11324                "skip must not remove an existing closer on undo"
11325            );
11326        });
11327    }
11328
11329    #[gpui::test]
11330    fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11331        let view = InputView::<EditorMode>::new(cx);
11332        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11333        setup_cursors(&mut cx, &view.input, "|");
11334        cx.update(|window, cx| {
11335            view.input.update(cx, |state, cx| {
11336                state.replace_text_in_range(None, "(", window, cx);
11337            });
11338        });
11339        assert_cursors(&mut cx, &view.input, "(|)");
11340        cx.update(|window, cx| {
11341            view.input.update(cx, |state, cx| {
11342                state.undo(&Undo, window, cx);
11343                state.redo(&Redo, window, cx);
11344            });
11345        });
11346        assert_cursors(&mut cx, &view.input, "(|)");
11347    }
11348
11349    #[gpui::test]
11350    fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11351        let view = InputView::<EditorMode>::new(cx);
11352        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11353        setup_cursors(&mut cx, &view.input, "{|}");
11354        cx.update(|window, cx| {
11355            view.input.update(cx, |state, cx| {
11356                state.enter(
11357                    &Enter {
11358                        secondary: false,
11359                        shift: false,
11360                    },
11361                    window,
11362                    cx,
11363                );
11364            });
11365        });
11366        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11367        cx.update(|window, cx| {
11368            view.input.update(cx, |state, cx| {
11369                state.undo(&Undo, window, cx);
11370            });
11371        });
11372        assert_cursors(&mut cx, &view.input, "{|}");
11373        cx.update(|window, cx| {
11374            view.input
11375                .update(cx, |state, cx| state.redo(&Redo, window, cx));
11376        });
11377        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11378    }
11379
11380    #[gpui::test]
11381    fn test_auto_close_parens(cx: &mut TestAppContext) {
11382        let view = InputView::<EditorMode>::new(cx);
11383        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11384        setup_cursors(&mut cx, &view.input, "|");
11385        cx.update(|window, cx| {
11386            view.input.update(cx, |state, cx| {
11387                state.replace_text_in_range(None, "(", window, cx);
11388            });
11389        });
11390        assert_cursors(&mut cx, &view.input, "(|)");
11391        // Selection must be collapsed: typing next must insert, not replace.
11392        cx.update(|window, cx| {
11393            view.input.update(cx, |state, cx| {
11394                state.replace_text_in_range(None, "x", window, cx);
11395            });
11396        });
11397        assert_cursors(&mut cx, &view.input, "(x|)");
11398    }
11399
11400    #[gpui::test]
11401    fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
11402        let view = InputView::<EditorMode>::new(cx);
11403        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11404        setup_cursors(&mut cx, &view.input, "(|)");
11405        cx.update(|window, cx| {
11406            view.input.update(cx, |state, cx| {
11407                state.replace_text_in_range(None, ")", window, cx);
11408            });
11409        });
11410        // No duplicate closer, cursor moves past the existing one.
11411        assert_cursors(&mut cx, &view.input, "()|");
11412        // Selection must be collapsed, not covering blank space.
11413        view.input.read_with(&cx, |state, _| {
11414            assert!(state.active_selection().is_empty());
11415        });
11416    }
11417
11418    #[gpui::test]
11419    fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
11420        let view = InputView::<EditorMode>::new(cx);
11421        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11422        setup_cursors(&mut cx, &view.input, "don|");
11423        cx.update(|window, cx| {
11424            view.input.update(cx, |state, cx| {
11425                state.replace_text_in_range(None, "'", window, cx);
11426            });
11427        });
11428        // Contraction: no auto-close.
11429        assert_cursors(&mut cx, &view.input, "don'|");
11430    }
11431
11432    #[gpui::test]
11433    fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
11434        let view = InputView::<EditorMode>::new(cx);
11435        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11436        // Unicode-safe previous-char lookup: must not panic on multi-byte prefix.
11437        // CJK counts as word-like, so no pairing — single quote inserted.
11438        setup_cursors(&mut cx, &view.input, "中|");
11439        cx.update(|window, cx| {
11440            view.input.update(cx, |state, cx| {
11441                state.replace_text_in_range(None, "'", window, cx);
11442            });
11443        });
11444        assert_cursors(&mut cx, &view.input, "中'|");
11445    }
11446
11447    #[gpui::test]
11448    fn test_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
11449        let view = InputView::<EditorMode>::new(cx);
11450        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11451        // Cursor before existing closing quote: typing `"` skips past it.
11452        setup_cursors(&mut cx, &view.input, "\"hello|\"");
11453        cx.update(|window, cx| {
11454            view.input.update(cx, |state, cx| {
11455                state.replace_text_in_range(None, "\"", window, cx);
11456            });
11457        });
11458        assert_cursors(&mut cx, &view.input, "\"hello\"|");
11459        view.input.read_with(&cx, |state, _| {
11460            assert!(state.active_selection().is_empty());
11461        });
11462    }
11463
11464    #[gpui::test]
11465    fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
11466        let view = InputView::<EditorMode>::new(cx);
11467        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11468        // UTF-16 conversion: deleting `()` after CJK must not touch neighbors.
11469        setup_cursors(&mut cx, &view.input, "中(|)abc");
11470        cx.update(|window, cx| {
11471            view.input
11472                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11473        });
11474        assert_cursors(&mut cx, &view.input, "中|abc");
11475    }
11476
11477    #[gpui::test]
11478    fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
11479        let view = InputView::<EditorMode>::new(cx);
11480        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11481        setup_cursors(&mut cx, &view.input, "{|}");
11482        cx.update(|window, cx| {
11483            view.input.update(cx, |state, cx| {
11484                state.set_smart_indent(false, window, cx);
11485                state.enter(
11486                    &Enter {
11487                        secondary: false,
11488                        shift: false,
11489                    },
11490                    window,
11491                    cx,
11492                );
11493            });
11494        });
11495        // Smart indent controls both structural splitting and extra indentation.
11496        assert_cursors(&mut cx, &view.input, "{\n|}");
11497    }
11498
11499    #[gpui::test]
11500    fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
11501        let view = InputView::<EditorMode>::new(cx);
11502        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11503        setup_cursors(&mut cx, &view.input, "{|}");
11504        cx.update(|window, cx| {
11505            view.input.update(cx, |state, cx| {
11506                state.set_auto_close(false, window, cx);
11507                state.enter(
11508                    &Enter {
11509                        secondary: false,
11510                        shift: false,
11511                    },
11512                    window,
11513                    cx,
11514                );
11515            });
11516        });
11517        // Disabling automatic insertion does not disable structural indentation.
11518        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11519    }
11520
11521    #[gpui::test]
11522    fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
11523        use crate::input::{AutoClosingPair, set_language_config};
11524        let view = InputView::<EditorMode>::new(cx);
11525        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11526        cx.update(|window, cx| {
11527            set_language_config(
11528                "alpha",
11529                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
11530                cx,
11531            );
11532            set_language_config(
11533                "beta",
11534                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
11535                cx,
11536            );
11537            let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
11538            let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
11539            first.update(cx, |state, cx| {
11540                state.replace_text_in_range(None, "«", window, cx);
11541                assert_eq!(state.text().to_string(), "«»");
11542                state.set_value("", window, cx);
11543                state.set_smart_indent(false, window, cx);
11544                state.set_highlighter("beta", cx);
11545                assert!(!state.mode.is_smart_indent());
11546                state.replace_text_in_range(None, "‹", window, cx);
11547                assert_eq!(state.text().to_string(), "‹›");
11548                state.set_value("", window, cx);
11549                state.set_highlighter("unknown", cx);
11550                state.replace_text_in_range(None, "(", window, cx);
11551                assert_eq!(state.text().to_string(), "()");
11552            });
11553            second.update(cx, |state, cx| {
11554                state.replace_text_in_range(None, "‹", window, cx);
11555                assert_eq!(state.text().to_string(), "‹›");
11556            });
11557        });
11558    }
11559
11560    #[gpui::test]
11561    fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
11562        use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
11563        struct StringLanguages(Rc<Cell<usize>>);
11564        impl LanguageProvider for StringLanguages {
11565            fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
11566                self.0.set(self.0.get() + 1);
11567                Some(Rc::new(StringAllProvider))
11568            }
11569        }
11570        struct CodeLanguages;
11571        impl LanguageProvider for CodeLanguages {}
11572        let view = InputView::<EditorMode>::new(cx);
11573        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11574        cx.update(|window, cx| {
11575            let creations = Rc::new(Cell::new(0));
11576            set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
11577            view.input.update(cx, |state, cx| {
11578                state.replace_text_in_range(None, "(", window, cx);
11579                state.replace_text_in_range(None, "[", window, cx);
11580                assert_eq!(state.text().to_string(), "([");
11581                assert_eq!(
11582                    creations.get(),
11583                    1,
11584                    "retain the document provider between edits"
11585                );
11586            });
11587            set_language_provider(Rc::new(CodeLanguages), cx);
11588            view.input.update(cx, |state, cx| {
11589                state.replace_text_in_range(None, "{", window, cx);
11590                assert_eq!(state.text().to_string(), "([{}");
11591            });
11592        });
11593    }
11594
11595    #[gpui::test]
11596    fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
11597        use crate::input::{AutoClosingPair, set_language_config};
11598        let view = InputView::<EditorMode>::new(cx);
11599        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11600        setup_cursors(&mut cx, &view.input, "|");
11601        cx.update(|window, cx| {
11602            view.input.update(cx, |state, cx| {
11603                state.set_highlighter("CUSTOM", cx);
11604                state.set_auto_close(false, window, cx);
11605                state.set_smart_indent(false, window, cx);
11606            });
11607            set_language_config(
11608                "custom",
11609                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
11610                cx,
11611            );
11612            // Batched registrations must update every affected language.
11613            set_language_config("other", LanguageConfig::default(), cx);
11614            view.input.update(cx, |state, cx| {
11615                assert!(!state.mode.is_auto_close());
11616                assert!(!state.mode.is_smart_indent());
11617                state.set_auto_close(true, window, cx);
11618                state.replace_text_in_range(None, "«", window, cx);
11619            });
11620        });
11621        assert_cursors(&mut cx, &view.input, "«|»");
11622    }
11623
11624    #[gpui::test]
11625    fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
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, "|word");
11629        cx.update(|window, cx| {
11630            view.input.update(cx, |state, cx| {
11631                state.replace_text_in_range(None, "(", window, cx)
11632            });
11633        });
11634        assert_cursors(&mut cx, &view.input, "(|word");
11635        setup_cursors(&mut cx, &view.input, "|word");
11636        cx.update(|window, cx| {
11637            view.input.update(cx, |state, cx| {
11638                crate::input::set_language_config(
11639                    state.language_name(),
11640                    LanguageConfig::default().auto_close_before("w"),
11641                    cx,
11642                );
11643                state.replace_text_in_range(None, "(", window, cx);
11644            });
11645        });
11646        assert_cursors(&mut cx, &view.input, "(|)word");
11647    }
11648
11649    #[gpui::test]
11650    fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
11651        use crate::input::{AutoClosingPair, SyntaxContext};
11652        let view = InputView::<EditorMode>::new(cx);
11653        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11654        setup_cursors(&mut cx, &view.input, "|");
11655        cx.update(|window, cx| {
11656            view.input.update(cx, |state, cx| {
11657                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11658                crate::input::set_language_config(
11659                    state.language_name(),
11660                    LanguageConfig::default().auto_closing_pairs([
11661                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
11662                        AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
11663                    ]),
11664                    cx,
11665                );
11666                state.replace_text_in_range(None, "(", window, cx);
11667                state.replace_text_in_range(None, "[", window, cx);
11668            });
11669        });
11670        assert_cursors(&mut cx, &view.input, "([|)");
11671    }
11672
11673    #[gpui::test]
11674    fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
11675        use crate::input::{AutoClosingPair, SyntaxContext};
11676        struct BlockComment;
11677        impl crate::input::SyntaxContextProvider for BlockComment {
11678            fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
11679                if text.to_string().contains("/*") {
11680                    SyntaxContext::Comment
11681                } else {
11682                    SyntaxContext::Code
11683                }
11684            }
11685        }
11686        let view = InputView::<EditorMode>::new(cx);
11687        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11688        setup_cursors(&mut cx, &view.input, "|");
11689        cx.update(|window, cx| {
11690            view.input.update(cx, |state, cx| {
11691                set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
11692                crate::input::set_language_config(
11693                    state.language_name(),
11694                    LanguageConfig::default()
11695                        .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
11696                            .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
11697                    cx,
11698                );
11699                state.replace_text_in_range(None, "/", window, cx);
11700                state.replace_text_in_range(None, "*", window, cx);
11701            });
11702        });
11703        assert_cursors(&mut cx, &view.input, "/*|*/");
11704        cx.update(|window, cx| {
11705            view.input
11706                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11707        });
11708        assert_cursors(&mut cx, &view.input, "|");
11709        cx.update(|window, cx| {
11710            view.input.update(cx, |state, cx| {
11711                state.undo(&Undo, window, cx);
11712                state.replace_text_in_range(None, "*", window, cx);
11713                state.replace_text_in_range(None, "/", window, cx);
11714            });
11715        });
11716        assert_cursors(&mut cx, &view.input, "/**/|");
11717    }
11718
11719    #[gpui::test]
11720    fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
11721        use crate::input::BracketPair;
11722        let view = InputView::<EditorMode>::new(cx);
11723        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11724        setup_cursors(&mut cx, &view.input, "|");
11725        cx.update(|window, cx| {
11726            view.input.update(cx, |state, cx| {
11727                let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
11728                rules.auto_closing_pairs = None;
11729                crate::input::set_language_config(state.language_name(), rules.clone(), cx);
11730                state.replace_text_in_range(None, "«", window, cx);
11731                crate::input::set_language_config(
11732                    state.language_name(),
11733                    rules.auto_closing_pairs([]),
11734                    cx,
11735                );
11736                state.replace_text_in_range(None, "«", window, cx);
11737            });
11738        });
11739        assert_cursors(&mut cx, &view.input, "««|»");
11740    }
11741
11742    #[gpui::test]
11743    fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
11744        use crate::input::{AutoClosingPair, SyntaxContext};
11745        let view = InputView::<EditorMode>::new(cx);
11746        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11747        setup_cursors(&mut cx, &view.input, "|");
11748        cx.update(|window, cx| {
11749            view.input.update(cx, |state, cx| {
11750                crate::input::set_language_config(
11751                    state.language_name(),
11752                    LanguageConfig::default()
11753                        .auto_closing_pairs([
11754                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11755                        ]),
11756                    cx,
11757                );
11758                state.replace_text_in_range(None, "/", window, cx);
11759                state.replace_text_in_range(None, "*", window, cx);
11760                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11761                state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
11762                state.undo(&Undo, window, cx);
11763                state.replace_text_in_range(None, "*", window, cx);
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_does_not_promote_literal_comment_delimiters(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                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11779                crate::input::set_language_config(
11780                    state.language_name(),
11781                    LanguageConfig::default()
11782                        .auto_closing_pairs([
11783                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11784                        ]),
11785                    cx,
11786                );
11787                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
11788                state.undo(&Undo, window, cx);
11789                state.backspace(&Backspace, window, cx);
11790            });
11791        });
11792        assert_cursors(&mut cx, &view.input, "/|*/");
11793    }
11794
11795    #[gpui::test]
11796    fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
11797        use crate::input::{AutoClosingPair, SyntaxContext};
11798        struct CommentScope;
11799        impl crate::input::SyntaxContextProvider for CommentScope {
11800            fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
11801                if text
11802                    .to_string()
11803                    .find("*/")
11804                    .is_some_and(|end| offset < end + 2)
11805                {
11806                    SyntaxContext::Comment
11807                } else {
11808                    SyntaxContext::Code
11809                }
11810            }
11811        }
11812        let view = InputView::<EditorMode>::new(cx);
11813        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11814        setup_cursors(&mut cx, &view.input, "|");
11815        cx.update(|window, cx| {
11816            view.input.update(cx, |state, cx| {
11817                set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
11818                crate::input::set_language_config(
11819                    state.language_name(),
11820                    LanguageConfig::default().auto_closing_pairs([
11821                        AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
11822                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
11823                    ]),
11824                    cx,
11825                );
11826                state.replace_text_in_range(None, "/", window, cx);
11827                state.replace_text_in_range(None, "*", window, cx);
11828                state.set_selected_range(4..4, cx);
11829                state.replace_text_in_range(None, "(", window, cx);
11830                state.set_selected_range(2..2, cx);
11831                state.replace_text_in_range(None, "*", window, cx);
11832                state.replace_text_in_range(None, "/", window, cx);
11833            });
11834        });
11835        assert_cursors(&mut cx, &view.input, "/**/|()");
11836        cx.update(|window, cx| {
11837            view.input.update(cx, |state, cx| {
11838                state.set_selected_range(2..2, cx);
11839                state.backspace(&Backspace, window, cx);
11840                state.undo(&Undo, window, cx);
11841                state.redo(&Redo, window, cx);
11842            });
11843        });
11844        assert_cursors(&mut cx, &view.input, "|()");
11845    }
11846
11847    #[gpui::test]
11848    fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
11849        use crate::input::{AutoClosingPair, SyntaxContext};
11850        let view = InputView::<EditorMode>::new(cx);
11851        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11852        setup_cursors(&mut cx, &view.input, "|");
11853        cx.update(|window, cx| {
11854            view.input.update(cx, |state, cx| {
11855                crate::input::set_language_config(
11856                    state.language_name(),
11857                    LanguageConfig::default()
11858                        .auto_closing_pairs([
11859                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
11860                        ]),
11861                    cx,
11862                );
11863                state.replace_text_in_range(None, "/", window, cx);
11864                state.replace_text_in_range(None, "*", window, cx);
11865                state.replace_text_in_range(Some(0..2), "//", window, cx);
11866                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11867                state.replace_text_in_range(None, "*", window, cx);
11868            });
11869        });
11870        assert_cursors(&mut cx, &view.input, "//*|*/");
11871    }
11872
11873    #[gpui::test]
11874    fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
11875        use crate::input::IndentationRules;
11876        let view = InputView::<EditorMode>::new(cx);
11877        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11878        setup_cursors(&mut cx, &view.input, "BEGIN|");
11879        cx.update(|window, cx| {
11880            view.input.update(cx, |state, cx| {
11881                let rules = |insensitive| {
11882                    LanguageConfig::default().indentation_rules(IndentationRules::new(
11883                        regex::RegexBuilder::new("begin$")
11884                            .case_insensitive(insensitive)
11885                            .build()
11886                            .unwrap(),
11887                        regex::Regex::new("^end").unwrap(),
11888                    ))
11889                };
11890                crate::input::set_language_config(state.language_name(), rules(false), cx);
11891                crate::input::set_language_config(state.language_name(), rules(true), cx);
11892                state.enter(
11893                    &Enter {
11894                        secondary: false,
11895                        shift: false,
11896                    },
11897                    window,
11898                    cx,
11899                );
11900            });
11901        });
11902        assert_cursors(&mut cx, &view.input, "BEGIN\n  |");
11903    }
11904
11905    #[gpui::test]
11906    fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
11907        use crate::input::IndentationRules;
11908        let view = InputView::<EditorMode>::new(cx);
11909        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11910        let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
11911            regex::Regex::new(r"\bbegin\s*$").unwrap(),
11912            regex::Regex::new(r"^\s*end\b").unwrap(),
11913        ));
11914        for (before, expected) in [("begin|", "begin\n  |"), ("  |end", "  \n|end")] {
11915            setup_cursors(&mut cx, &view.input, before);
11916            cx.update(|window, cx| {
11917                view.input.update(cx, |state, cx| {
11918                    crate::input::set_language_config(state.language_name(), rules.clone(), cx);
11919                    state.enter(
11920                        &Enter {
11921                            secondary: false,
11922                            shift: false,
11923                        },
11924                        window,
11925                        cx,
11926                    );
11927                });
11928            });
11929            assert_cursors(&mut cx, &view.input, expected);
11930        }
11931    }
11932
11933    #[gpui::test]
11934    fn test_custom_language_config(cx: &mut TestAppContext) {
11935        let view = InputView::<EditorMode>::new(cx);
11936        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11937        cx.update(|_window, cx| {
11938            view.input.update(cx, |state, cx| {
11939                crate::input::set_language_config(
11940                    state.language_name(),
11941                    crate::input::language_config::LanguageConfig::default()
11942                        .brackets([crate::input::BracketPair::new("«", "»")])
11943                        .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
11944                    cx,
11945                );
11946            });
11947        });
11948        // Custom pair closes.
11949        setup_cursors(&mut cx, &view.input, "|");
11950        cx.update(|window, cx| {
11951            view.input.update(cx, |state, cx| {
11952                state.replace_text_in_range(None, "«", window, cx);
11953            });
11954        });
11955        assert_cursors(&mut cx, &view.input, "«|»");
11956        // Default `(` no longer pairs under custom rules.
11957        cx.update(|window, cx| {
11958            view.input.update(cx, |state, cx| {
11959                state.set_value("\n", window, cx);
11960                state.set_selected_range(0..0, cx);
11961                state.replace_text_in_range(None, "(", window, cx);
11962            });
11963        });
11964        assert_cursors(&mut cx, &view.input, "(|");
11965    }
11966
11967    #[gpui::test]
11968    fn test_skip_records_no_history(cx: &mut TestAppContext) {
11969        let view = InputView::<EditorMode>::new(cx);
11970        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11971        setup_cursors(&mut cx, &view.input, "(a|)");
11972        cx.update(|window, cx| {
11973            view.input.update(cx, |state, cx| {
11974                // Type a normal char (recorded), then skip over `)`.
11975                state.replace_text_in_range(None, "b", window, cx);
11976            });
11977        });
11978        assert_cursors(&mut cx, &view.input, "(ab|)");
11979        cx.update(|window, cx| {
11980            view.input.update(cx, |state, cx| {
11981                state.replace_text_in_range(None, ")", window, cx);
11982            });
11983        });
11984        // Skip is a pure cursor move: no history entry of its own.
11985        assert_cursors(&mut cx, &view.input, "(ab)|");
11986        // Undo removes `b`, never exposing a transient `())`.
11987        cx.update(|window, cx| {
11988            view.input
11989                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11990        });
11991        assert_cursors(&mut cx, &view.input, "(a|)");
11992    }
11993
11994    #[gpui::test]
11995    fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
11996        let view = InputView::<EditorMode>::new(cx);
11997        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11998        setup_cursors(&mut cx, &view.input, "|");
11999        cx.update(|window, cx| {
12000            view.input.update(cx, |state, cx| {
12001                state.replace_text_in_range(None, "(", window, cx);
12002            });
12003        });
12004        assert_cursors(&mut cx, &view.input, "(|)");
12005        // One undo removes the whole pair (typing coalescing).
12006        cx.update(|window, cx| {
12007            view.input
12008                .update(cx, |state, cx| state.undo(&Undo, window, cx));
12009        });
12010        assert_cursors(&mut cx, &view.input, "|");
12011    }
12012
12013    #[gpui::test]
12014    fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
12015        let view = InputView::<EditorMode>::new(cx);
12016        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12017        // Odd backslashes: the typed quote is escaped, insert literally.
12018        setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
12019        cx.update(|window, cx| {
12020            view.input.update(cx, |state, cx| {
12021                state.replace_text_in_range(None, "\"", window, cx);
12022            });
12023        });
12024        assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
12025    }
12026
12027    #[gpui::test]
12028    fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
12029        let view = InputView::<EditorMode>::new(cx);
12030        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12031        // Even backslashes: quote is not escaped, skip over the terminator.
12032        setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
12033        cx.update(|window, cx| {
12034            view.input.update(cx, |state, cx| {
12035                state.replace_text_in_range(None, "\"", window, cx);
12036            });
12037        });
12038        assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
12039    }
12040
12041    #[gpui::test]
12042    fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
12043        use crate::input::{BracketPair, LanguageConfig};
12044
12045        let view = InputView::<EditorMode>::new(cx);
12046        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12047        cx.update(|window, cx| {
12048            view.input.update(cx, |state, cx| {
12049                // Language changes update rules without changing editor preferences.
12050                state.set_smart_indent(false, window, cx);
12051                crate::input::set_language_config(
12052                    state.language_name(),
12053                    LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
12054                    cx,
12055                );
12056            });
12057        });
12058        view.input.read_with(&cx, |state, _| {
12059            assert!(!state.mode.is_smart_indent(), "editor option preserved");
12060            assert!(state.mode.is_auto_close());
12061            let pairs = &state.mode.language_config().unwrap().brackets;
12062            assert_eq!(pairs.len(), 1, "pairs follow configuration");
12063            assert_eq!(pairs[0].open.as_ref(), "«");
12064        });
12065    }
12066
12067    struct CommentAllProvider;
12068    impl crate::input::SyntaxContextProvider for CommentAllProvider {
12069        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12070            crate::input::SyntaxContext::Comment
12071        }
12072    }
12073
12074    struct StringAllProvider;
12075    impl crate::input::SyntaxContextProvider for StringAllProvider {
12076        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12077            crate::input::SyntaxContext::String
12078        }
12079    }
12080
12081    #[gpui::test]
12082    fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
12083        use std::rc::Rc;
12084
12085        let view = InputView::<EditorMode>::new(cx);
12086        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12087        cx.update(|_window, cx| {
12088            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12089        });
12090        // Trigger `{` inside a string: no extra level, base indent only.
12091        setup_cursors(&mut cx, &view.input, "  x = {|");
12092        cx.update(|window, cx| {
12093            view.input.update(cx, |state, cx| {
12094                state.enter(
12095                    &Enter {
12096                        secondary: false,
12097                        shift: false,
12098                    },
12099                    window,
12100                    cx,
12101                );
12102            });
12103        });
12104        assert_cursors(&mut cx, &view.input, "  x = {\n  |");
12105    }
12106
12107    #[gpui::test]
12108    fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
12109        use std::rc::Rc;
12110
12111        let view = InputView::<EditorMode>::new(cx);
12112        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12113        cx.update(|_window, cx| {
12114            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12115        });
12116        // No three-way split inside strings: plain newline instead.
12117        setup_cursors(&mut cx, &view.input, "{|}");
12118        cx.update(|window, cx| {
12119            view.input.update(cx, |state, cx| {
12120                state.enter(
12121                    &Enter {
12122                        secondary: false,
12123                        shift: false,
12124                    },
12125                    window,
12126                    cx,
12127                );
12128            });
12129        });
12130        assert_cursors(&mut cx, &view.input, "{\n|}");
12131    }
12132
12133    #[gpui::test]
12134    fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
12135        use std::rc::Rc;
12136
12137        let view = InputView::<EditorMode>::new(cx);
12138        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12139        cx.update(|_window, cx| {
12140            set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
12141        });
12142        setup_cursors(&mut cx, &view.input, "|");
12143        cx.update(|window, cx| {
12144            view.input.update(cx, |state, cx| {
12145                state.replace_text_in_range(None, "(", window, cx);
12146            });
12147        });
12148        // In comments every character is literal.
12149        assert_cursors(&mut cx, &view.input, "(|");
12150    }
12151
12152    #[gpui::test]
12153    fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
12154        let view = InputView::<EditorMode>::new(cx);
12155        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12156        setup_cursors(&mut cx, &view.input, "{|}");
12157        cx.update(|window, cx| {
12158            view.input
12159                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12160        });
12161        assert_cursors(&mut cx, &view.input, "|");
12162    }
12163
12164    #[gpui::test]
12165    fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
12166        let view = InputView::<EditorMode>::new(cx);
12167        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12168        setup_cursors(&mut cx, &view.input, "{d|}");
12169        cx.update(|window, cx| {
12170            view.input
12171                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12172        });
12173        // Only `d` is deleted, the closing brace stays.
12174        assert_cursors(&mut cx, &view.input, "{|}");
12175    }
12176
12177    #[gpui::test]
12178    fn test_enter_splits_brackets(cx: &mut TestAppContext) {
12179        let view = InputView::<EditorMode>::new(cx);
12180        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12181        setup_cursors(&mut cx, &view.input, "{|}");
12182        cx.update(|window, cx| {
12183            view.input.update(cx, |state, cx| {
12184                state.enter(
12185                    &Enter {
12186                        secondary: false,
12187                        shift: false,
12188                    },
12189                    window,
12190                    cx,
12191                );
12192            });
12193        });
12194        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
12195        // Selection must be collapsed: typing next must insert, not replace.
12196        view.input.read_with(&cx, |state, _| {
12197            assert!(state.active_selection().is_empty());
12198        });
12199        cx.update(|window, cx| {
12200            view.input.update(cx, |state, cx| {
12201                state.replace_text_in_range(None, "x", window, cx);
12202            });
12203        });
12204        assert_cursors(&mut cx, &view.input, "{\n  x|\n}");
12205    }
12206
12207    #[gpui::test]
12208    fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
12209        let view = InputView::<EditorMode>::new(cx);
12210        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12211        setup_cursors(&mut cx, &view.input, "fn main() {|");
12212        cx.update(|window, cx| {
12213            view.input.update(cx, |state, cx| {
12214                state.enter(
12215                    &Enter {
12216                        secondary: false,
12217                        shift: false,
12218                    },
12219                    window,
12220                    cx,
12221                );
12222            });
12223        });
12224        assert_cursors(&mut cx, &view.input, "fn main() {\n  |");
12225    }
12226
12227    #[gpui::test]
12228    fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
12229        let view = multi_line(cx);
12230        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12231        setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12232        cx.update(|window, cx| {
12233            view.input
12234                .update(cx, |state, cx| state.indent(true, window, cx));
12235        });
12236        assert_cursors(&mut cx, &view.input, "  |ab\n  |cd\n  |ef");
12237        cx.update(|window, cx| {
12238            view.input
12239                .update(cx, |state, cx| state.outdent(true, window, cx));
12240        });
12241        assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12242    }
12243
12244    #[gpui::test]
12245    fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
12246        let view = multi_line(cx);
12247        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12248        setup_cursors(&mut cx, &view.input, "ab\n | cd");
12249        cx.update(|window, cx| {
12250            view.input
12251                .update(cx, |state, cx| state.outdent(true, window, cx));
12252        });
12253        assert_cursors(&mut cx, &view.input, "ab\n|cd");
12254    }
12255
12256    #[gpui::test]
12257    fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
12258        let view = InputView::build(cx, |state| state);
12259        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12260        cx.update(|window, cx| {
12261            view.input.update(cx, |state, cx| {
12262                state.set_value("abc", window, cx);
12263                state.set_selected_range(1..2, cx);
12264                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
12265                state.replace_text_in_range(None, "你", window, cx);
12266                state.undo(&Undo, window, cx);
12267                assert_eq!(state.value(), "abc");
12268                assert_eq!(state.selected_range(), 1..2);
12269                state.redo(&Redo, window, cx);
12270                assert_eq!(state.selected_range(), 4..4);
12271            });
12272        });
12273    }
12274
12275    #[gpui::test]
12276    fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
12277        let view = multi_line(cx);
12278        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12279        cx.update(|window, cx| {
12280            view.input.update(cx, |state, cx| {
12281                state.set_value("abc", window, cx);
12282                state.set_selected_range(1..1, cx);
12283                state.replace_text_in_range(None, "X", window, cx);
12284                state.set_selected_range(0..0, cx);
12285                state.replace_text_in_range(None, "", window, cx);
12286                state.undo(&Undo, window, cx);
12287                state.redo(&Redo, window, cx);
12288                assert_eq!(state.value(), "aXbc");
12289                assert_eq!(state.selected_range(), 2..2);
12290            });
12291        });
12292    }
12293
12294    #[gpui::test]
12295    fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
12296        let view = multi_line(cx);
12297        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12298        let input = view.input;
12299
12300        setup_cursors(&mut cx, &input, "|hello |world|");
12301        cx.update(|window, cx| {
12302            input.update(cx, |state, cx| {
12303                state.replace_text_in_range(None, ">>>", window, cx);
12304            });
12305        });
12306        assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
12307    }
12308
12309    #[gpui::test]
12310    fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
12311        let view = multi_line(cx);
12312        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12313        let input = view.input;
12314
12315        setup_cursors(&mut cx, &input, "|islands| cars|");
12316        cx.update(|window, cx| {
12317            input.update(cx, |state, cx| {
12318                state.backspace(&Backspace, window, cx);
12319            });
12320        });
12321        // The first cursor has nothing to delete. The others delete an `s`.
12322        assert_cursors(&mut cx, &input, "|island| car|");
12323    }
12324
12325    #[gpui::test]
12326    fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
12327        let view = multi_line(cx);
12328        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12329        let input = view.input;
12330
12331        setup_cursors(&mut cx, &input, "hello| |world");
12332        cx.update(|window, cx| {
12333            input.update(cx, |state, cx| {
12334                state.delete(&Delete, window, cx);
12335            });
12336        });
12337        // Adjacent deletions merge into a single cursor.
12338        assert_cursors(&mut cx, &input, "hello|orld");
12339    }
12340
12341    #[gpui::test]
12342    fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
12343        let view = multi_line(cx);
12344        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12345        let input = view.input;
12346
12347        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12348        cx.update(|window, cx| {
12349            input.update(cx, |state, cx| {
12350                state.replace_text_in_range(None, "a", window, cx);
12351            });
12352        });
12353        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12354
12355        // The whole multi-edit insert is a single undo transaction.
12356        input.read_with(&cx, |state, _| {
12357            assert_eq!(state.undo_manager.undo_count(), 1);
12358        });
12359
12360        cx.update(|window, cx| {
12361            input.update(cx, |state, cx| {
12362                state.backspace(&Backspace, window, cx);
12363            });
12364        });
12365        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12366    }
12367
12368    #[gpui::test]
12369    fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
12370        let view = multi_line(cx);
12371        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12372        let input = view.input;
12373
12374        setup_cursors(&mut cx, &input, "ab|cd\nabcd");
12375        cx.update(|window, cx| {
12376            input.update(cx, |state, cx| {
12377                state.add_cursor_below(&AddCursorBelow, window, cx);
12378            });
12379        });
12380        assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
12381    }
12382
12383    #[gpui::test]
12384    fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
12385        let view = multi_line(cx);
12386        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12387        let input = view.input;
12388
12389        setup_cursors(&mut cx, &input, "he|llo");
12390        cx.update(|_, cx| {
12391            input.update(cx, |state, cx| {
12392                // Duplicate of the existing cursor is rejected.
12393                state.add_cursor_at(2, cx);
12394                assert_eq!(state.selections.len(), 1);
12395                // A distinct offset adds a cursor.
12396                state.add_cursor_at(4, cx);
12397                assert_eq!(state.selections.len(), 2);
12398            });
12399        });
12400    }
12401
12402    #[gpui::test]
12403    fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
12404        let view = multi_line(cx);
12405        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12406        let input = view.input;
12407
12408        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12409        cx.update(|window, cx| {
12410            input.update(cx, |state, cx| {
12411                state.replace_text_in_range(None, "a", window, cx);
12412            });
12413        });
12414        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12415
12416        cx.update(|window, cx| {
12417            input.update(cx, |state, cx| {
12418                state.undo(&Undo, window, cx);
12419            });
12420        });
12421        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12422
12423        cx.update(|window, cx| {
12424            input.update(cx, |state, cx| {
12425                state.redo(&Redo, window, cx);
12426            });
12427        });
12428        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12429    }
12430
12431    #[gpui::test]
12432    fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
12433        let view = multi_line(cx);
12434        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12435        let input = view.input;
12436
12437        setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12438        cx.update(|window, cx| {
12439            input.update(cx, |state, cx| {
12440                state.replace_text_in_range(None, "a", window, cx);
12441            });
12442        });
12443        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12444
12445        cx.update(|window, cx| {
12446            input.update(cx, |state, cx| {
12447                state.undo(&Undo, window, cx);
12448            });
12449        });
12450        assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12451
12452        cx.update(|window, cx| {
12453            input.update(cx, |state, cx| {
12454                state.redo(&Redo, window, cx);
12455            });
12456        });
12457        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12458    }
12459
12460    #[gpui::test]
12461    fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
12462        let view = multi_line(cx);
12463        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12464        let input = view.input;
12465
12466        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12467        for ch in ['a', 'b', 'c'] {
12468            cx.update(|window, cx| {
12469                input.update(cx, |state, cx| {
12470                    state.replace_text_in_range(None, &ch.to_string(), window, cx);
12471                });
12472            });
12473        }
12474        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12475
12476        // The repeated keystrokes form one typing gesture.
12477        cx.update(|window, cx| {
12478            input.update(cx, |state, cx| {
12479                assert_eq!(state.undo_manager.undo_count(), 1);
12480                state.undo(&Undo, window, cx);
12481            });
12482        });
12483        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12484
12485        cx.update(|window, cx| {
12486            input.update(cx, |state, cx| {
12487                state.redo(&Redo, window, cx);
12488            });
12489        });
12490        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12491    }
12492
12493    #[gpui::test]
12494    fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
12495        let view = multi_line(cx);
12496        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12497        let input = view.input;
12498
12499        setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12500        for _ in 0..3 {
12501            cx.update(|window, cx| {
12502                input.update(cx, |state, cx| {
12503                    state.backspace(&Backspace, window, cx);
12504                });
12505            });
12506        }
12507        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12508
12509        cx.update(|window, cx| {
12510            input.update(cx, |state, cx| {
12511                assert_eq!(state.undo_manager.undo_count(), 1);
12512                state.undo(&Undo, window, cx);
12513            });
12514        });
12515        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12516    }
12517
12518    #[gpui::test]
12519    fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
12520        let view = multi_line(cx);
12521        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12522        let input = view.input;
12523
12524        setup_cursors(&mut cx, &input, "|1\n2\n3");
12525        cx.update(|window, cx| {
12526            input.update(cx, |state, cx| {
12527                state.replace_text_in_range(None, "a", window, cx);
12528                state.add_cursor_below(&AddCursorBelow, window, cx);
12529                state.replace_text_in_range(None, "b", window, cx);
12530            });
12531        });
12532        assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
12533
12534        // The keystroke after the cursor was added is its own undo entry.
12535        cx.update(|window, cx| {
12536            input.update(cx, |state, cx| {
12537                state.undo(&Undo, window, cx);
12538            });
12539        });
12540        assert_cursors(&mut cx, &input, "a|1\n2|\n3");
12541    }
12542
12543    #[gpui::test]
12544    fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
12545        let view = multi_line(cx);
12546        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12547        let input = view.input;
12548
12549        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12550        cx.update(|window, cx| {
12551            input.update(cx, |state, cx| {
12552                state.indent_inline(&IndentInline, window, cx);
12553                assert_eq!(state.undo_manager.undo_count(), 1);
12554                state.undo(&Undo, window, cx);
12555            });
12556        });
12557        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12558    }
12559
12560    #[gpui::test]
12561    fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
12562        let view = multi_line(cx);
12563        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12564        let input = view.input;
12565
12566        // Cursors at line starts.
12567        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12568        cx.update(|window, cx| {
12569            input.update(cx, |state, cx| {
12570                state.indent(false, window, cx);
12571            });
12572        });
12573        assert_cursors(&mut cx, &input, "  |1\n  |2\n  |3");
12574
12575        cx.update(|window, cx| {
12576            input.update(cx, |state, cx| {
12577                state.outdent(false, window, cx);
12578            });
12579        });
12580        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12581    }
12582
12583    #[gpui::test]
12584    fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
12585        let view = multi_line(cx);
12586        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12587        let input = view.input;
12588
12589        // A mid-line indent lands at the cursor, and the outdent does not
12590        // take it back: it only ever removes leading line indentation.
12591        setup_cursors(&mut cx, &input, "1|2\n1|2");
12592        cx.update(|window, cx| {
12593            input.update(cx, |state, cx| {
12594                state.indent(false, window, cx);
12595            });
12596        });
12597        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
12598
12599        cx.update(|window, cx| {
12600            input.update(cx, |state, cx| {
12601                state.outdent(false, window, cx);
12602            });
12603        });
12604        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
12605
12606        // A line with leading indentation loses that, wherever the cursor is.
12607        setup_cursors(&mut cx, &input, "  1|2\n  1|2");
12608        cx.update(|window, cx| {
12609            input.update(cx, |state, cx| {
12610                state.outdent(false, window, cx);
12611            });
12612        });
12613        assert_cursors(&mut cx, &input, "1|2\n1|2");
12614    }
12615
12616    #[gpui::test]
12617    fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
12618        let view = multi_line(cx);
12619        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12620        let input = view.input;
12621
12622        setup_cursors(&mut cx, &input, "a|b\nc|d");
12623        cx.update(|window, cx| {
12624            input.update(cx, |state, cx| {
12625                let before: Vec<_> = state.selections.iter().copied().collect();
12626                state.set_readonly(true, cx);
12627                state.backspace(&Backspace, window, cx);
12628                state.indent_inline(&IndentInline, window, cx);
12629
12630                assert_eq!(state.value(), "ab\ncd\n");
12631                assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
12632            });
12633        });
12634    }
12635
12636    #[gpui::test]
12637    fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
12638        let view = multi_line(cx);
12639        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12640        let input = view.input;
12641
12642        setup_cursors(&mut cx, &input, "x|\n|y");
12643        cx.update(|window, cx| {
12644            input.update(cx, |state, cx| {
12645                let mut selections: Vec<_> = state.selections.iter().copied().collect();
12646                selections.swap(0, 1);
12647                state.selections.replace_all(selections);
12648                let active_id = state.active_selection().id;
12649                state.replace_text_in_range(None, "!", window, cx);
12650                assert_eq!(state.active_selection().id, active_id);
12651            });
12652        });
12653    }
12654
12655    #[gpui::test]
12656    fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
12657        let view = multi_line(cx);
12658        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12659        let input = view.input;
12660
12661        cx.update(|window, cx| {
12662            input.update(cx, |state, cx| {
12663                state.set_value("line1\nline2\nline3", window, cx);
12664                let id = state.selections.generate_id();
12665                state
12666                    .selections
12667                    .replace_all(vec![CursorSelection::new(id, 0, 17)]);
12668                cx.notify();
12669            });
12670        });
12671
12672        cx.update(|window, cx| {
12673            input.update(cx, |state, cx| {
12674                state.indent(true, window, cx);
12675            });
12676        });
12677        input.read_with(&cx, |state, _| {
12678            assert_eq!(state.text.to_string(), "  line1\n  line2\n  line3");
12679        });
12680
12681        cx.update(|window, cx| {
12682            input.update(cx, |state, cx| {
12683                state.outdent(true, window, cx);
12684            });
12685        });
12686        input.read_with(&cx, |state, _| {
12687            assert_eq!(state.text.to_string(), "line1\nline2\nline3");
12688        });
12689    }
12690
12691    #[gpui::test]
12692    fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
12693        let view = multi_line(cx);
12694        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12695        let input = view.input;
12696
12697        setup_cursors(
12698            &mut cx,
12699            &input,
12700            "on|e two three\none t|wo three\non|e two three",
12701        );
12702
12703        cx.update(|window, cx| {
12704            input.update(cx, |state, cx| {
12705                state.move_to_next_word(&MoveToNextWord, window, cx);
12706            });
12707        });
12708        assert_cursors(
12709            &mut cx,
12710            &input,
12711            "one| two three\none two| three\none| two three",
12712        );
12713
12714        cx.update(|window, cx| {
12715            input.update(cx, |state, cx| {
12716                state.move_to_previous_word(&MoveToPreviousWord, window, cx);
12717            });
12718        });
12719        assert_cursors(
12720            &mut cx,
12721            &input,
12722            "|one two three\none |two three\n|one two three",
12723        );
12724
12725        // Move to end/start of document collapses to a single cursor.
12726        cx.update(|window, cx| {
12727            input.update(cx, |state, cx| {
12728                state.move_to_end(&MoveToEnd, window, cx);
12729            });
12730        });
12731        input.read_with(&cx, |state, _| {
12732            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12733            assert_eq!(cursors, vec![state.text.len()]);
12734        });
12735
12736        cx.update(|window, cx| {
12737            input.update(cx, |state, cx| {
12738                state.move_to_start(&MoveToStart, window, cx);
12739            });
12740        });
12741        input.read_with(&cx, |state, _| {
12742            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12743            assert_eq!(cursors, vec![0]);
12744        });
12745    }
12746
12747    #[gpui::test]
12748    fn test_rtl_arrow_keys_move_visually(cx: &mut TestAppContext) {
12749        let view = multi_line(cx);
12750        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12751        let input = view.input;
12752        // Each Arabic letter is two bytes.
12753        let text = "مرحبا عالم";
12754        let place = |cx: &mut VisualTestContext, offset: usize| {
12755            cx.update(|window, cx| {
12756                input.update(cx, |state, cx| {
12757                    state.set_value(text, window, cx);
12758                    let id = state.selections.generate_id();
12759                    state
12760                        .selections
12761                        .replace_all(vec![CursorSelection::new(id, offset, offset)]);
12762                });
12763            });
12764        };
12765        let selection = |cx: &mut VisualTestContext| {
12766            input.read_with(cx, |state, _| {
12767                let sel = state.active_selection();
12768                (sel.start, sel.end, sel.cursor_offset())
12769            })
12770        };
12771
12772        cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
12773
12774        // Right moves toward the start of a right-to-left paragraph.
12775        place(&mut cx, 4);
12776        cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
12777        assert_eq!(selection(&mut cx).2, 2);
12778        cx.update(|window, cx| input.update(cx, |s, cx| s.left(&MoveLeft, window, cx)));
12779        assert_eq!(selection(&mut cx).2, 4);
12780
12781        // Shift-arrows extend the selection the same way.
12782        cx.update(|window, cx| input.update(cx, |s, cx| s.select_right(&SelectRight, window, cx)));
12783        assert_eq!(selection(&mut cx), (2, 4, 2));
12784        place(&mut cx, 4);
12785        cx.update(|window, cx| input.update(cx, |s, cx| s.select_left(&SelectLeft, window, cx)));
12786        assert_eq!(selection(&mut cx), (4, 6, 6));
12787
12788        // Word movement: Right goes to the previous word start.
12789        let second_word = text.find('ع').unwrap();
12790        place(&mut cx, text.len());
12791        cx.update(|window, cx| {
12792            input.update(cx, |s, cx| s.move_to_next_word(&MoveToNextWord, window, cx))
12793        });
12794        assert_eq!(selection(&mut cx).2, second_word);
12795        place(&mut cx, 0);
12796        cx.update(|window, cx| {
12797            input.update(cx, |s, cx| {
12798                s.move_to_previous_word(&MoveToPreviousWord, window, cx)
12799            })
12800        });
12801        assert_eq!(selection(&mut cx).2, text.find(' ').unwrap());
12802
12803        // Left to right keeps the logical meaning.
12804        cx.update(|_, cx| crate::LayoutDirection::Ltr.set_global(cx));
12805        place(&mut cx, 4);
12806        cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
12807        assert_eq!(selection(&mut cx).2, 6);
12808    }
12809
12810    #[gpui::test]
12811    fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
12812        let view = multi_line(cx);
12813        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12814        let input = view.input;
12815
12816        setup_cursors(
12817            &mut cx,
12818            &input,
12819            "on|e two three\none t|wo three\non|e two three",
12820        );
12821        cx.update(|window, cx| {
12822            input.update(cx, |state, cx| {
12823                state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
12824            });
12825        });
12826        assert_cursors(
12827            &mut cx,
12828            &input,
12829            "|one two three\n|one two three\n|one two three",
12830        );
12831
12832        // Select to document start collapses to the active cursor only.
12833        setup_cursors(
12834            &mut cx,
12835            &input,
12836            "on|e two three\none t|wo three\non|e two three",
12837        );
12838        cx.update(|window, cx| {
12839            input.update(cx, |state, cx| {
12840                state.select_to_start(&SelectToStart, window, cx);
12841            });
12842        });
12843        input.read_with(&cx, |state, _| {
12844            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
12845            assert_eq!(cursors, vec![0]);
12846        });
12847    }
12848
12849    #[gpui::test]
12850    fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
12851        let view = multi_line(cx);
12852        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12853        let input = view.input;
12854
12855        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
12856        cx.update(|window, cx| {
12857            input.update(cx, |state, cx| {
12858                state.select_right(&SelectRight, window, cx);
12859            });
12860        });
12861        input.read_with(&cx, |state, _| {
12862            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12863            assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
12864        });
12865
12866        cx.update(|window, cx| {
12867            input.update(cx, |state, cx| {
12868                state.replace_text_in_range(None, "x", window, cx);
12869            });
12870        });
12871        assert_cursors(&mut cx, &input, "x|\nx|\nx|");
12872    }
12873
12874    #[gpui::test]
12875    fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
12876        let view = multi_line(cx);
12877        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12878        let input = view.input;
12879
12880        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
12881        cx.update(|window, cx| {
12882            input.update(cx, |state, cx| {
12883                state.escape(&Escape, window, cx);
12884            });
12885        });
12886        input.read_with(&cx, |state, _| {
12887            assert_eq!(state.selections.len(), 1);
12888        });
12889    }
12890
12891    #[gpui::test]
12892    fn test_build_columnar_selection(cx: &mut TestAppContext) {
12893        let view = multi_line(cx);
12894        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12895        let input = view.input;
12896
12897        setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
12898        cx.update(|_, cx| {
12899            input.update(cx, |state, cx| {
12900                // From row 0 col 1 to row 2 col 3.
12901                state.build_columnar_selection(
12902                    ColumnarPoint::new(1, 0),
12903                    ColumnarPoint::new(13, 0),
12904                    cx,
12905                );
12906                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12907                assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
12908            });
12909        });
12910    }
12911
12912    #[gpui::test]
12913    fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
12914        let view = multi_line(cx);
12915        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12916        let input = view.input;
12917
12918        setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
12919        cx.update(|_, cx| {
12920            input.update(cx, |state, cx| {
12921                // Ends on the short row, 3 columns past its end: the block still spans
12922                // columns 1..5, and only that row is clipped to what it has.
12923                state.build_columnar_selection(
12924                    ColumnarPoint::new(1, 0),
12925                    ColumnarPoint::new(9, 3),
12926                    cx,
12927                );
12928                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
12929                assert_eq!(ranges, vec![(1, 5), (8, 9)]);
12930            });
12931        });
12932    }
12933
12934    #[gpui::test]
12935    fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
12936        let view = multi_line(cx);
12937        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12938        let input = view.input;
12939
12940        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12941        cx.update(|_, cx| {
12942            cx.write_to_clipboard(ClipboardItem::new_string("x\ny\nz".to_string()));
12943        });
12944        cx.update(|window, cx| {
12945            input.update(cx, |state, cx| {
12946                state.paste(&Paste, window, cx);
12947            });
12948        });
12949        // One clipboard line per cursor.
12950        assert_cursors(&mut cx, &input, "x|1\ny|2\nz|3");
12951    }
12952
12953    #[gpui::test]
12954    fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
12955        use gpui::{ClipboardEntry, Image, ImageFormat};
12956
12957        let input_view = InputView::build(cx, |state| state);
12958        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
12959        let input = input_view.input;
12960
12961        cx.update(|window, cx| {
12962            input.update(cx, |state, cx| {
12963                state.set_value("hello world", window, cx);
12964                state.select_all(window, cx);
12965                cx.write_to_clipboard(ClipboardItem {
12966                    entries: vec![ClipboardEntry::Image(Image::from_bytes(
12967                        ImageFormat::Png,
12968                        vec![0x89, b'P', b'N', b'G'],
12969                    ))],
12970                });
12971
12972                // An image-only clipboard must not replace the selection
12973                // with nothing.
12974                state.paste(&Paste, window, cx);
12975                assert_eq!(state.value(), "hello world");
12976                assert_eq!(state.selected_range(), 0..11);
12977            });
12978        });
12979    }
12980
12981    #[gpui::test]
12982    fn test_paste_target_tracks_edits_and_selections(cx: &mut TestAppContext) {
12983        let view = multi_line(cx);
12984        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12985        let input = view.input;
12986
12987        setup_cursors(&mut cx, &input, "ab|c");
12988        let target = input.read_with(&cx, |state, _| state.paste_target());
12989        // Nothing happened: a paste asked for then still applies.
12990        assert_eq!(
12991            input.read_with(&cx, |state, _| state.paste_target()),
12992            target
12993        );
12994
12995        // Moving the caret changes where the paste would go.
12996        cx.update(|_, cx| {
12997            input.update(cx, |state, cx| {
12998                let id = state.selections.generate_id();
12999                state
13000                    .selections
13001                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13002                cx.notify();
13003            });
13004        });
13005        let moved = input.read_with(&cx, |state, _| state.paste_target());
13006        assert_ne!(moved, target);
13007
13008        // Editing the text changes it too, even with the caret put back.
13009        cx.update(|window, cx| {
13010            input.update(cx, |state, cx| {
13011                state.replace_text_in_range_silent(None, "x", window, cx);
13012                let id = state.selections.generate_id();
13013                state
13014                    .selections
13015                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13016            });
13017        });
13018        assert_ne!(input.read_with(&cx, |state, _| state.paste_target()), moved);
13019    }
13020
13021    #[gpui::test]
13022    fn character_index_for_point_finds_each_letter_where_it_is_drawn(cx: &mut TestAppContext) {
13023        // With a gutter and without, on the first line and on the lines after it.
13024        for line_number in [true, false] {
13025            let input_view = InputView::build_editor(cx, move |state| {
13026                state
13027                    .line_number(line_number)
13028                    .default_value("Teh quick\nbrown fox\njumps")
13029            });
13030            let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13031            visual.update(|window, cx| window.draw(cx).clear(cx));
13032
13033            visual.update(|window, cx| {
13034                input_view.input.update(cx, |state, cx| {
13035                    let bounds = state.text_bounds().unwrap();
13036                    for index in [0, 5, 8, 10, 14, 18, 20, 24] {
13037                        let middle = state
13038                            .bounds_for_range(index..index + 1, bounds, window, cx)
13039                            .unwrap()
13040                            .center();
13041                        assert_eq!(
13042                            state.character_index_for_point(middle, window, cx),
13043                            Some(index),
13044                            "line numbers: {line_number}"
13045                        );
13046                    }
13047                });
13048            });
13049        }
13050    }
13051
13052    #[gpui::test]
13053    fn test_ime_candidate_bounds_fallback_before_repaint(cx: &mut TestAppContext) {
13054        let input_view = InputView::build_textarea(cx, |state| {
13055            state.default_value("这是一段已经输入的中文文字")
13056        });
13057        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13058        visual.update(|window, cx| window.draw(cx).clear(cx));
13059
13060        visual.update(|window, cx| {
13061            input_view.input.update(cx, |state, cx| {
13062                state.focus(window, cx);
13063                let len = state.text.len();
13064                state.set_cursor_to(len);
13065            });
13066        });
13067        visual.update(|window, cx| window.draw(cx).clear(cx));
13068
13069        visual.update(|window, cx| {
13070            input_view.input.update(cx, |state, cx| {
13071                let bounds = state.text_bounds().unwrap_or_default();
13072                let before = state.selected_text_range(false, window, cx).unwrap().range;
13073                let previous = state
13074                    .bounds_for_range(before.end..before.end, bounds, window, cx)
13075                    .unwrap();
13076
13077                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
13078
13079                let after = state.selected_text_range(false, window, cx).unwrap().range;
13080                let pending = state
13081                    .bounds_for_range(after.end..after.end, bounds, window, cx)
13082                    .unwrap();
13083
13084                assert!(
13085                    (pending.origin.x - previous.origin.x).abs() < px(40.0),
13086                    "pending origin.x {:?} must remain close to previous origin.x {:?}",
13087                    pending.origin.x,
13088                    previous.origin.x
13089                );
13090
13091                let range_bounds = state
13092                    .bounds_for_range(before.end..after.end, bounds, window, cx)
13093                    .unwrap();
13094                assert!(
13095                    (range_bounds.origin.x - previous.origin.x).abs() < px(40.0),
13096                    "range_bounds origin.x {:?} must remain close to previous origin.x {:?}",
13097                    range_bounds.origin.x,
13098                    previous.origin.x
13099                );
13100                assert!(range_bounds.size.width >= px(0.0));
13101            });
13102        });
13103    }
13104
13105    #[gpui::test]
13106    fn test_ime_candidate_bounds_multiline_line_end(cx: &mut TestAppContext) {
13107        let input_view =
13108            InputView::build_textarea(cx, |state| state.default_value("First line\nSecond line"));
13109        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13110        visual.update(|window, cx| window.draw(cx).clear(cx));
13111
13112        visual.update(|window, cx| {
13113            input_view.input.update(cx, |state, cx| {
13114                state.focus(window, cx);
13115                // Position at end of first line ("First line".len() == 10)
13116                state.set_cursor_to(10);
13117            });
13118        });
13119        visual.update(|window, cx| window.draw(cx).clear(cx));
13120
13121        visual.update(|window, cx| {
13122            input_view.input.update(cx, |state, cx| {
13123                let bounds = state.text_bounds().unwrap_or_default();
13124                let candidate_bounds = state.bounds_for_range(10..10, bounds, window, cx).unwrap();
13125
13126                // Candidate bounds for end of line 0 must be positioned at the end of line 0,
13127                // and must not jump to the start of the next line (column 0).
13128                let line_number_width = state
13129                    .last_layout
13130                    .as_ref()
13131                    .map(|l| l.line_number_width)
13132                    .unwrap_or_default();
13133                assert!(
13134                    candidate_bounds.origin.x > bounds.origin.x + line_number_width,
13135                    "candidate bounds at line end must be past the line start, got {:?}",
13136                    candidate_bounds.origin.x
13137                );
13138
13139                let (line_idx, sub_line, pos) = state.line_and_position_for_offset(10);
13140                assert_eq!(line_idx, 0);
13141                assert_eq!(sub_line, 0);
13142                assert!(pos.is_some());
13143                assert!(pos.unwrap().x > line_number_width);
13144            });
13145        });
13146    }
13147}
13148
13149/// Methods that only a single-line input offers.
13150impl InputBaseState<crate::input::InputMode> {
13151    /// Create a single-line text input state.
13152    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13153        Self::new_in_mode(window, cx)
13154    }
13155
13156    /// Set a custom step function of the [`super::NumberInput`].
13157    ///
13158    /// The `f` receives the current value and the [`StepAction`], and returns
13159    /// the step to apply, so the step can vary with the value.
13160    ///
13161    /// # Example
13162    ///
13163    /// ```ignore
13164    /// // At the boundary 1.0 the step is 0.1 going down and 0.5 going up.
13165    /// InputState::new(window, cx).step_by(|value, action, _cx| match action {
13166    ///     StepAction::Increment => if value < 1.0 { 0.1 } else { 0.5 },
13167    ///     StepAction::Decrement => if value <= 1.0 { 0.1 } else { 0.5 },
13168    /// })
13169    /// ```
13170    pub fn step_by(mut self, f: impl Fn(f64, StepAction, &mut App) -> f64 + 'static) -> Self {
13171        self.number_step = Some(NumberStep::by_value(f));
13172        self
13173    }
13174
13175    /// Set with password masked state.
13176    pub fn masked(mut self, masked: bool) -> Self {
13177        self.masked = masked;
13178        self
13179    }
13180
13181    /// Set the password masked state of the input field.
13182    pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
13183        self.masked = masked;
13184        cx.notify();
13185    }
13186
13187    /// Set the regular expression pattern of the input field.
13188    pub fn pattern(mut self, pattern: regex::Regex) -> Self {
13189        self.pattern = Some(pattern);
13190        self
13191    }
13192
13193    /// Set the regular expression pattern of the input field with reference.
13194    pub fn set_pattern(
13195        &mut self,
13196        pattern: regex::Regex,
13197        _window: &mut Window,
13198        _cx: &mut Context<Self>,
13199    ) {
13200        self.pattern = Some(pattern);
13201    }
13202
13203    /// Set the validation function of the input field.
13204    pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
13205        self.validate = Some(Box::new(f));
13206        self
13207    }
13208
13209    pub fn set_validator(
13210        &mut self,
13211        validate: impl Fn(&str, &mut App) -> bool + 'static,
13212        _cx: &mut Context<Self>,
13213    ) {
13214        self.validate = Some(Box::new(validate));
13215    }
13216
13217    /// Set the step value of the [`super::NumberInput`] for increment/decrement.
13218    ///
13219    /// If any of `step`, `min`, `max` is set, the [`super::NumberInput`] will
13220    /// update the value internally (step by `step`, default 1, clamp to the
13221    /// `min`/`max` range and emit [`InputEvent::Change`]) instead of emitting
13222    /// [`super::NumberInputEvent::Step`].
13223    ///
13224    /// See also [`Self::step_by`] to calculate the step value
13225    /// based on the current value.
13226    pub fn step(mut self, step: impl Into<NumberStep>) -> Self {
13227        self.number_step = Some(step.into());
13228        self
13229    }
13230
13231    /// Set the minimum value of the [`super::NumberInput`].
13232    ///
13233    /// The value will be clamped to the minimum value on stepping and on
13234    /// blur (only if the clamped value passes the `pattern`/`validate` check).
13235    /// See also [`Self::step`].
13236    pub fn min(mut self, min: f64) -> Self {
13237        self.number_min = Some(min);
13238        self
13239    }
13240
13241    /// Set the maximum value of the [`super::NumberInput`].
13242    ///
13243    /// The value will be clamped to the maximum value on stepping and on
13244    /// blur (only if the clamped value passes the `pattern`/`validate` check).
13245    /// See also [`Self::step`].
13246    pub fn max(mut self, max: f64) -> Self {
13247        self.number_max = Some(max);
13248        self
13249    }
13250
13251    /// Update the step value after construction, `None` to fall back to
13252    /// emitting [`super::NumberInputEvent::Step`] (if `min`, `max` are unset).
13253    ///
13254    /// See [`Self::step`] and [`Self::step_by`].
13255    pub fn set_step(
13256        &mut self,
13257        step: impl Into<Option<NumberStep>>,
13258        _: &mut Window,
13259        _: &mut Context<Self>,
13260    ) {
13261        self.number_step = step.into();
13262    }
13263
13264    /// Update the minimum value after construction. See [`Self::min`].
13265    pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13266        self.number_min = min;
13267    }
13268
13269    /// Update the maximum value after construction. See [`Self::max`].
13270    pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13271        self.number_max = max;
13272    }
13273
13274    /// Set true to show spinner at the input right.
13275    pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
13276        self.loading = loading;
13277        cx.notify();
13278    }
13279}
13280
13281/// Methods shared by the two multi-line modes, and reachable on neither a
13282/// single-line input nor anything else.
13283impl<M: crate::input::MultiLineMode> InputBaseState<M> {
13284    /// Set whether text taller than the input stretches past its top and
13285    /// bottom and springs back when precise trackpad or Magic Mouse scrolling
13286    /// or its momentum runs into an end. Ordinary line-wheel scrolling does
13287    /// not bounce. The default follows
13288    /// [`crate::ScrollBounce::enabled_by_default`]: on on iOS, Android and
13289    /// macOS, off elsewhere. Under reduced motion the text stops at its ends
13290    /// without stretching.
13291    pub fn scroll_bounce(mut self, scroll_bounce: bool) -> Self {
13292        self.scroll_bounce = scroll_bounce;
13293        self
13294    }
13295
13296    /// Update whether the text stretches past its ends, see
13297    /// [`InputBaseState::scroll_bounce`]. Turning it off drops a stretch in
13298    /// progress.
13299    pub fn set_scroll_bounce(&mut self, scroll_bounce: bool, cx: &mut Context<Self>) {
13300        if self.scroll_bounce != scroll_bounce {
13301            self.scroll_bounce = scroll_bounce;
13302            self.overscroll.reset();
13303            cx.notify();
13304        }
13305    }
13306
13307    /// Whether the built-in search panel and its shortcut are enabled. Off by
13308    /// default, on for the code editor.
13309    ///
13310    /// This only concerns the panel. An input that is not searchable still
13311    /// answers [`InputBaseState::set_search_query`] and the other search
13312    /// methods, and lets `Ctrl-F` / `Cmd-F` bubble up to its ancestors, so an
13313    /// application can put its own search UI on top of the same engine.
13314    pub fn searchable(mut self, searchable: bool) -> Self {
13315        self.searchable = searchable;
13316        self
13317    }
13318
13319    /// See [`InputBaseState::searchable`].
13320    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
13321        self.searchable = searchable;
13322        cx.notify();
13323    }
13324
13325    /// Set the soft wrap mode, default is true.
13326    #[doc(hidden)]
13327    pub fn soft_wrap(mut self, wrap: bool) -> Self {
13328        self.soft_wrap = wrap;
13329        self
13330    }
13331
13332    /// Update the soft wrap mode, default is true.
13333    pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
13334        self.soft_wrap = wrap;
13335        if wrap {
13336            let wrap_width = self
13337                .last_layout
13338                .as_ref()
13339                .and_then(|b| b.wrap_width)
13340                .unwrap_or(self.input_bounds.size.width);
13341
13342            self.display_map.on_layout_changed(Some(wrap_width), cx);
13343
13344            // Reset scroll to left 0
13345            let mut offset = self.scroll_handle.offset();
13346            offset.x = px(0.);
13347            self.scroll_handle.set_offset(offset);
13348        } else {
13349            self.display_map.on_layout_changed(None, cx);
13350        }
13351        cx.notify();
13352    }
13353
13354    /// Set how soft-wrapped continuation lines are indented, default is [`WrappingIndent::Same`]
13355    #[doc(hidden)]
13356    pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
13357        self.wrapping_indent = wrapping_indent;
13358        self
13359    }
13360
13361    /// Update how soft-wrapped continuation lines are indented.
13362    pub fn set_wrapping_indent(
13363        &mut self,
13364        wrapping_indent: WrappingIndent,
13365        _: &mut Window,
13366        cx: &mut Context<Self>,
13367    ) {
13368        self.wrapping_indent = wrapping_indent;
13369        self.display_map.set_wrapping_indent(wrapping_indent, cx);
13370        cx.notify();
13371    }
13372}
13373
13374/// Methods that only ordinary multi-line text offers.
13375impl InputBaseState<crate::input::TextareaMode> {
13376    /// Create a multi-line text state.
13377    ///
13378    /// Being multi-line is carried by the mode, not by the layout, so the
13379    /// default plain-text layout needs no adjustment here.
13380    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13381        Self::new_in_mode(window, cx)
13382    }
13383
13384    pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
13385        self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
13386        self.mode.update_auto_grow(&self.display_map);
13387        cx.notify();
13388    }
13389
13390    /// Set the number of rows for the multi-line Textarea.
13391    ///
13392    /// This is only used when `multi_line` is set to true. The input is at least
13393    /// this many lines tall.
13394    ///
13395    /// default: 1
13396    #[doc(hidden)]
13397    pub fn rows(mut self, rows: usize) -> Self {
13398        match &mut self.mode {
13399            LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
13400                *r = rows
13401            }
13402            LayoutMode::AutoGrow {
13403                max_rows: max_r,
13404                rows: r,
13405                ..
13406            } => {
13407                *r = rows;
13408                *max_r = rows;
13409            }
13410        }
13411        self
13412    }
13413
13414    pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
13415        match &mut self.mode {
13416            LayoutMode::PlainText { rows: value, .. }
13417            | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
13418            LayoutMode::AutoGrow {
13419                rows: value,
13420                max_rows,
13421                ..
13422            } => {
13423                *value = rows;
13424                *max_rows = rows;
13425            }
13426        }
13427        cx.notify();
13428    }
13429
13430    /// Grow with the content from `min_rows` through `max_rows`.
13431    pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
13432        self.mode = LayoutMode::auto_grow(min_rows, max_rows);
13433        self
13434    }
13435}
13436
13437/// Methods that only a source-code editor offers.
13438impl InputBaseState<crate::input::EditorMode> {
13439    /// Create a source-code editor state.
13440    ///
13441    /// Default options: line numbers on, tab size 2 with soft tabs, indent
13442    /// guides on, multi-line, and search enabled. Set the language for syntax
13443    /// highlighting with [`Self::language`]; without one the text is shown
13444    /// unhighlighted.
13445    ///
13446    /// The editor aims at simple code editing or display, not at being a
13447    /// full-featured code editor. It offers syntax highlighting, auto indent,
13448    /// line numbers, and handles large text up to about 50K lines.
13449    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13450        let mut state = Self::new_in_mode(window, cx);
13451        state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
13452        state.searchable = true;
13453        state
13454    }
13455
13456    /// Set the language to highlight, e.g. `"rust"`.
13457    ///
13458    /// See [`Self::set_highlighter`] to change it after construction.
13459    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
13460        if let LayoutMode::CodeEditor {
13461            language: l,
13462            highlighter,
13463            ..
13464        } = &mut self.mode
13465        {
13466            l.set_name(language.into());
13467            *highlighter.borrow_mut() = None;
13468        }
13469        self
13470    }
13471
13472    /// The current language name, e.g. `"rust"`.
13473    pub fn language_name(&self) -> SharedString {
13474        match &self.mode {
13475            LayoutMode::CodeEditor { language, .. } => language.name(),
13476            _ => SharedString::default(),
13477        }
13478    }
13479
13480    /// Set enable/disable code folding.
13481    ///
13482    /// Default: true
13483    #[doc(hidden)]
13484    pub fn folding(mut self, folding: bool) -> Self {
13485        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13486            *f = folding;
13487        }
13488        self
13489    }
13490
13491    /// Set code folding at runtime.
13492    ///
13493    /// When disabling, all existing folds are cleared.
13494    pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
13495        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13496            *f = folding;
13497        }
13498        if !folding {
13499            self.display_map.clear_folds();
13500        }
13501        cx.notify();
13502    }
13503
13504    /// Unfold any folded ranges that hide the given position.
13505    ///
13506    /// Use this to reveal a position before acting on it (e.g. before
13507    /// [`Self::set_cursor_position`], which stops at a fold boundary),
13508    /// without touching folds elsewhere in the buffer. Fold candidates are
13509    /// kept, so the opened ranges can be folded again from the gutter.
13510    ///
13511    /// A fold keeps its own first and last line visible, so a position on
13512    /// either of them opens nothing. Nested folds all open, since opening
13513    /// only the outermost would leave the position hidden.
13514    ///
13515    /// Returns whether any fold was opened.
13516    pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
13517        let offset = self.text.position_to_offset(&position.into());
13518        let line = self.text.offset_to_point(offset).row;
13519        // A fold hides start_line + 1 ..= end_line - 1, so a line is hidden
13520        // exactly when some folded range strictly contains it.
13521        let covering: Vec<usize> = self
13522            .display_map
13523            .folded_ranges()
13524            .iter()
13525            .filter(|fold| line > fold.start_line && line < fold.end_line)
13526            .map(|fold| fold.start_line)
13527            .collect();
13528        if covering.is_empty() {
13529            return false;
13530        }
13531
13532        for start_line in covering {
13533            self.display_map.set_folded(start_line, false);
13534        }
13535        cx.notify();
13536        true
13537    }
13538
13539    /// Horizontal offset from the content area's left edge to unscrolled source text.
13540    ///
13541    /// Includes the laid-out gap, line numbers, folding controls, and gutter
13542    /// decorations. Excludes input-frame padding, horizontal scrolling, and
13543    /// text alignment. For left-aligned text, add this to the content area's
13544    /// origin and the horizontal scroll offset to recover the text origin.
13545    ///
13546    /// Returns `None` before the first layout. Like [`Self::range_to_bounds`],
13547    /// this describes the most recent layout; render again after changing
13548    /// gutter settings or typography before using it to align a static view.
13549    pub fn text_origin_offset(&self) -> Option<Pixels> {
13550        self.last_layout
13551            .as_ref()
13552            .map(|layout| layout.line_number_width)
13553    }
13554
13555    /// Set enable/disable line number.
13556    #[doc(hidden)]
13557    pub fn line_number(mut self, line_number: bool) -> Self {
13558        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
13559            *l = line_number;
13560        }
13561        self
13562    }
13563
13564    /// Set line number.
13565    pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
13566        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
13567            if *l == line_number {
13568                return;
13569            }
13570            *l = line_number;
13571        }
13572        cx.notify();
13573    }
13574
13575    /// Set enable/disable automatic closing brackets and quotes.
13576    ///
13577    /// When enabled, typing an opener from [`LanguageConfig::auto_closing_pairs`](crate::input::language_config::LanguageConfig::auto_closing_pairs) inserts the
13578    /// matching closer and places the cursor inside. Typing a closer that is
13579    /// already present just moves past it. Default: true
13580    #[doc(hidden)]
13581    pub fn auto_close(mut self, auto_close: bool) -> Self {
13582        self.mode.set_auto_close(auto_close);
13583        self
13584    }
13585
13586    /// Set automatic closing brackets and quotes at runtime.
13587    pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
13588        self.mode.set_auto_close(auto_close);
13589        cx.notify();
13590    }
13591
13592    /// Set enable/disable smart indent on Enter.
13593    ///
13594    /// When enabled, Enter uses structural brackets and
13595    /// [`LanguageConfig::indentation_rules`](crate::input::language_config::LanguageConfig::indentation_rules) to choose indentation.
13596    /// Default: true
13597    #[doc(hidden)]
13598    pub fn smart_indent(mut self, smart_indent: bool) -> Self {
13599        self.mode.set_smart_indent(smart_indent);
13600        self
13601    }
13602
13603    /// Set smart indent on Enter at runtime.
13604    pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
13605        self.mode.set_smart_indent(smart_indent);
13606        cx.notify();
13607    }
13608}