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, line_number_digits_width, line_number_len,
34    },
35    kind::InputModeKind,
36    mask_pattern::normalize_number_input,
37    mode::LayoutMode,
38    undo_manager::{EditIntent, UndoManager},
39};
40use crate::ScrollbarPlacement;
41use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
42use crate::input::blink_cursor::CURSOR_WIDTH;
43use crate::input::movement::MoveDirection;
44use crate::input::rope_ext::{next_grapheme_boundary, previous_grapheme_boundary};
45use crate::input::{
46    EditorLineNumberRenderer, InputEdit, InputExtras as _, Position, RopeExt as _,
47    element::RIGHT_MARGIN, layout::LastLayout,
48};
49use crate::overscroll::Overscroll;
50use crate::{AutoScroll, StepAction, TestSupportExt as _};
51
52pub(super) const EDITOR_ELEMENT_ID: &str = "input-state";
53
54/// Vertical clearance to retain when revealing a text position.
55pub(crate) enum ScrollPadding {
56    Minimal,
57    SurroundingLines,
58}
59
60#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
61#[action(namespace = input, no_json)]
62pub struct Enter {
63    /// Is confirm with secondary.
64    pub secondary: bool,
65    /// Whether the Shift modifier was held when Enter was pressed.
66    pub shift: bool,
67}
68
69impl Enter {
70    /// Returns true if `action` is a primary `Enter` action (`secondary: false`),
71    /// regardless of whether Shift was held.
72    pub fn is_primary(action: &dyn Action) -> bool {
73        action.partial_eq(&Enter {
74            secondary: false,
75            shift: false,
76        }) || action.partial_eq(&Enter {
77            secondary: false,
78            shift: true,
79        })
80    }
81}
82
83actions!(
84    input,
85    [
86        ActivateToken,
87        Backspace,
88        Delete,
89        DeleteToBeginningOfLine,
90        DeleteToEndOfLine,
91        DeleteToPreviousWordStart,
92        DeleteToNextWordEnd,
93        Indent,
94        Outdent,
95        IndentInline,
96        OutdentInline,
97        MoveUp,
98        MoveDown,
99        MoveLeft,
100        MoveRight,
101        MoveHome,
102        MoveEnd,
103        MovePageUp,
104        MovePageDown,
105        AddCursorAbove,
106        AddCursorBelow,
107        SelectAll,
108        SelectToStartOfLine,
109        SelectToEndOfLine,
110        SelectToStart,
111        SelectToEnd,
112        SelectToPreviousWordStart,
113        SelectToNextWordEnd,
114        ShowCharacterPalette,
115        Copy,
116        Cut,
117        Paste,
118        Undo,
119        Redo,
120        MoveToStartOfLine,
121        MoveToEndOfLine,
122        MoveToStart,
123        MoveToEnd,
124        MoveToPreviousWord,
125        MoveToNextWord,
126        Escape,
127        ToggleCodeActions,
128        ShowCompletions,
129        Search,
130        Replace,
131        GoToDefinition,
132    ]
133);
134
135/// An event emitted by an input.
136///
137/// Subscribe to [`InputEditsEvent`] for the immutable edits associated with a
138/// change. `Change` itself remains available for consumers that only need a
139/// notification.
140#[derive(Clone)]
141pub enum InputEvent {
142    Change,
143    PressEnter { secondary: bool, shift: bool },
144    Focus,
145    Blur,
146}
147
148/// An immutable batch of text edits emitted for one input change.
149///
150/// Each entry contains the edit and the document immediately after it, in
151/// application order. Unlike reading the input state in a `Change` subscriber,
152/// this snapshot remains associated with its event when updates are queued.
153#[derive(Clone)]
154pub struct InputEditsEvent {
155    edits: Vec<(InputEdit, Rope)>,
156}
157
158impl InputEditsEvent {
159    /// The edits and the text after each edit, in application order.
160    pub fn edits(&self) -> &[(InputEdit, Rope)] {
161        &self.edits
162    }
163}
164
165pub(super) const CONTEXT: &str = "Input";
166
167pub(crate) fn init(cx: &mut App) {
168    cx.bind_keys([
169        KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
170        KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
171        #[cfg(target_os = "macos")]
172        KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
173        KeyBinding::new("delete", Delete, Some(CONTEXT)),
174        KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
175        #[cfg(target_os = "macos")]
176        KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
177        #[cfg(target_os = "macos")]
178        KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
179        #[cfg(target_os = "macos")]
180        KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
181        #[cfg(not(target_os = "macos"))]
182        KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
183        #[cfg(target_os = "macos")]
184        KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
185        #[cfg(not(target_os = "macos"))]
186        KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
187        KeyBinding::new(
188            "enter",
189            Enter {
190                secondary: false,
191                shift: false,
192            },
193            Some(CONTEXT),
194        ),
195        KeyBinding::new(
196            "shift-enter",
197            Enter {
198                secondary: false,
199                shift: true,
200            },
201            Some(CONTEXT),
202        ),
203        KeyBinding::new(
204            if cx.platform_info().is_mac() {
205                "cmd-enter"
206            } else {
207                "ctrl-enter"
208            },
209            Enter {
210                secondary: true,
211                shift: false,
212            },
213            Some(CONTEXT),
214        ),
215        KeyBinding::new("escape", Escape, Some(CONTEXT)),
216        KeyBinding::new("up", MoveUp, Some(CONTEXT)),
217        KeyBinding::new("down", MoveDown, Some(CONTEXT)),
218        KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
219        KeyBinding::new("right", MoveRight, Some(CONTEXT)),
220        KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
221        KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
222        KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
223        KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
224        #[cfg(target_os = "macos")]
225        KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
226        #[cfg(not(target_os = "macos"))]
227        KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
228        #[cfg(target_os = "macos")]
229        KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
230        #[cfg(not(target_os = "macos"))]
231        KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
232        KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
233        KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
234        KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
235        KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
236        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
237        KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
238        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
239        KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
240        // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them.
241        #[cfg(target_os = "macos")]
242        KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
243        #[cfg(target_os = "macos")]
244        KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
245        #[cfg(target_os = "windows")]
246        KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
247        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
248        KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
249        #[cfg(target_os = "windows")]
250        KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
251        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
252        KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
253        KeyBinding::new("home", MoveHome, Some(CONTEXT)),
254        KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
255        #[cfg(not(target_os = "macos"))]
256        KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
257        #[cfg(not(target_os = "macos"))]
258        KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
259        #[cfg(not(target_os = "macos"))]
260        KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
261        #[cfg(not(target_os = "macos"))]
262        KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
263        KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
264        KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
265        #[cfg(target_os = "macos")]
266        KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
267        #[cfg(target_os = "macos")]
268        KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
269        #[cfg(target_os = "macos")]
270        KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
271        #[cfg(target_os = "macos")]
272        KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
273        #[cfg(any(target_os = "macos", target_os = "linux"))]
274        KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
275        #[cfg(not(target_os = "macos"))]
276        KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
277        #[cfg(any(target_os = "macos", target_os = "linux"))]
278        KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
279        #[cfg(not(target_os = "macos"))]
280        KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
281        #[cfg(target_os = "macos")]
282        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
283        #[cfg(target_os = "macos")]
284        KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
285        #[cfg(not(target_os = "macos"))]
286        KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
287        #[cfg(target_os = "macos")]
288        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
289        #[cfg(not(target_os = "macos"))]
290        KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
291        #[cfg(target_os = "macos")]
292        KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
293        #[cfg(not(target_os = "macos"))]
294        KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
295        #[cfg(target_os = "macos")]
296        KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
297        #[cfg(not(target_os = "macos"))]
298        KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
299        #[cfg(target_os = "macos")]
300        KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
301        #[cfg(target_os = "macos")]
302        KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
303        #[cfg(target_os = "macos")]
304        KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
305        #[cfg(target_os = "macos")]
306        KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
307        #[cfg(target_os = "macos")]
308        KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
309        #[cfg(target_os = "macos")]
310        KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
311        #[cfg(target_os = "macos")]
312        KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
313        #[cfg(target_os = "macos")]
314        KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
315        #[cfg(target_os = "macos")]
316        KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
317        #[cfg(target_os = "macos")]
318        KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
319        #[cfg(not(target_os = "macos"))]
320        KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
321        #[cfg(not(target_os = "macos"))]
322        KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
323        #[cfg(target_os = "macos")]
324        KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
325        #[cfg(target_os = "macos")]
326        KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
327        #[cfg(not(target_os = "macos"))]
328        KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
329        #[cfg(not(target_os = "macos"))]
330        KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
331        #[cfg(target_os = "macos")]
332        KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
333        #[cfg(not(target_os = "macos"))]
334        KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
335        #[cfg(target_os = "macos")]
336        KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
337        #[cfg(not(target_os = "macos"))]
338        KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
339        #[cfg(target_os = "macos")]
340        KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
341        #[cfg(not(target_os = "macos"))]
342        KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
343    ]);
344}
345
346/// A mouse position resolved for a columnar (block) selection.
347///
348/// A position past the end of a short row has no glyph to land on, so `offset` clips to
349/// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they
350/// say which column the pointer really reached, which is what a block spanning rows of
351/// different lengths has to be measured in.
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353pub(super) struct ColumnarPoint {
354    offset: usize,
355    columns_past_line_end: usize,
356}
357
358impl ColumnarPoint {
359    pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
360        Self {
361            offset,
362            columns_past_line_end,
363        }
364    }
365}
366
367/// The document and selections a paste was asked to replace, taken when the
368/// `Paste` action ran so a clipboard read that resolves later can tell
369/// whether it still applies. See [`InputBaseState::paste_target`].
370#[derive(Debug, PartialEq)]
371struct PasteTarget {
372    document_revision: u64,
373    selections: Vec<CursorSelection>,
374}
375
376/// Caret positioning geometry from the input's latest prepaint.
377///
378/// Stashed during prepaint so caret-anchored popups can position themselves
379/// from the current frame's geometry in their deferred prepaint.
380#[derive(Clone, Copy, Debug)]
381#[doc(hidden)]
382pub struct PrepaintCaretGeometry {
383    cursor_bounds: Bounds<Pixels>,
384    line_height: Pixels,
385    input_bounds: Bounds<Pixels>,
386    scroll_offset: Point<Pixels>,
387    pub(super) scroll_y_f64: f64,
388    /// A resize owns visibility while its requested repaint settles.
389    pub(super) resize_reveal_owned: bool,
390}
391
392impl PrepaintCaretGeometry {
393    pub(super) fn new(
394        cursor_bounds: Bounds<Pixels>,
395        line_height: Pixels,
396        input_bounds: Bounds<Pixels>,
397        scroll_offset: Point<Pixels>,
398    ) -> Self {
399        Self {
400            cursor_bounds,
401            line_height,
402            input_bounds,
403            scroll_offset,
404            scroll_y_f64: f64::from(f32::from(scroll_offset.y)),
405            resize_reveal_owned: false,
406        }
407    }
408
409    /// The active caret's bounds from the fresh prepaint layout.
410    pub fn cursor_bounds(&self) -> Bounds<Pixels> {
411        self.cursor_bounds
412    }
413
414    /// Line height from the fresh prepaint layout.
415    pub fn line_height(&self) -> Pixels {
416        self.line_height
417    }
418
419    /// The input container bounds from the fresh prepaint.
420    pub fn input_bounds(&self) -> Bounds<Pixels> {
421        self.input_bounds
422    }
423
424    /// The scroll offset that will be in effect after paint, clamped like
425    /// `InputBaseState::update_scroll_offset` clamps it.
426    pub fn scroll_offset(&self) -> Point<Pixels> {
427        self.scroll_offset
428    }
429}
430
431/// The shared text-editing engine behind [`crate::input::InputState`],
432/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
433///
434/// `M` is the mode marker: it carries no data and only decides which methods
435/// exist, so an ordinary input cannot reach the editor's language features.
436///
437/// The three states are type aliases of this one, which is why this name is
438/// public: an alias is only as usable as the type behind it, so hiding this
439/// would leave `InputState` unable to do anything. Prefer naming the aliases
440/// — write `InputState`, not `InputBaseState<InputMode>`.
441pub struct InputBaseState<M: InputModeKind> {
442    /// State only this mode needs. See [`InputModeKind::Extras`].
443    pub(crate) extras: M::Extras,
444    pub(super) focus_handle: FocusHandle,
445    selection_focus: Option<WeakFocusHandle>,
446    pub(super) mode: LayoutMode,
447    pub(super) text: Rope,
448    pub(super) display_map: DisplayMap,
449    pub(super) undo_manager: UndoManager,
450    pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
451    pub(super) pending_token: Option<super::InlineToken>,
452    pub(super) replaying_history: bool,
453    pub(super) validated_token_edit: bool,
454    pub(super) document_revision: u64,
455    pub(super) token_presentation: super::InlineTokenPresentation,
456    pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
457    /// Real per-frame bounds of the placed token elements, keyed by token
458    /// start offset; used for hover payloads and stale-hover reconciliation.
459    pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
460    /// The currently hovered token: its entered span, last measured bounds,
461    /// and UTF-16 range as of entry. Retained so hover exit can still be
462    /// delivered when the token is removed, replaced, scrolled out, or
463    /// disabled.
464    pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
465    pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
466    /// The start offset of a pressed token, with the document revision and
467    /// pointer position at the press.
468    pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
469    pub(super) search_session: super::SearchSession,
470    /// Advances every time search is explicitly invoked. See
471    /// [`InputBaseState::search_activation_revision`].
472    pub(super) search_activation_revision: u64,
473    pub(super) searchable: bool,
474    pub(super) replaceable: bool,
475    pub(super) soft_wrap: bool,
476    pub(super) wrapping_indent: WrappingIndent,
477    pub(super) scroll_beyond_last_line: Option<usize>,
478    pub(super) cursor_surrounding_lines: Option<usize>,
479    pub(super) blink_cursor: Entity<BlinkCursor>,
480    pub(super) loading: bool,
481    /// The cursors and selections.
482    ///
483    /// Always contains at least one selection where index 0 is the active cursor.
484    pub(super) selections: Selections,
485    /// Range for save the selected word, use to keep word range when drag move.
486    pub(super) selected_word_range: Option<CursorSelection>,
487    /// The marked range is the temporary insert text on IME typing.
488    pub(super) ime_marked_range: Option<CursorSelection>,
489    /// Text before an unannounced IME composition, until the next change.
490    ime_original_text: Option<Rope>,
491    pub(super) last_layout: Option<LastLayout>,
492    /// Fresh caret geometry stashed during prepaint for caret-anchored popups.
493    ///
494    /// Popups are positioned in their deferred prepaint, which runs after the
495    /// input's prepaint but before its paint.
496    pub(crate) prepaint_caret_geometry: Option<PrepaintCaretGeometry>,
497    pub(super) last_cursor: Option<usize>,
498    /// Where the platform was last told the caret is, for its IME panel.
499    pub(super) ime_anchor: Option<(Point<Pixels>, Option<Bounds<Pixels>>)>,
500    /// The input container bounds
501    pub(super) input_bounds: Bounds<Pixels>,
502    /// The text bounds
503    pub(super) last_bounds: Option<Bounds<Pixels>>,
504    /// The fully visible part of the window this input last asked its scroll
505    /// containers to reveal it in, while focused. `None` while unfocused.
506    pub(super) revealed_viewport: Option<Bounds<Pixels>>,
507    pub(super) last_selected_range: Option<CursorSelection>,
508    /// The current edit batch, copied into an event when a change is emitted.
509    pub(super) last_input_edits: Vec<(InputEdit, Rope)>,
510    pub(super) selecting: bool,
511    /// Anchor point of an in-progress columnar (block) selection.
512    pub(super) column_select_start: Option<ColumnarPoint>,
513    /// The selection a long press made, with its handles and edit menu.
514    pub(super) touch_selection: super::touch::TouchSelection,
515    pub(crate) disabled: bool,
516    pub(crate) readonly: bool,
517    pub(crate) text_align: TextAlign,
518    pub(super) masked: bool,
519    pub(super) clean_on_escape: bool,
520    pub(super) submit_on_enter: bool,
521    /// Overrides for [`Self::text_input_configuration`].
522    pub(super) input_action: Option<TextInputAction>,
523    pub(super) autocorrect: Option<bool>,
524    pub(super) autocapitalize: Option<Autocapitalize>,
525    pub(super) show_whitespaces: bool,
526    /// This flag tells the renderer to prefer the end of the current visual line.
527    pub(crate) cursor_line_end_affinity: bool,
528    pub(super) pattern: Option<regex::Regex>,
529    pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
530    /// The step strategy for [`super::NumberInput`] to increment/decrement.
531    /// See [`Self::step`] and [`Self::step_by`].
532    pub(crate) number_step: Option<NumberStep>,
533    /// The minimum value for [`super::NumberInput`]. See [`Self::min`].
534    pub(crate) number_min: Option<f64>,
535    /// The maximum value for [`super::NumberInput`]. See [`Self::max`].
536    pub(crate) number_max: Option<f64>,
537    pub(crate) scroll_handle: ScrollHandle,
538    /// Whether the text stretches past its ends, see [`Self::scroll_bounce`].
539    scroll_bounce: bool,
540    /// The text's stretch past an end, while it lasts.
541    pub(super) overscroll: Overscroll,
542    /// The deferred scroll offset to apply on next layout.
543    pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
544    /// Authoritative `f64` vertical scroll offset (`<= 0.0`) to preserve precision past `2^24` px.
545    pub(crate) scroll_y_f64: f64,
546    pub(crate) deferred_scroll_y_f64: Option<f64>,
547    pub(crate) last_synced_handle_y: Cell<Pixels>,
548    /// Authoritative `f64` scrollable height in pixels.
549    pub(crate) scroll_height_f64: f64,
550    /// The size of the scrollable content.
551    pub(crate) scroll_size: gpui::Size<Pixels>,
552    pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
553    /// Overview ruler marks in display rows, kept between frames.
554    pub(super) overview_ruler_rows: std::cell::RefCell<OverviewRulerRows>,
555    pub(super) scrollbar_placement: ScrollbarPlacement,
556    /// The widest measured unwrapped line width and what it was measured for.
557    pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
558    pub(super) editor_paddings: Edges<Pixels>,
559    /// The style this state paints with: what was projected onto it, with
560    /// every colour left unset resolved from the palette that is current. It
561    /// is rebuilt at the top of every render, which is what keeps it current
562    /// when the palette changes after the state was built.
563    pub(super) editor_style: InputEditorStyle,
564    /// What a consumer projected, kept verbatim so that resolution never
565    /// consumes its own output: resolving in place would fill the unset
566    /// colours once and then never see them as unset again, which is the same
567    /// freeze in a different place.
568    projected_editor_style: InputEditorStyle,
569    pub(super) fold_placeholder_renderer: Option<FoldPlaceholderRenderer>,
570    pub(super) fold_background: Option<Hsla>,
571    pub(super) accessibility: Option<InputAccessibility>,
572    /// What paints in place of Base's editor scrollbar, when a consumer
573    /// supplies its own.
574    pub(super) scrollbar_renderer: Option<crate::input::EditorScrollbarRenderer>,
575
576    /// The mask pattern for formatting the input text
577    pub(crate) mask_pattern: MaskPattern,
578    /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`]
579    /// or [`Self::set_mask_pattern`]), to let [`super::NumberInput`] only apply
580    /// its default mask when the user has not made an explicit choice.
581    pub(super) mask_pattern_set: bool,
582    pub(super) placeholder: SharedString,
583
584    /// Diagnostic currently requested by pointer hover; applications render it.
585    pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
586
587    context_menu_handler: Option<
588        Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
589    >,
590    pending_context_menu: Option<(Point<Pixels>, usize)>,
591    context_menu_offset: Option<usize>,
592
593    /// Whether the context menu that shows on right-click is enabled.
594    ///
595    pub(super) enable_context_menu: bool,
596
597    /// A flag to indicate if we are currently inserting a completion item.
598    pub(super) completion_inserting: bool,
599    pub(super) overlay_action_handler: Option<
600        Rc<
601            dyn Fn(
602                super::InputOverlayKind,
603                Box<dyn Action>,
604                &mut Window,
605                &mut Context<InputBaseState<M>>,
606            ) -> bool,
607        >,
608    >,
609
610    /// A flag to indicate if we have a pending update to the text.
611    ///
612    /// If true, will call some update (for example LSP, Syntax Highlight) before render.
613    _pending_update: bool,
614    /// A flag to indicate if we should ignore the next completion event.
615    pub(super) silent_replace_text: bool,
616    /// A flag to indicate if we should emit InputEvents.
617    pub(super) emit_events: bool,
618
619    _subscriptions: Vec<Subscription>,
620
621    pub(super) auto_scroll: AutoScroll,
622}
623
624/// Accessibility presentation for the editor's existing keyboard-focus boundary.
625///
626/// Frames and their addon controls keep their own identities. This projection
627/// does not create a focus handle or register another text Tab stop. The engine
628/// supplies the live value and guards accessibility actions against its current
629/// disabled, read-only and masked state.
630#[derive(Clone, Debug)]
631pub struct InputAccessibility {
632    role: Option<gpui::Role>,
633    label: Option<SharedString>,
634    placeholder: Option<SharedString>,
635    accessibility_id: Option<SharedString>,
636    value_exposed: bool,
637}
638
639impl InputAccessibility {
640    pub fn new(role: Option<gpui::Role>) -> Self {
641        Self {
642            role,
643            label: None,
644            placeholder: None,
645            accessibility_id: None,
646            value_exposed: true,
647        }
648    }
649
650    pub fn with_label(mut self, label: Option<SharedString>) -> Self {
651        self.label = label;
652        self
653    }
654
655    pub fn with_placeholder(mut self, placeholder: Option<SharedString>) -> Self {
656        self.placeholder = placeholder;
657        self
658    }
659
660    pub fn with_accessibility_id(mut self, id: Option<SharedString>) -> Self {
661        self.accessibility_id = id;
662        self
663    }
664
665    /// Suppress values for secret content even when the mask is revealed.
666    pub fn with_value_exposed(mut self, exposed: bool) -> Self {
667        self.value_exposed = exposed;
668        self
669    }
670
671    pub fn role(&self) -> Option<gpui::Role> {
672        self.role
673    }
674
675    pub fn label(&self) -> Option<&SharedString> {
676        self.label.as_ref()
677    }
678
679    pub fn placeholder(&self) -> Option<&SharedString> {
680        self.placeholder.as_ref()
681    }
682
683    pub fn accessibility_id(&self) -> Option<&SharedString> {
684        self.accessibility_id.as_ref()
685    }
686
687    pub fn value_exposed(&self) -> bool {
688        self.value_exposed
689    }
690}
691
692/// Read-only styling data exposed to presentation facades.
693///
694/// The fields are private and read through the methods below, so that a new
695/// one can be added without breaking the facades.
696#[derive(Clone)]
697pub struct InputPresentation {
698    focus_handle: FocusHandle,
699    disabled: bool,
700    readonly: bool,
701    loading: bool,
702    masked: bool,
703    multi_line: bool,
704    code_editor: bool,
705    text_align: TextAlign,
706    placeholder: SharedString,
707    mask_placeholder: Option<String>,
708}
709
710impl InputPresentation {
711    pub fn focus_handle(&self) -> &FocusHandle {
712        &self.focus_handle
713    }
714
715    pub fn is_disabled(&self) -> bool {
716        self.disabled
717    }
718
719    pub fn is_readonly(&self) -> bool {
720        self.readonly
721    }
722
723    /// Returns true if the user is allowed to change the text.
724    ///
725    /// See also: [`InputBaseState::is_editable`].
726    pub fn is_editable(&self) -> bool {
727        !self.disabled && !self.readonly
728    }
729
730    pub fn is_loading(&self) -> bool {
731        self.loading
732    }
733
734    pub fn is_masked(&self) -> bool {
735        self.masked
736    }
737
738    pub fn is_multi_line(&self) -> bool {
739        self.multi_line
740    }
741
742    pub fn is_code_editor(&self) -> bool {
743        self.code_editor
744    }
745
746    pub fn text_align(&self) -> TextAlign {
747        self.text_align
748    }
749
750    pub fn placeholder(&self) -> &SharedString {
751        &self.placeholder
752    }
753
754    /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
755    pub fn mask_placeholder(&self) -> Option<&str> {
756        self.mask_placeholder.as_deref()
757    }
758}
759
760impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
761impl<M: InputModeKind> EventEmitter<InputEditsEvent> for InputBaseState<M> {}
762
763impl<M: InputModeKind> InputBaseState<M> {
764    #[doc(hidden)]
765    pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
766        let layout = self.last_layout.as_ref()?;
767        let mut bounds = layout.cursor_bounds?;
768        bounds.origin.y -= self.scroll_handle.offset().y;
769        Some((bounds, layout.line_height))
770    }
771
772    /// Caret geometry from the latest prepaint, for caret-anchored popups.
773    ///
774    /// Popups positioned in their deferred prepaint read this to anchor to
775    /// the current frame's caret instead of the previous frame's paint.
776    #[doc(hidden)]
777    pub fn prepaint_caret_geometry(&self) -> Option<PrepaintCaretGeometry> {
778        self.prepaint_caret_geometry
779    }
780
781    pub fn input_bounds(&self) -> Bounds<Pixels> {
782        self.input_bounds
783    }
784
785    pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
786        self.last_bounds
787    }
788
789    /// The cached display map for querying wrapped rows and display positions.
790    ///
791    /// Reading this does not prepare text or force layout. Before the first
792    /// layout, [`DisplayMap::wrap_row_count`] can be zero; prepared empty text
793    /// has one row. The count describes content, independent of minimum rows,
794    /// auto-grow limits and viewport height.
795    ///
796    /// Text edits use the cached wrapping parameters. Layout refreshes the
797    /// cache after width or font changes; consume that count on a subsequent
798    /// render, or use [`Self::prewrap`] to prepare it before the first layout.
799    pub fn display_map(&self) -> &DisplayMap {
800        &self.display_map
801    }
802
803    /// Wrap the text for `font`, `font_size` and `width` before the first
804    /// layout, so that [`DisplayMap::wrap_row_count`] is known on the first frame.
805    ///
806    /// Call it after setting the value and the wrapping indent. `width` is the
807    /// width of the input's text area: its width less its padding, and less
808    /// the line-number gutter for an editor with line numbers. It wraps as
809    /// layout does, a little short of that width and with the state's wrapping
810    /// indent. Once the input has been laid out this does nothing, and layout
811    /// keeps the wrap up to date. The font and font size must match the input's
812    /// actual text style.
813    pub fn prewrap(
814        &mut self,
815        font: gpui::Font,
816        font_size: Pixels,
817        width: Pixels,
818        cx: &mut Context<Self>,
819    ) {
820        if self.last_layout.is_some() {
821            return;
822        }
823        let wrap_width = (width - RIGHT_MARGIN).max(px(1.));
824        self.display_map.set_font(font, font_size, cx);
825        self.display_map
826            .set_tab_size(self.mode.tab_size().tab_size, cx);
827        self.display_map
828            .on_layout_changed(self.soft_wrap.then_some(wrap_width), cx);
829        self.display_map
830            .set_wrapping_indent(self.wrapping_indent, cx);
831        self.display_map.ensure_text_prepared(&self.text, cx);
832    }
833
834    pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
835        self.diagnostic_popover.clone()
836    }
837
838    pub fn presentation(&self) -> InputPresentation {
839        InputPresentation {
840            focus_handle: self.focus_handle.clone(),
841            disabled: self.disabled,
842            readonly: self.readonly,
843            loading: self.loading,
844            masked: self.masked,
845            multi_line: self.is_multi_line(),
846            code_editor: self.is_code_editor(),
847            text_align: self.text_align,
848            placeholder: self.placeholder.clone(),
849            mask_placeholder: self.mask_pattern.placeholder(),
850        }
851    }
852
853    /// Whether this input spans more than one line.
854    ///
855    /// Answered by the mode marker, which is fixed when the state is built.
856    /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
857    #[inline]
858    /// Whether this input paints scrollbars.
859    ///
860    /// Only a multi-line input can scroll: a single-line input keeps its
861    /// caret in view by moving its own offset, and never has a viewport a
862    /// user could drag. Adding the editor scrollbar to every input put a
863    /// thumb inside every text field, which is a control the field does not
864    /// have.
865    pub(crate) fn shows_scrollbar(&self) -> bool {
866        self.is_multi_line()
867    }
868
869    pub fn is_multi_line(&self) -> bool {
870        M::MULTI_LINE
871    }
872
873    /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
874    #[inline]
875    pub fn is_single_line(&self) -> bool {
876        !M::MULTI_LINE
877    }
878
879    /// Whether this input is a source-code editor.
880    #[inline]
881    pub fn is_code_editor(&self) -> bool {
882        M::CODE_EDITOR
883    }
884
885    /// Whether the user is allowed to copy the selection out.
886    ///
887    /// A masked input keeps its value out of the clipboard.
888    pub fn is_copyable(&self) -> bool {
889        self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
890    }
891
892    pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
893        let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
894        InputContextMenuCapabilities::new()
895            .disabled(self.disabled)
896            .readonly(self.readonly)
897            .code_editor(self.is_code_editor())
898            .selection(!self.active_selection().is_empty())
899            .masked(self.masked)
900            .go_to_definition(go_to_definition)
901            .code_actions(code_actions)
902    }
903
904    pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
905        if !self.is_single_line() || self.text_align == text_align {
906            return;
907        }
908
909        self.text_align = text_align;
910        cx.notify();
911    }
912
913    /// Flip the password mask.
914    ///
915    /// Setting the mask is a single-line method, but flipping it stays here:
916    /// the reveal button is rendered from the generic path, and it can only be
917    /// switched on through [`crate::input::InputState`] anyway.
918    pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
919        self.masked = !self.masked;
920        cx.notify();
921    }
922
923    pub fn on_context_menu(
924        &mut self,
925        handler: Rc<
926            dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
927        >,
928    ) {
929        self.context_menu_handler = Some(handler);
930    }
931
932    /// Keeps the selection highlighted while this popup or one of its children has focus.
933    ///
934    /// This does not transfer keyboard focus or keep the caret visible. The
935    /// association holds only a weak focus handle. Pass `None` to clear it.
936    pub fn set_selection_focus(&mut self, focus: Option<FocusHandle>, cx: &mut Context<Self>) {
937        self.selection_focus = focus.as_ref().map(FocusHandle::downgrade);
938        cx.notify();
939    }
940
941    /// Whether the input or its associated selection popup has focus.
942    pub fn has_selection_focus(&self, window: &Window, cx: &App) -> bool {
943        self.focus_handle.is_focused(window)
944            || self
945                .selection_focus
946                .as_ref()
947                .and_then(WeakFocusHandle::upgrade)
948                .is_some_and(|focus| focus.is_focused(window) || focus.contains_focused(window, cx))
949    }
950
951    /// Build the engine. Each mode's own `new` sets its layout on top of this.
952    fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
953        let focus_handle = cx.focus_handle().tab_stop(true);
954        let blink_cursor = cx.new(BlinkCursor::new);
955        let undo_manager = UndoManager::new();
956
957        let _subscriptions = vec![
958            // Key bindings can consume events before on_key_down. Observe input
959            // before action dispatch so every keystroke resets the blink delay.
960            cx.intercept_keystrokes({
961                let focus_handle = focus_handle.clone();
962                let blink_cursor = blink_cursor.downgrade();
963                move |_, window, cx| {
964                    if focus_handle.is_focused(window) {
965                        _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
966                    }
967                }
968            }),
969            // Observe the blink cursor to repaint the view when it changes.
970            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
971            // Blink the cursor when the window is active, pause when it's not.
972            cx.observe_window_activation(window, |input, window, cx| {
973                if !window.is_window_active() {
974                    input.cancel_mouse_gesture(cx);
975                }
976                if window.is_window_active() {
977                    let focus_handle = input.focus_handle.clone();
978                    if focus_handle.is_focused(window) {
979                        input.blink_cursor.update(cx, |blink_cursor, cx| {
980                            blink_cursor.start(cx);
981                        });
982                    }
983                }
984            }),
985            cx.observe_window_bounds(window, |input, _, cx| input.cancel_mouse_gesture(cx)),
986            cx.on_focus(&focus_handle, window, Self::on_focus),
987            cx.on_blur(&focus_handle, window, Self::on_blur),
988        ];
989
990        let text_style = window.text_style();
991
992        Self {
993            extras: M::Extras::default(),
994            focus_handle: focus_handle.clone(),
995            selection_focus: None,
996            text: "".into(),
997            display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
998            search_session: super::SearchSession::default(),
999            search_activation_revision: 0,
1000            searchable: false,
1001            replaceable: true,
1002            soft_wrap: true,
1003            wrapping_indent: WrappingIndent::default(),
1004            scroll_beyond_last_line: None,
1005            cursor_surrounding_lines: None,
1006            blink_cursor,
1007            undo_manager,
1008            inline_tokens: None,
1009            pending_token: None,
1010            replaying_history: false,
1011            validated_token_edit: false,
1012            document_revision: 0,
1013            token_presentation: Default::default(),
1014            token_bounds: Default::default(),
1015            hovered_token: None,
1016            pending_token_hover_exits: Vec::new(),
1017            token_layout_cache: None,
1018            pressed_token: None,
1019            selections: Selections::default(),
1020            selected_word_range: None,
1021            ime_marked_range: None,
1022            ime_original_text: None,
1023            input_bounds: Bounds::default(),
1024            selecting: false,
1025            touch_selection: Default::default(),
1026            disabled: false,
1027            readonly: false,
1028            text_align: TextAlign::Left,
1029            masked: false,
1030            clean_on_escape: false,
1031            submit_on_enter: false,
1032            input_action: None,
1033            autocorrect: None,
1034            autocapitalize: None,
1035            show_whitespaces: false,
1036            loading: false,
1037            pattern: None,
1038            validate: None,
1039            number_step: Some(NumberStep::Fixed(1.)),
1040            number_min: None,
1041            number_max: None,
1042            mode: LayoutMode::default(),
1043            last_layout: None,
1044            prepaint_caret_geometry: None,
1045            last_bounds: None,
1046            revealed_viewport: None,
1047            last_selected_range: None,
1048            last_input_edits: Vec::new(),
1049            column_select_start: None,
1050            last_cursor: None,
1051            ime_anchor: None,
1052            scroll_handle: ScrollHandle::new(),
1053            scroll_bounce: crate::ScrollBounce::enabled_by_default(),
1054            overscroll: Overscroll::default(),
1055            scroll_size: gpui::size(px(0.), px(0.)),
1056            scroll_y_f64: 0.0,
1057            deferred_scroll_y_f64: None,
1058            last_synced_handle_y: Cell::new(px(0.)),
1059            scroll_height_f64: 0.0,
1060            editor_scrollbar_snapshot: Cell::new(None),
1061            overview_ruler_rows: Default::default(),
1062            scrollbar_placement: ScrollbarPlacement::default(),
1063            longest_line_width: Cell::new(None),
1064            editor_paddings: Edges::default(),
1065            deferred_scroll_offset: None,
1066            placeholder: SharedString::default(),
1067            mask_pattern: MaskPattern::default(),
1068            mask_pattern_set: false,
1069            editor_style: InputEditorStyle::default(),
1070            projected_editor_style: InputEditorStyle::default(),
1071            fold_placeholder_renderer: None,
1072            fold_background: None,
1073            accessibility: None,
1074            scrollbar_renderer: None,
1075            diagnostic_popover: None,
1076            context_menu_handler: None,
1077            pending_context_menu: None,
1078            context_menu_offset: None,
1079            enable_context_menu: true,
1080            completion_inserting: false,
1081            overlay_action_handler: None,
1082            silent_replace_text: false,
1083            emit_events: true,
1084            _subscriptions,
1085            _pending_update: false,
1086            cursor_line_end_affinity: false,
1087            auto_scroll: AutoScroll::default(),
1088        }
1089    }
1090
1091    /// Sets whether the context menu that shows on right-click is enabled.
1092    ///
1093    /// The context menu is enabled by default. Disabling it turns off the
1094    /// right-click menu entirely, including a custom menu set on the element.
1095    /// A custom menu already replaces the built-in one, so keep this enabled
1096    /// to show only your own items.
1097    pub fn context_menu(mut self, enable: bool) -> Self {
1098        self.enable_context_menu = enable;
1099        self
1100    }
1101
1102    pub fn set_context_menu_enabled(&mut self, enabled: bool) {
1103        self.enable_context_menu = enabled;
1104    }
1105
1106    /// Set whether search UI allows replacement, default is true.
1107    #[doc(hidden)]
1108    pub fn replaceable(mut self, allow: bool) -> Self {
1109        self.replaceable = allow;
1110        self
1111    }
1112
1113    /// Set placeholder
1114    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1115        self.placeholder = placeholder.into();
1116        self
1117    }
1118
1119    /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode.
1120    pub fn set_highlighter(
1121        &mut self,
1122        new_language: impl Into<SharedString>,
1123        cx: &mut Context<Self>,
1124    ) {
1125        match &mut self.mode {
1126            LayoutMode::CodeEditor {
1127                language,
1128                highlighter,
1129                ..
1130            } => {
1131                language.set_name(new_language.into());
1132                *highlighter.borrow_mut() = None;
1133            }
1134            _ => {}
1135        }
1136        self.refresh(cx);
1137    }
1138
1139    fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
1140        match &mut self.mode {
1141            LayoutMode::CodeEditor { highlighter, .. } => {
1142                *highlighter.borrow_mut() = None;
1143            }
1144            _ => {}
1145        }
1146        cx.notify();
1147    }
1148
1149    /// Install the parser/highlighter adapter used by code-editor mode.
1150    pub fn set_highlighter_factory(
1151        &mut self,
1152        factory: InputHighlighterFactory,
1153        cx: &mut Context<Self>,
1154    ) {
1155        self.mode.set_highlighter_factory(factory);
1156        self._pending_update = true;
1157        self.token_layout_cache = None;
1158        cx.notify();
1159    }
1160
1161    /// Install a default adapter without replacing an application-provided one.
1162    pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
1163        self.mode.ensure_highlighter_factory(factory);
1164    }
1165
1166    pub fn set_editor_style(&mut self, style: InputEditorStyle) {
1167        self.editor_style = style.clone();
1168        self.projected_editor_style = style;
1169    }
1170
1171    /// Draws a placeholder right after the text of each folded line, given its
1172    /// buffer row. Clicking it unfolds the line.
1173    pub fn set_fold_placeholder_renderer(
1174        &mut self,
1175        renderer: Option<FoldPlaceholderRenderer>,
1176        cx: &mut Context<Self>,
1177    ) {
1178        self.fold_placeholder_renderer = renderer;
1179        cx.notify();
1180    }
1181
1182    /// Fills each folded line across the editor, as VS Code's
1183    /// `editor.foldBackground`.
1184    pub fn set_fold_background(&mut self, color: Option<Hsla>, cx: &mut Context<Self>) {
1185        self.fold_background = color;
1186        cx.notify();
1187    }
1188
1189    /// Project semantics onto the editor, never onto a second focus owner.
1190    pub fn set_accessibility(&mut self, accessibility: InputAccessibility) {
1191        self.accessibility = Some(accessibility);
1192    }
1193
1194    fn handle_accessibility_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1195        if !self.disabled {
1196            self.focus(window, cx);
1197        }
1198    }
1199
1200    fn handle_accessibility_set_value(
1201        &mut self,
1202        data: Option<&gpui::accesskit::ActionData>,
1203        window: &mut Window,
1204        cx: &mut Context<Self>,
1205    ) {
1206        let Some(gpui::accesskit::ActionData::Value(value)) = data else {
1207            return;
1208        };
1209        // The action may have been queued before editability changed.
1210        if self.is_editable() {
1211            self.replace_all(value.to_string(), window, cx);
1212        }
1213    }
1214
1215    /// Set presentation padding for multi-line text and its scrollbar layout.
1216    #[doc(hidden)]
1217    pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
1218        self.editor_paddings = paddings;
1219    }
1220
1221    /// Supply the element painted in place of the editor's scrollbar, or
1222    /// `None` to keep Base's. The renderer is called where the editor paints
1223    /// its scrollbar, with that frame's [`EditorScrollbarContext`]. Like
1224    /// [`Self::set_editor_style`], this does not notify, so it can be called
1225    /// while rendering.
1226    ///
1227    /// [`EditorScrollbarContext`]: crate::input::EditorScrollbarContext
1228    pub fn set_scrollbar_renderer(
1229        &mut self,
1230        renderer: Option<crate::input::EditorScrollbarRenderer>,
1231    ) {
1232        self.scrollbar_renderer = renderer;
1233    }
1234
1235    pub fn apply_highlighter_fold_candidates(
1236        &mut self,
1237        candidates: Vec<crate::input::FoldRange>,
1238        cx: &mut Context<Self>,
1239    ) {
1240        if self.mode.is_folding() {
1241            self.display_map.set_fold_candidates(candidates);
1242        }
1243        cx.notify();
1244    }
1245
1246    #[inline]
1247    pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
1248        self.mode.diagnostics()
1249    }
1250
1251    #[inline]
1252    pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
1253        self.mode.diagnostics_mut()
1254    }
1255
1256    /// Set placeholder
1257    pub fn set_placeholder(
1258        &mut self,
1259        placeholder: impl Into<SharedString>,
1260        _: &mut Window,
1261        cx: &mut Context<Self>,
1262    ) {
1263        self.placeholder = placeholder.into();
1264        cx.notify();
1265    }
1266
1267    /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
1268    ///
1269    /// Returns:
1270    ///
1271    /// - The index of the line (zero-based) containing the offset.
1272    /// - The index of the sub-line (zero-based) within the line containing the offset.
1273    /// - The position of the offset.
1274    pub(super) fn line_and_position_for_offset(
1275        &self,
1276        offset: usize,
1277    ) -> (usize, usize, Option<Point<Pixels>>) {
1278        let Some(last_layout) = &self.last_layout else {
1279            return (0, 0, None);
1280        };
1281        let line_height = last_layout.line_height;
1282        let target_row = self.text.offset_to_point(offset.min(self.text.len())).row;
1283
1284        let mut row_offset: isize = 0;
1285        for (vi, line) in last_layout.lines.iter().enumerate() {
1286            let buffer_line = last_layout.visible_buffer_lines[vi];
1287            if buffer_line == target_row {
1288                let y_offset = last_layout.local_row_y(row_offset);
1289                let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
1290                let local_offset = offset.saturating_sub(prev_lines_offset).min(line.len());
1291                let pos = line
1292                    .position_for_index(local_offset, last_layout, false)
1293                    .unwrap_or_else(|| point(px(0.), px(0.)));
1294                let sub_line_index = (pos.y / line_height) as usize;
1295                let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
1296                return (vi, sub_line_index, Some(adjusted_pos));
1297            }
1298
1299            row_offset += line.wrapped_lines.len() as isize;
1300        }
1301        (0, 0, None)
1302    }
1303
1304    /// Set the value of the input field: plain text, or [`InputContent`] to
1305    /// restore text together with its inline tokens. Editing history is
1306    /// cleared and no [`InputEvent::Change`] is emitted.
1307    ///
1308    /// For single-line inputs the caret is placed at the end of the text while
1309    /// the view is scrolled back to the start, so a long value shows its
1310    /// beginning instead of its tail (matching HTML `<input>`). Multi-line
1311    /// inputs reset the selection to `0..0`.
1312    pub fn set_value(
1313        &mut self,
1314        value: impl Into<super::InputContent>,
1315        window: &mut Window,
1316        cx: &mut Context<Self>,
1317    ) {
1318        let content = value.into();
1319        self.inline_tokens = None;
1320        self.undo_manager.set_ignoring(true);
1321        self.emit_events = false;
1322        self.replace_text(content.text().clone(), window, cx);
1323        self.ime_original_text = None;
1324        self.install_tokens(content);
1325        self.undo_manager.set_ignoring(false);
1326        self.emit_events = true;
1327
1328        self.reset_selection();
1329        self.reset_lsp_state();
1330        self.reset_scroll_to_start();
1331
1332        self.undo_manager.clear();
1333        cx.notify();
1334    }
1335
1336    /// Replace the entire text content while preserving undo history.
1337    ///
1338    /// Unlike [`set_value`](Self::set_value), this method records the
1339    /// replacement in the undo stack, allowing the user to undo/redo
1340    /// the change. The selection is placed at the end of the new text
1341    /// for single-line inputs, or cleared (0..0) for multi-line inputs.
1342    ///
1343    /// Use this when programmatically replacing the full text but the
1344    /// user should still be able to undo the operation — e.g. formatting.
1345    pub fn replace_all(
1346        &mut self,
1347        text: impl Into<SharedString>,
1348        window: &mut Window,
1349        cx: &mut Context<Self>,
1350    ) {
1351        self.replace_text(text, window, cx);
1352        self.reset_selection();
1353        self.reset_lsp_state();
1354        self.reset_scroll_to_start();
1355
1356        cx.notify();
1357    }
1358
1359    /// Perform `f` with the user-facing edit restrictions lifted.
1360    ///
1361    /// The `disabled` and `readonly` modes only reject the changes made by the
1362    /// user, the programmatic APIs must always be able to update the text.
1363    pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1364        let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1365        (self.disabled, self.readonly) = (false, false);
1366        f(self);
1367        (self.disabled, self.readonly) = (was_disabled, was_readonly);
1368    }
1369
1370    /// Insert text at the current cursor position.
1371    ///
1372    /// And the cursor will be moved to the end of inserted text.
1373    pub fn insert(
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            let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1383            this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1384            let end = this.active_selection().end;
1385            this.set_cursor_to(end);
1386        });
1387    }
1388
1389    /// Replace text at the current cursor position.
1390    ///
1391    /// And the cursor will be moved to the end of replaced text.
1392    pub fn replace(
1393        &mut self,
1394        text: impl Into<SharedString>,
1395        window: &mut Window,
1396        cx: &mut Context<Self>,
1397    ) {
1398        let text: SharedString = text.into();
1399        self.with_edits_allowed(|this| {
1400            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1401            this.replace_text_in_range_silent(None, &text, window, cx);
1402            let end = this.active_selection().end;
1403            this.set_cursor_to(end);
1404        });
1405    }
1406
1407    fn replace_text(
1408        &mut self,
1409        text: impl Into<SharedString>,
1410        window: &mut Window,
1411        cx: &mut Context<Self>,
1412    ) {
1413        let text: SharedString = text.into();
1414        self.with_edits_allowed(|this| {
1415            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1416            let range = 0..this.text.len_utf16();
1417            this.replace_text_in_range_silent(Some(range), &text, window, cx);
1418            this.reset_highlighter(cx);
1419        });
1420    }
1421
1422    fn reset_selection(&mut self) {
1423        self.selections.remove_all_but_active();
1424
1425        // For single-line inputs the caret is placed at the end of the text
1426        // (matching HTML `<input>`); multi-line inputs reset the selection to
1427        // `0..0`.
1428        if self.is_single_line() {
1429            let end = self.text.len();
1430            self.set_cursor_to(end);
1431        } else {
1432            self.active_selection_mut().clear();
1433        }
1434    }
1435
1436    fn reset_lsp_state(&mut self) {
1437        if self.is_code_editor() {
1438            self._pending_update = true;
1439            M::reset_language_features(self);
1440        }
1441    }
1442
1443    fn reset_scroll_to_start(&mut self) {
1444        // Move scroll to the start. For single-line the caret is at the end, so
1445        // override the cursor-follow scroll for the next painted frame to keep
1446        // the start visible; the deferred offset is consumed during that paint.
1447        self.scroll_handle.set_offset(point(px(0.), px(0.)));
1448        self.scroll_y_f64 = 0.0;
1449        self.last_synced_handle_y.set(px(0.));
1450        if self.is_single_line() {
1451            self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1452            self.deferred_scroll_y_f64 = Some(0.0);
1453        }
1454    }
1455
1456    /// Set with disabled mode.
1457    ///
1458    /// See also: [`Self::set_disabled`].
1459    #[allow(unused)]
1460    pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1461        self.disabled = disabled;
1462        self
1463    }
1464
1465    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1466        if self.disabled == disabled {
1467            return;
1468        }
1469
1470        self.disabled = disabled;
1471        if disabled {
1472            M::hide_context_menu(self, cx);
1473            M::clear_inline_completion(self, cx);
1474        }
1475        cx.notify();
1476    }
1477
1478    /// Set with read-only mode.
1479    ///
1480    /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1481    /// focus, cursor, selection and copy behavior, it only rejects any change
1482    /// of the text made by the user.
1483    ///
1484    /// See also: [`Self::set_readonly`].
1485    #[allow(unused)]
1486    pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1487        self.readonly = readonly;
1488        self
1489    }
1490
1491    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1492        if self.readonly == readonly {
1493            return;
1494        }
1495
1496        self.readonly = readonly;
1497        if readonly {
1498            M::hide_context_menu(self, cx);
1499            M::clear_inline_completion(self, cx);
1500            self.search_session.replace_mode = false;
1501        }
1502        cx.notify();
1503    }
1504
1505    /// Returns true if the user is allowed to change the text.
1506    ///
1507    /// This is false when the input is `disabled` or `readonly`, the programmatic
1508    /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1509    pub fn is_editable(&self) -> bool {
1510        !self.disabled && !self.readonly
1511    }
1512
1513    /// Set true to clear the input by pressing Escape key.
1514    ///
1515    /// Not on Android, where Escape is also the back button.
1516    pub fn clean_on_escape(mut self) -> Self {
1517        self.clean_on_escape = true;
1518        self
1519    }
1520
1521    pub fn set_clean_on_escape(&mut self, clean: bool) {
1522        self.clean_on_escape = clean;
1523    }
1524
1525    /// Set true to treat `Enter` as a submit action in multi-line mode,
1526    /// while `Shift+Enter` inserts a newline.
1527    ///
1528    /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1529    #[doc(hidden)]
1530    pub fn submit_on_enter(mut self, submit: bool) -> Self {
1531        self.submit_on_enter = submit;
1532        self
1533    }
1534
1535    pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1536        self.submit_on_enter = submit;
1537        cx.notify();
1538    }
1539
1540    /// Set the action a software keyboard shows on its enter key, like Search
1541    /// or Send. Pressing it still emits [`InputEvent::PressEnter`].
1542    ///
1543    /// Default is [`TextInputAction::Done`] for a single-line input (and a
1544    /// multi-line one that submits on enter), and [`TextInputAction::Enter`]
1545    /// (a line break) for a multi-line input.
1546    pub fn input_action(mut self, action: TextInputAction) -> Self {
1547        self.input_action = Some(action);
1548        self
1549    }
1550
1551    /// Set whether the platform may autocorrect the text and offer word
1552    /// suggestions.
1553    ///
1554    /// Default is `false`. Enable this explicitly for fields that accept prose;
1555    /// masking or revealing text does not change the setting.
1556    pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1557        self.autocorrect = Some(autocorrect);
1558        self
1559    }
1560
1561    /// Set how a software keyboard capitalizes the text.
1562    ///
1563    /// Default is [`Autocapitalize::None`]. Enable capitalization explicitly for
1564    /// fields where it is appropriate, independently of autocorrection.
1565    pub fn autocapitalize(mut self, autocapitalize: Autocapitalize) -> Self {
1566        self.autocapitalize = Some(autocapitalize);
1567        self
1568    }
1569
1570    /// The text assistance a platform IME (a software keyboard) should give
1571    /// this input, from [`Self::input_action`], [`Self::autocorrect`] and
1572    /// [`Self::autocapitalize`] or the defaults they describe.
1573    pub fn text_input_configuration(&self) -> TextInputConfiguration {
1574        // Masking is a presentation choice, not a reliable content type: a
1575        // revealed password must not acquire text assistance. Keep assistance
1576        // opt-in for structured fields such as passwords, email and URLs.
1577        let autocorrect = self.autocorrect.unwrap_or(false);
1578        let input_action =
1579            self.input_action
1580                .unwrap_or(if self.is_multi_line() && !self.submit_on_enter {
1581                    TextInputAction::Enter
1582                } else {
1583                    TextInputAction::Done
1584                });
1585        TextInputConfiguration {
1586            autocorrect,
1587            autocapitalize: self.autocapitalize.unwrap_or(Autocapitalize::None),
1588            suggestions: autocorrect,
1589            input_action,
1590        }
1591    }
1592
1593    /// Set whether to show whitespace characters.
1594    #[doc(hidden)]
1595    pub fn show_whitespaces(mut self, show: bool) -> Self {
1596        self.show_whitespaces = show;
1597        self
1598    }
1599
1600    /// Update whether to show whitespace characters.
1601    pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1602        self.show_whitespaces = show;
1603        cx.notify();
1604    }
1605
1606    /// Empty rows reserved below the last line of content ("scroll
1607    /// beyond last line"), code-editor mode only. Mirrors VSCode's
1608    /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1609    ///
1610    /// - `None` (default): half the viewport, floored at
1611    ///   [`BOTTOM_MARGIN_ROWS`] line-heights.
1612    /// - `Some(0)`: no trailing space; the cursor sits flush with the
1613    ///   last row at scroll-max.
1614    /// - `Some(n)`: exactly `n` rows.
1615    pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1616        self.scroll_beyond_last_line = rows;
1617        self
1618    }
1619
1620    /// Update [`Self::scroll_beyond_last_line`] after construction.
1621    pub fn set_scroll_beyond_last_line(
1622        &mut self,
1623        rows: Option<usize>,
1624        _: &mut Window,
1625        cx: &mut Context<Self>,
1626    ) {
1627        if self.scroll_beyond_last_line == rows {
1628            return;
1629        }
1630        self.scroll_beyond_last_line = rows;
1631        cx.notify();
1632    }
1633
1634    /// Minimum number of lines the cursor is kept clear of the viewport's
1635    /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1636    /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1637    /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1638    /// empty region; this controls the cursor's resting distance from the
1639    /// edge.
1640    ///
1641    /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to
1642    ///   one line on small viewports.
1643    /// - `Some(n)`: requests `n` lines, clamped to half the viewport.
1644    ///
1645    /// In a constrained viewport, edge clearance yields to the cursor's
1646    /// complete visual row so surrounding space cannot clip the text being edited.
1647    pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1648        self.cursor_surrounding_lines = lines;
1649        self
1650    }
1651
1652    /// Update [`Self::cursor_surrounding_lines`] after construction.
1653    pub fn set_cursor_surrounding_lines(
1654        &mut self,
1655        lines: Option<usize>,
1656        _: &mut Window,
1657        cx: &mut Context<Self>,
1658    ) {
1659        if self.cursor_surrounding_lines == lines {
1660            return;
1661        }
1662        self.cursor_surrounding_lines = lines;
1663        cx.notify();
1664    }
1665
1666    /// Set the default value of the input field.
1667    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1668        let text: SharedString = value.into();
1669        self.text = Rope::from(self.normalize_input(&text).as_ref());
1670        if let Some(diagnostics) = self.mode.diagnostics_mut() {
1671            diagnostics.reset(&self.text)
1672        }
1673        // Note: We can't call display_map.set_text here because it needs cx.
1674        // The text will be set during prepare_if_need in element.rs
1675        self._pending_update = true;
1676        self
1677    }
1678
1679    /// Return the value of the input field as an owned string.
1680    ///
1681    /// The string is materialized on each call. See [`Self::text`] for the
1682    /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1683    pub fn value(&self) -> SharedString {
1684        SharedString::new(self.text.to_string())
1685    }
1686
1687    /// Return the portion of the value within the input field that
1688    /// is selected by the user, as an owned string.
1689    ///
1690    /// The string is materialized on each call. See [`Self::selected_text`]
1691    /// for the same selection borrowed out of the [`Rope`] the state owns.
1692    pub fn selected_value(&self) -> SharedString {
1693        SharedString::new(self.selected_text().to_string())
1694    }
1695
1696    /// Return the value without mask.
1697    pub fn unmask_value(&self) -> SharedString {
1698        self.mask_pattern.unmask(&self.text.to_string()).into()
1699    }
1700
1701    /// Kept so existing render paths keep compiling.
1702    ///
1703    /// Configuration used to be collected by a facade and applied here; the
1704    /// state now configures itself, so this does nothing and can be deleted at
1705    /// the call site.
1706    #[doc(hidden)]
1707    pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1708
1709    /// Return the text [`Rope`] of the input field.
1710    ///
1711    /// Borrowed from the state, so reading even a large document copies
1712    /// nothing. See [`Self::value`] when an owned string is wanted.
1713    pub fn text(&self) -> &Rope {
1714        &self.text
1715    }
1716
1717    /// Report the change with its own snapshot before the legacy notification.
1718    fn emit_change(&mut self, cx: &mut Context<Self>) {
1719        if let Some(original) = self.ime_original_text.take() {
1720            self.last_input_edits = vec![(
1721                Self::full_input_edit(&original, &self.text),
1722                self.text.clone(),
1723            )];
1724        }
1725        cx.emit(InputEditsEvent {
1726            edits: self.last_input_edits.clone(),
1727        });
1728        cx.emit(InputEvent::Change);
1729    }
1730
1731    fn full_input_edit(old_text: &Rope, new_text: &Rope) -> InputEdit {
1732        InputEdit {
1733            start_byte: 0,
1734            old_end_byte: old_text.len(),
1735            new_end_byte: new_text.len(),
1736            start_position: old_text.offset_to_point(0),
1737            old_end_position: old_text.offset_to_point(old_text.len()),
1738            new_end_position: new_text.offset_to_point(new_text.len()),
1739        }
1740    }
1741
1742    /// Return the (0-based) [`Position`] of the cursor.
1743    pub fn cursor_position(&self) -> Position {
1744        let offset = self.cursor();
1745        self.text.offset_to_position(offset)
1746    }
1747
1748    /// Set (0-based) [`Position`] of the cursor.
1749    ///
1750    /// This will move the cursor to the specified line and column, and update the selection range.
1751    pub fn set_cursor_position(
1752        &mut self,
1753        position: impl Into<Position>,
1754        window: &mut Window,
1755        cx: &mut Context<Self>,
1756    ) {
1757        let position: Position = position.into();
1758        let offset = self.text.position_to_offset(&position);
1759
1760        self.move_to(offset, None, cx);
1761        self.update_preferred_column();
1762        self.focus(window, cx);
1763    }
1764
1765    /// Focus the input field.
1766    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1767        self.focus_handle.focus(window, cx);
1768        self.blink_cursor.update(cx, |cursor, cx| {
1769            cursor.start(cx);
1770        });
1771    }
1772
1773    /// Refresh the input, so the next render re-runs syntax highlighting and
1774    /// the LSP providers, not just a redraw.
1775    ///
1776    /// Assigning the `lsp` providers (or other render-affecting state) at
1777    /// runtime does not take effect until the text next changes. Call this
1778    /// afterwards to force the refresh on the next render.
1779    ///
1780    /// ```ignore
1781    /// input.update(cx, |state, cx| {
1782    ///     state.extras.lsp.hover_provider = Some(provider);
1783    ///     state.refresh(cx);
1784    /// });
1785    /// ```
1786    pub fn refresh(&mut self, cx: &mut Context<Self>) {
1787        self._pending_update = true;
1788        cx.notify();
1789    }
1790
1791    pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1792        self.undo_manager.break_transaction_coalescing();
1793        let mirrored = self.arrows_mirrored(cx);
1794        self.select_all_cursors_to(
1795            move |s, sel| {
1796                if mirrored {
1797                    s.next_boundary(sel.cursor_offset())
1798                } else {
1799                    s.previous_boundary(sel.cursor_offset())
1800                }
1801            },
1802            cx,
1803        );
1804    }
1805
1806    pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1807        let mirrored = self.arrows_mirrored(cx);
1808        self.select_all_cursors_to(
1809            move |s, sel| {
1810                if mirrored {
1811                    s.previous_boundary(sel.cursor_offset())
1812                } else {
1813                    s.next_boundary(sel.cursor_offset())
1814                }
1815            },
1816            cx,
1817        );
1818    }
1819
1820    pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1821        if self.is_single_line() {
1822            return;
1823        }
1824        self.select_all_cursors_to_with_affinity(
1825            |s, sel| {
1826                s.vertical_selection_target(
1827                    sel.cursor_offset(),
1828                    sel.column_anchor,
1829                    s.line_end_affinity_for(sel),
1830                    -1,
1831                )
1832            },
1833            true,
1834            cx,
1835        );
1836    }
1837
1838    pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1839        if self.is_single_line() {
1840            return;
1841        }
1842        self.select_all_cursors_to_with_affinity(
1843            |s, sel| {
1844                s.vertical_selection_target(
1845                    sel.cursor_offset(),
1846                    sel.column_anchor,
1847                    s.line_end_affinity_for(sel),
1848                    1,
1849                )
1850            },
1851            true,
1852            cx,
1853        );
1854    }
1855
1856    pub(super) fn on_action_select_all(
1857        &mut self,
1858        _: &SelectAll,
1859        window: &mut Window,
1860        cx: &mut Context<Self>,
1861    ) {
1862        self.select_all(window, cx);
1863    }
1864
1865    pub(super) fn select_to_start(
1866        &mut self,
1867        _: &SelectToStart,
1868        _: &mut Window,
1869        cx: &mut Context<Self>,
1870    ) {
1871        self.undo_manager.break_transaction_coalescing();
1872        self.select_all_cursors_to(|_, _| 0, cx);
1873    }
1874
1875    pub(super) fn select_to_end(
1876        &mut self,
1877        _: &SelectToEnd,
1878        _: &mut Window,
1879        cx: &mut Context<Self>,
1880    ) {
1881        self.undo_manager.break_transaction_coalescing();
1882        let end = self.text.len();
1883        self.select_all_cursors_to(move |_, _| end, cx);
1884    }
1885
1886    pub(super) fn select_to_start_of_line(
1887        &mut self,
1888        _: &SelectToStartOfLine,
1889        _: &mut Window,
1890        cx: &mut Context<Self>,
1891    ) {
1892        self.undo_manager.break_transaction_coalescing();
1893        self.select_all_cursors_to(
1894            |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1895            cx,
1896        );
1897    }
1898
1899    pub(super) fn select_to_end_of_line(
1900        &mut self,
1901        _: &SelectToEndOfLine,
1902        _: &mut Window,
1903        cx: &mut Context<Self>,
1904    ) {
1905        self.undo_manager.break_transaction_coalescing();
1906        self.select_all_cursors_to_with_affinity(
1907            |s, sel| {
1908                (
1909                    s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1910                    true,
1911                )
1912            },
1913            false,
1914            cx,
1915        );
1916    }
1917
1918    pub(super) fn select_to_previous_word(
1919        &mut self,
1920        _: &SelectToPreviousWordStart,
1921        _: &mut Window,
1922        cx: &mut Context<Self>,
1923    ) {
1924        self.undo_manager.break_transaction_coalescing();
1925        let mirrored = self.arrows_mirrored(cx);
1926        self.select_all_cursors_to(
1927            move |s, sel| {
1928                if mirrored {
1929                    s.next_end_of_word_at(sel.cursor_offset())
1930                } else {
1931                    s.previous_start_of_word_at(sel.cursor_offset())
1932                }
1933            },
1934            cx,
1935        );
1936    }
1937
1938    pub(super) fn select_to_next_word(
1939        &mut self,
1940        _: &SelectToNextWordEnd,
1941        _: &mut Window,
1942        cx: &mut Context<Self>,
1943    ) {
1944        self.undo_manager.break_transaction_coalescing();
1945        let mirrored = self.arrows_mirrored(cx);
1946        self.select_all_cursors_to(
1947            move |s, sel| {
1948                if mirrored {
1949                    s.previous_start_of_word_at(sel.cursor_offset())
1950                } else {
1951                    s.next_end_of_word_at(sel.cursor_offset())
1952                }
1953            },
1954            cx,
1955        );
1956    }
1957
1958    /// Return the start offset of the previous word.
1959    /// Return the previous start offset of the word before `offset`.
1960    pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1961        if self.masked {
1962            // The mask replaces every character, so the displayed text has no
1963            // word boundaries to move or delete by. Collapse the word to the
1964            // whole text.
1965            return 0;
1966        }
1967
1968        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1969        // FIXME: Avoid to_string
1970        let left_part = self.text.slice(0..offset).to_string();
1971
1972        let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1973            .rfind(|(_, s)| !s.trim_start().is_empty())
1974            .map(|(i, _)| i)
1975            .unwrap_or(0);
1976        self.token_boundary(target, Bias::Left)
1977    }
1978
1979    /// Return the next end offset of the word after `offset`.
1980    pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1981        if self.masked {
1982            // See `previous_start_of_word_at`.
1983            return self.text.len();
1984        }
1985
1986        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1987        let right_part = self.text.slice(offset..self.text.len()).to_string();
1988
1989        let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1990            .find(|(_, s)| !s.trim_start().is_empty())
1991            .map(|(i, s)| offset + i + s.len())
1992            .unwrap_or(self.text.len());
1993        self.token_boundary(target, Bias::Right)
1994    }
1995
1996    /// Get start of line byte offset for the given `offset`.
1997    ///
1998    /// When soft wrap is active, first press goes to visual line start,
1999    /// second press (already at visual start) goes to logical line start.
2000    pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2001        if self.is_single_line() {
2002            return 0;
2003        }
2004
2005        let row = self.text.offset_to_point(offset).row;
2006        let logical_start = self.text.line_start_offset(row);
2007
2008        if self.soft_wrap && self.is_code_editor() {
2009            let wrap_point = self
2010                .display_map
2011                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2012            if let Some(line) = self.display_map.line(row)
2013                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2014            {
2015                let visual_start = logical_start + range.start;
2016                if offset != visual_start {
2017                    return visual_start;
2018                }
2019            }
2020        }
2021
2022        logical_start
2023    }
2024
2025    /// Get end of line byte offset for the given `offset`.
2026    ///
2027    /// When soft wrap is active, first press goes to visual line end,
2028    /// second press (already at visual end) goes to logical line end.
2029    pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2030        if self.is_single_line() {
2031            return self.text.len();
2032        }
2033
2034        let row = self.text.offset_to_point(offset).row;
2035        let logical_start = self.text.line_start_offset(row);
2036        let logical_end = self.text.line_end_offset(row);
2037
2038        if self.soft_wrap && self.is_code_editor() {
2039            // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
2040            // the next row, and a second End press would keep walking down instead of falling
2041            // through to the logical line end.
2042            let wrap_point = self
2043                .display_map
2044                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2045            if let Some(line) = self.display_map.line(row)
2046                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2047            {
2048                let visual_end = logical_start + range.end;
2049                if offset != visual_end {
2050                    return visual_end;
2051                }
2052            }
2053        }
2054
2055        logical_end
2056    }
2057
2058    /// Get indent string of next line.
2059    ///
2060    /// To get current and next line indent, to return more depth one.
2061    pub(super) fn indent_of_next_line(&mut self) -> String {
2062        self.indent_of_next_line_at(self.cursor())
2063    }
2064
2065    /// Get indent string of the next line, relative to the given `offset`.
2066    pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
2067        if self.is_single_line() {
2068            return "".into();
2069        }
2070
2071        let mut current_indent = String::new();
2072        let mut next_indent = String::new();
2073        let line_end_affinity = self.line_end_affinity_at(offset);
2074        let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
2075        let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
2076        for c in self.text.slice(current_line_start_pos..).chars() {
2077            if !c.is_whitespace() {
2078                break;
2079            }
2080            if c == '\n' || c == '\r' {
2081                break;
2082            }
2083            current_indent.push(c);
2084        }
2085
2086        for c in self.text.slice(next_line_start_pos..).chars() {
2087            if !c.is_whitespace() {
2088                break;
2089            }
2090            if c == '\n' || c == '\r' {
2091                break;
2092            }
2093            next_indent.push(c);
2094        }
2095
2096        if next_indent.len() > current_indent.len() {
2097            return next_indent;
2098        }
2099
2100        // Smart indent: one extra level after lines ending with a trigger.
2101        // Skipped inside strings and comments: the trigger is literal text.
2102        if let Some(rules) = self.mode.language_config() {
2103            if self.mode.is_smart_indent()
2104                && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
2105            {
2106                let line_before: String = self
2107                    .text
2108                    .slice(current_line_start_pos..offset)
2109                    .chars()
2110                    .collect();
2111                if rules.opens_indent(line_before.trim_end()) {
2112                    let tab = self.mode.tab_size();
2113                    if tab.hard_tabs {
2114                        current_indent.push('\t');
2115                    } else {
2116                        for _ in 0..tab.tab_size {
2117                            current_indent.push(' ');
2118                        }
2119                    }
2120                } else {
2121                    let line_after = self.text.slice(offset..next_line_start_pos).to_string();
2122                    if rules.closes_indent(&line_after) {
2123                        let tab = self.mode.tab_size();
2124                        if current_indent.ends_with('\t') {
2125                            current_indent.pop();
2126                        } else {
2127                            for _ in 0..tab.tab_size {
2128                                if !current_indent.ends_with(' ') {
2129                                    break;
2130                                }
2131                                current_indent.pop();
2132                            }
2133                        }
2134                    }
2135                }
2136            }
2137        }
2138
2139        current_indent
2140    }
2141
2142    /// Delete every selection as one batch. Collapsed cursors are first
2143    /// expanded to a deletion range by `collapsed_target` and non-empty
2144    /// selections delete their own range.
2145    ///
2146    /// `collapsed_intent` is the intent to record when every cursor is
2147    /// collapsed, which is what makes a run of single-character deletes undo
2148    /// as one gesture. Deleting a real selection is always atomic.
2149    fn delete_selections(
2150        &mut self,
2151        silent: bool,
2152        collapsed_intent: EditIntent,
2153        mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
2154        window: &mut Window,
2155        cx: &mut Context<Self>,
2156    ) {
2157        if !self.is_editable() {
2158            return;
2159        }
2160        let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
2161        let intent = if cursors.iter().all(|sel| sel.is_empty()) {
2162            collapsed_intent
2163        } else {
2164            EditIntent::Atomic
2165        };
2166        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
2167        for sel in &cursors {
2168            let range = if sel.is_empty() {
2169                collapsed_target(self, sel.cursor_offset())
2170            } else {
2171                sel.start..sel.end
2172            };
2173            let (start, end) = (range.start.min(range.end), range.start.max(range.end));
2174            let mut selection = *sel;
2175            selection.start = start;
2176            selection.end = end;
2177            new_selections.push(selection);
2178        }
2179        // Capture the user's selections before expanding or merging deletion
2180        // ranges. The edit ranges cannot reconstruct their original carets.
2181        self.undo_manager.begin_transaction_with(intent);
2182        self.undo_manager
2183            .record_selections(cursors.clone(), cursors.clone());
2184        self.selections.replace_all(new_selections);
2185        self.undo_manager.set_pending_intent(intent);
2186
2187        let was_silent = self.silent_replace_text;
2188        self.silent_replace_text = silent;
2189        self.replace_text_in_range(None, "", window, cx);
2190        self.silent_replace_text = was_silent;
2191        self.undo_manager
2192            .record_selections(cursors, self.selections.iter().copied().collect());
2193        self.undo_manager.commit_transaction();
2194        self.pause_blink_cursor(cx);
2195    }
2196
2197    /// Decide pairing against the pre-edit text, before an opening quote can
2198    /// change its own syntax context. Ordinary characters never query syntax.
2199    fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
2200        if self.silent_replace_text
2201            || self.ime_marked_range.is_some()
2202            || !self.selections.is_single()
2203            || !self.active_selection().is_empty()
2204            || !range.is_empty()
2205            || range.start != self.cursor()
2206            || text.chars().count() != 1
2207            || !self.mode.is_auto_close()
2208        {
2209            return None;
2210        }
2211        let rules = self.mode.language_config()?;
2212        if self
2213            .text
2214            .chars_at(range.start)
2215            .next()
2216            .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
2217        {
2218            return None;
2219        }
2220        for (open, close, not_in) in rules.closing_pairs() {
2221            let Some(prefix) = open.strip_suffix(text) else {
2222                continue;
2223            };
2224            if !self.text_before_matches(range.start, prefix) {
2225                continue;
2226            }
2227            let start = range.start - prefix.len();
2228            if open == close
2229                && (self.is_escaped_at(start)
2230                    || self
2231                        .text
2232                        .chars_at(start)
2233                        .reversed()
2234                        .next()
2235                        .is_some_and(|c| c.is_alphanumeric() || c == '_'))
2236            {
2237                continue;
2238            }
2239            if not_in.contains(&M::editing_syntax_context(self, start)) {
2240                continue;
2241            }
2242            return Some((open.len(), close.into()));
2243        }
2244        None
2245    }
2246
2247    fn text_before_matches(&self, offset: usize, text: &str) -> bool {
2248        offset >= text.len()
2249            && self.text.is_char_boundary(offset - text.len())
2250            && self.text.slice(offset - text.len()..offset) == text
2251    }
2252
2253    fn text_after_matches(&self, offset: usize, text: &str) -> bool {
2254        offset + text.len() <= self.text.len()
2255            && self.text.is_char_boundary(offset + text.len())
2256            && self.text.slice(offset..offset + text.len()) == text
2257    }
2258
2259    fn is_escaped_at(&self, offset: usize) -> bool {
2260        self.text
2261            .chars_at(offset)
2262            .reversed()
2263            .take_while(|c| *c == '\\')
2264            .count()
2265            % 2
2266            == 1
2267    }
2268
2269    /// Cursor target when a typed closer should skip over an existing one.
2270    ///
2271    /// Returns `Some(offset)` when `new_text` is a single closer from the
2272    /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
2273    /// not escaped. The caller then moves the cursor without editing text or
2274    /// history. `None` means insert normally.
2275    fn skip_over_target(&self, new_text: &str) -> Option<usize> {
2276        if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
2277            return None;
2278        }
2279        let rules = self.mode.language_config()?;
2280        let cursor = self.cursor();
2281        for (open, close, not_in) in rules.closing_pairs() {
2282            for (index, _) in close.char_indices() {
2283                if !close[index..].starts_with(new_text)
2284                    || !self.text_before_matches(cursor, &close[..index])
2285                    || !self.text_after_matches(cursor, &close[index..])
2286                {
2287                    continue;
2288                }
2289                let context = M::editing_syntax_context(self, cursor);
2290                let generated =
2291                    self.mode
2292                        .auto_closed_pairs()
2293                        .contains_closer(cursor, index, close.len());
2294                if !generated
2295                    && not_in.contains(&context)
2296                    && !(context == crate::input::SyntaxContext::String && open == close)
2297                {
2298                    continue;
2299                }
2300                if self.is_escaped_at(cursor - index) {
2301                    continue;
2302                }
2303                return Some(cursor + new_text.len());
2304            }
2305        }
2306        None
2307    }
2308
2309    pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
2310        // Nothing to delete at the start of the text. Propagate so an ancestor
2311        // (e.g. a command palette navigating back a level) can act on it.
2312        // This is harmless when nothing upstream is bound to backspace. With multiple
2313        // cursors the others can still delete, so only the lone-cursor case
2314        // propagates.
2315        if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
2316            cx.propagate();
2317            return;
2318        }
2319
2320        // Pair deletion follows automatic closing rules, independently of
2321        // structural brackets used by Enter.
2322        if self.mode.is_auto_close()
2323            && self.selections.is_single()
2324            && self.active_selection().is_empty()
2325        {
2326            let off = self.cursor();
2327            let deletion = self.mode.language_config().and_then(|rules| {
2328                rules.closing_pairs().find_map(|(open, close, not_in)| {
2329                    if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
2330                    {
2331                        return None;
2332                    }
2333                    let start = off - open.len();
2334                    let generated = self
2335                        .mode
2336                        .auto_closed_pairs()
2337                        .contains(start..off, off..off + close.len());
2338                    if self.is_escaped_at(start)
2339                        || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
2340                    {
2341                        return None;
2342                    }
2343                    Some(start..off + close.len())
2344                })
2345            });
2346            if let Some(range) = deletion {
2347                let utf16 = self.range_to_utf16(&range);
2348                self.replace_text_in_range_silent(Some(utf16), "", window, cx);
2349                return;
2350            }
2351        }
2352
2353        self.delete_selections(
2354            false,
2355            EditIntent::Backspace,
2356            |s, offset| s.previous_boundary(offset)..offset,
2357            window,
2358            cx,
2359        );
2360    }
2361
2362    pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2363        self.delete_selections(
2364            false,
2365            EditIntent::DeleteForward,
2366            |s, offset| offset..s.next_boundary(offset),
2367            window,
2368            cx,
2369        );
2370    }
2371
2372    pub(super) fn delete_to_beginning_of_line(
2373        &mut self,
2374        _: &DeleteToBeginningOfLine,
2375        window: &mut Window,
2376        cx: &mut Context<Self>,
2377    ) {
2378        self.delete_selections(
2379            true,
2380            EditIntent::Atomic,
2381            |s, offset| {
2382                let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
2383                if start == offset {
2384                    start = start.saturating_sub(1);
2385                }
2386                start..offset
2387            },
2388            window,
2389            cx,
2390        );
2391    }
2392
2393    pub(super) fn delete_to_end_of_line(
2394        &mut self,
2395        _: &DeleteToEndOfLine,
2396        window: &mut Window,
2397        cx: &mut Context<Self>,
2398    ) {
2399        self.delete_selections(
2400            true,
2401            EditIntent::Atomic,
2402            |s, offset| {
2403                let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
2404                if end == offset {
2405                    end = (end + 1).clamp(0, s.text.len());
2406                }
2407                offset..end
2408            },
2409            window,
2410            cx,
2411        );
2412    }
2413
2414    pub(super) fn delete_previous_word(
2415        &mut self,
2416        _: &DeleteToPreviousWordStart,
2417        window: &mut Window,
2418        cx: &mut Context<Self>,
2419    ) {
2420        self.delete_selections(
2421            true,
2422            EditIntent::Atomic,
2423            |s, offset| s.previous_start_of_word_at(offset)..offset,
2424            window,
2425            cx,
2426        );
2427    }
2428
2429    pub(super) fn delete_next_word(
2430        &mut self,
2431        _: &DeleteToNextWordEnd,
2432        window: &mut Window,
2433        cx: &mut Context<Self>,
2434    ) {
2435        self.delete_selections(
2436            true,
2437            EditIntent::Atomic,
2438            |s, offset| offset..s.next_word_delete_end_at(offset, !cfg!(target_os = "macos")),
2439            window,
2440            cx,
2441        );
2442    }
2443
2444    /// Return where a forward word delete starting at `offset` stops.
2445    ///
2446    /// With `stop_at_whitespace` (Windows and Linux `Ctrl+Delete`, as in
2447    /// Notepad and VS Code), a line break or a run of blanks is deleted on its
2448    /// own instead of together with the word after it. macOS `Option+Delete`
2449    /// deletes through to the end of the next word.
2450    pub(super) fn next_word_delete_end_at(&self, offset: usize, stop_at_whitespace: bool) -> usize {
2451        if stop_at_whitespace && !self.masked {
2452            let mut chars = self.text.slice(offset..self.text.len()).chars();
2453            match chars.next() {
2454                Some('\r') => {
2455                    let next = if chars.next() == Some('\n') { 2 } else { 1 };
2456                    return offset + next;
2457                }
2458                Some('\n') => return offset + 1,
2459                Some(c) if c.is_whitespace() => {
2460                    let mut end = offset + c.len_utf8();
2461                    for c in chars {
2462                        if c == '\n' || c == '\r' || !c.is_whitespace() {
2463                            break;
2464                        }
2465                        end += c.len_utf8();
2466                    }
2467                    return end;
2468                }
2469                _ => {}
2470            }
2471        }
2472        self.next_end_of_word_at(offset)
2473    }
2474
2475    pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
2476        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2477            return;
2478        }
2479
2480        // Clear inline completion on enter (user chose not to accept it)
2481        if M::has_inline_completion(self) {
2482            M::clear_inline_completion(self, cx);
2483        }
2484
2485        // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
2486        // (without Shift) is treated as submit: propagate the action and emit
2487        // PressEnter without inserting a newline. `Shift+Enter` still inserts
2488        // a newline. A secondary `Enter` (Cmd/Ctrl+Enter) is always a submit
2489        // gesture and never inserts a newline.
2490        let insert_newline =
2491            self.is_multi_line() && !action.secondary && (!self.submit_on_enter || action.shift);
2492
2493        if insert_newline {
2494            if !self.selections.is_single() {
2495                // Insert a newline (with per-line indent) at every cursor.
2496                self.selections.merge_overlapping();
2497                let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2498                let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
2499                for sel in &selections {
2500                    let indent = if self.is_code_editor() {
2501                        self.indent_of_next_line_at(sel.cursor_offset())
2502                    } else {
2503                        String::new()
2504                    };
2505                    edits.push((sel.start..sel.end, format!("\n{}", indent)));
2506                }
2507                edits.sort_by_key(|(range, _)| range.start);
2508                self.replace_text_in_ranges(&edits, window, cx);
2509                self.pause_blink_cursor(cx);
2510            } else {
2511                // Bracket split: Enter between `{|}` produces `{\n  \n}`
2512                // with the cursor on the middle line. Controlled by smart_indent,
2513                // independently of automatic closing.
2514                // Skipped inside strings and comments: splitting there would
2515                // restructure literal text.
2516                let mut split = false;
2517                if self.is_code_editor() && self.active_selection().is_empty() {
2518                    if let Some(rules) = self.mode.language_config() {
2519                        if self.mode.is_smart_indent()
2520                            && M::editing_syntax_context(self, self.cursor())
2521                                == crate::input::SyntaxContext::Code
2522                        {
2523                            let off = self.cursor();
2524                            let is_pair = rules.brackets.iter().any(|p| {
2525                                !p.open.is_empty()
2526                                    && !p.close.is_empty()
2527                                    && p.open != p.close
2528                                    && self.text_before_matches(off, p.open.as_ref())
2529                                    && self.text_after_matches(off, p.close.as_ref())
2530                            });
2531                            if is_pair {
2532                                // Base indent: leading whitespace only.
2533                                let line_end_affinity = self.line_end_affinity_at(off);
2534                                let line_start = self.start_of_line_at(off, line_end_affinity);
2535                                let mut indent = String::new();
2536                                for c in self.text.slice(line_start..).chars() {
2537                                    if !c.is_whitespace() || c == '\n' || c == '\r' {
2538                                        break;
2539                                    }
2540                                    indent.push(c);
2541                                }
2542                                // Extra level only with smart indent enabled.
2543                                let mut inner = indent.clone();
2544                                if self.mode.is_smart_indent() {
2545                                    let tab = self.mode.tab_size();
2546                                    if tab.hard_tabs {
2547                                        inner.push('\t');
2548                                    } else {
2549                                        for _ in 0..tab.tab_size {
2550                                            inner.push(' ');
2551                                        }
2552                                    }
2553                                }
2554                                let new_line_text = format!("\n{inner}\n{indent}");
2555                                self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2556                                self.set_cursor_to(off + 1 + inner.len());
2557                                self.update_preferred_column();
2558                                let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2559                                self.undo_manager
2560                                    .record_selections(cursors.clone(), cursors);
2561                                self.pause_blink_cursor(cx);
2562                                split = true;
2563                            }
2564                        }
2565                    }
2566                }
2567                if !split {
2568                    // Get current line indent
2569                    let indent = if self.is_code_editor() {
2570                        self.indent_of_next_line()
2571                    } else {
2572                        "".to_string()
2573                    };
2574
2575                    // Add newline and indent
2576                    let new_line_text = format!("\n{}", indent);
2577                    self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2578                    self.pause_blink_cursor(cx);
2579                }
2580            }
2581        } else {
2582            // Single line input or submit-on-enter: just emit the event
2583            // (e.g.: in a dialog to confirm, or a chat textarea to send).
2584            self.undo_manager.break_transaction_coalescing();
2585            cx.propagate();
2586        }
2587
2588        cx.emit(InputEvent::PressEnter {
2589            secondary: action.secondary,
2590            shift: action.shift,
2591        });
2592    }
2593
2594    pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2595        self.replace_text("", window, cx);
2596        self.set_selection(0, 0);
2597        self.scroll_to(0, None, cx);
2598    }
2599
2600    pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2601        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2602            return;
2603        }
2604
2605        // Escape also dismisses a request whose popup has not arrived yet.
2606        M::hide_context_menu(self, cx);
2607
2608        // Collapse extra cursors back to the active one first.
2609        if !self.selections.is_single() {
2610            self.undo_manager.break_transaction_coalescing();
2611            self.selections.remove_all_but_active();
2612            cx.notify();
2613            return;
2614        }
2615
2616        // Clear inline completion on escape
2617        if M::has_inline_completion(self) {
2618            M::clear_inline_completion(self, cx);
2619            return; // Consume the escape, don't propagate
2620        }
2621        M::clear_inline_completion(self, cx);
2622
2623        // The handles and the edit menu are the topmost surface to dismiss.
2624        if self.touch_selection().is_some() {
2625            self.dismiss_touch_selection(cx);
2626            return;
2627        }
2628
2629        if self.ime_marked_range.is_some() {
2630            self.unmark_text(window, cx);
2631        }
2632
2633        // Android delivers its back button as escape, and back leaves a field's
2634        // text alone: it closes what is open or navigates.
2635        if self.clean_on_escape && !cfg!(target_os = "android") {
2636            return self.clean(window, cx);
2637        }
2638
2639        cx.propagate();
2640    }
2641
2642    /// Show the right-click context menu as a native OS menu.
2643    pub(crate) fn handle_right_click_menu(
2644        &mut self,
2645        position: Point<Pixels>,
2646        offset: usize,
2647        window: &mut Window,
2648        cx: &mut Context<Self>,
2649    ) {
2650        if self.disabled {
2651            return;
2652        }
2653        if crate::GlobalState::is_in_deferred_context(cx) {
2654            return;
2655        }
2656
2657        self.context_menu_offset = Some(offset);
2658        if !self.active_selection().contains(offset) {
2659            self.move_to(offset, None, cx);
2660        }
2661
2662        if self.is_code_editor() {
2663            M::on_hover_definition(self, offset, window, cx);
2664        }
2665
2666        if let Some(handler) = self.context_menu_handler.clone() {
2667            let capabilities = self.context_menu_capabilities();
2668            let input = cx.weak_entity();
2669            // The handler runs with the input released, so a custom builder can
2670            // read it (cursor, selection, text) to build its items.
2671            window.defer(cx, move |window, cx| {
2672                if input.upgrade().is_none() {
2673                    return;
2674                }
2675                let previous_focus = window.focused(cx);
2676                handler(NativeMenu::new(), capabilities, position, window, cx);
2677                // A drawn menu takes focus synchronously; native menus leave it
2678                // on the input. Capture it here rather than in the handler.
2679                input
2680                    .update(cx, |this, cx| {
2681                        if window.focused(cx) == previous_focus
2682                            && !this.focus_handle.is_focused(window)
2683                            && this.has_selection_focus(window, cx)
2684                        {
2685                            // A custom handler can reuse an already-focused popup.
2686                            return;
2687                        }
2688                        let menu_focus = window.focused(cx).filter(|focus| {
2689                            Some(focus) != previous_focus.as_ref() && *focus != this.focus_handle
2690                        });
2691                        this.set_selection_focus(menu_focus, cx);
2692                    })
2693                    .ok();
2694            });
2695        }
2696    }
2697
2698    pub(super) fn add_cursor_above(
2699        &mut self,
2700        _: &AddCursorAbove,
2701        _: &mut Window,
2702        cx: &mut Context<Self>,
2703    ) {
2704        self.add_cursor_vertical(-1, cx);
2705    }
2706
2707    pub(super) fn add_cursor_below(
2708        &mut self,
2709        _: &AddCursorBelow,
2710        _: &mut Window,
2711        cx: &mut Context<Self>,
2712    ) {
2713        self.add_cursor_vertical(1, cx);
2714    }
2715
2716    /// Add a new cursor one display line above (`move_lines < 0`) or below each
2717    /// existing cursor, preserving the column. Cursors that would not move (at
2718    /// the first/last display row) or that would duplicate an existing cursor
2719    /// are skipped.
2720    fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2721        if !self.is_multi_line() {
2722            return;
2723        }
2724
2725        self.pause_blink_cursor(cx);
2726        // Changing the cursor set ends the editing gesture that came before it.
2727        self.undo_manager.break_transaction_coalescing();
2728
2729        let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2730            .selections
2731            .iter()
2732            .map(|sel| {
2733                (
2734                    sel.cursor_offset(),
2735                    sel.column_anchor,
2736                    self.line_end_affinity_for(sel),
2737                )
2738            })
2739            .collect();
2740        let mut offsets: std::collections::HashSet<usize> =
2741            sources.iter().map(|(offset, _, _)| *offset).collect();
2742
2743        let mut newest: Option<usize> = None;
2744        for (offset, anchor, line_end_affinity) in sources {
2745            let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2746            let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2747            if target == offset || offsets.contains(&target) {
2748                continue;
2749            }
2750            offsets.insert(target);
2751            let id = self.selections.generate_id();
2752            let mut cursor = CursorSelection::new(id, target, target);
2753            cursor.column_anchor = anchor;
2754            self.selections.add(cursor);
2755            newest = Some(target);
2756        }
2757
2758        if let Some(newest) = newest {
2759            self.scroll_to(newest, None, cx);
2760        }
2761        cx.notify();
2762    }
2763
2764    /// Add an additional collapsed cursor at `offset`.
2765    ///
2766    /// Rejected when `offset` lands inside an existing selection or exactly on
2767    /// an existing cursor.
2768    pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2769        if !self.is_multi_line() {
2770            return;
2771        }
2772
2773        for sel in self.selections.iter() {
2774            if sel.contains(offset) {
2775                return;
2776            }
2777            if sel.is_collapsed() && sel.cursor_offset() == offset {
2778                return;
2779            }
2780        }
2781
2782        self.undo_manager.break_transaction_coalescing();
2783        let id = self.selections.generate_id();
2784        let mut selection = CursorSelection::new(id, offset, offset);
2785        selection.column_anchor = self.preferred_column_for(offset);
2786        self.selections.add(selection);
2787        cx.notify();
2788    }
2789
2790    /// Build a columnar (block) selection spanning the rows between the two
2791    /// points, one selection per display row at the same column span.
2792    ///
2793    /// The span keeps the columns the pointer sat past the end of a short row, so a row
2794    /// that runs out of text does not narrow the block for the rows that do reach that
2795    /// far. Each row is then clipped to its own end, selecting as much of the span as it
2796    /// actually has.
2797    pub(super) fn build_columnar_selection(
2798        &mut self,
2799        start: ColumnarPoint,
2800        end: ColumnarPoint,
2801        cx: &mut Context<Self>,
2802    ) {
2803        if !self.is_multi_line() {
2804            return;
2805        }
2806
2807        self.undo_manager.break_transaction_coalescing();
2808
2809        let (start_row, start_col) = self.columnar_row_column(start);
2810        let (end_row, end_col) = self.columnar_row_column(end);
2811        let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2812        let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2813
2814        let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2815        for row in start_row..=end_row {
2816            let sel_start = self
2817                .display_map
2818                .display_row_column_to_offset(row, start_col);
2819            let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2820            let id = self.selections.generate_id();
2821            let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2822            let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2823            new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2824        }
2825
2826        self.selections.replace_all(new_selections);
2827        cx.notify();
2828    }
2829
2830    /// Resolve a columnar point to the display row it is on and the column it reaches,
2831    /// counting the columns beyond the row's end so a short row keeps the full span.
2832    fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2833        let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2834        let row = self
2835            .display_map
2836            .wrap_row_to_display_row(display_point.row)
2837            .unwrap_or_else(|| {
2838                self.display_map
2839                    .nearest_visible_display_row(display_point.row)
2840            });
2841
2842        (row, display_point.column + point.columns_past_line_end)
2843    }
2844
2845    pub(super) fn on_mouse_down(
2846        &mut self,
2847        event: &MouseDownEvent,
2848        window: &mut Window,
2849        cx: &mut Context<Self>,
2850    ) {
2851        // A token that consumed the press (a double click selecting it) must
2852        // not also place the caret.
2853        if window.default_prevented() {
2854            return;
2855        }
2856        // A tap asks for the virtual keyboard. Focus alone does not when it
2857        // moves from another input, or stays here, after the user hid it.
2858        if event.button == MouseButton::Left
2859            && crate::GlobalState::is_touch_press(cx)
2860            && !self.disabled
2861            && !self.readonly
2862        {
2863            window.request_virtual_keyboard();
2864        }
2865        self.undo_manager.break_transaction_coalescing();
2866        // Treat every press like a cursor move: take focus now rather than
2867        // after GPUI's focus observer runs, show the caret at once and restart
2868        // the idle delay, whatever phase the blink was in.
2869        if !self.disabled {
2870            self.focus(window, cx);
2871            self.pause_blink_cursor(cx);
2872        }
2873        // Input has its own text selection; suppress the window-level text
2874        // selection (Root) so it does not start a drag from here.
2875        crate::global_state::GlobalState::suppress_text_selection(cx);
2876
2877        // Clear inline completion on any mouse interaction
2878        M::clear_inline_completion(self, cx);
2879        // A tap on the touch selection asks for its menu back. Any other press
2880        // places the caret or starts a new drag, and the handles and the menu
2881        // no longer belong to what is selected.
2882        if event.button == MouseButton::Left
2883            && event.click_count == 1
2884            && self.reopen_edit_menu_at(event.position, cx)
2885        {
2886            return;
2887        }
2888        self.dismiss_touch_selection(cx);
2889
2890        // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2891        // Clear the marked range.
2892        if let Some(ime_marked_range) = &self.ime_marked_range {
2893            if ime_marked_range.len() == 0 {
2894                self.ime_marked_range = None;
2895            }
2896        }
2897
2898        self.selecting = true;
2899        let (offset, line_end_affinity, columns_past_line_end) =
2900            self.resolve_mouse_position(event.position);
2901
2902        if M::on_click(self, event, offset, window, cx) {
2903            return;
2904        }
2905
2906        // Triple click to select line
2907        if event.button == MouseButton::Left && event.click_count >= 3 {
2908            self.select_line(offset, window, cx);
2909            return;
2910        }
2911
2912        // Double click to select word
2913        if event.button == MouseButton::Left && event.click_count == 2 {
2914            self.select_word(offset, window, cx);
2915            // A double tap is touch's other way to select a word, and it
2916            // gets the handles and the menu like a long press does.
2917            if crate::GlobalState::is_touch_press(cx) {
2918                self.keep_touch_selection(cx);
2919            }
2920            return;
2921        }
2922
2923        // Show Mouse context menu
2924        if event.button == MouseButton::Right {
2925            if self.enable_context_menu {
2926                if !self.active_selection().contains(offset) {
2927                    self.move_to(offset, None, cx);
2928                }
2929                self.pending_context_menu = Some((event.position, offset));
2930            }
2931            return;
2932        }
2933
2934        // Multi-cursor placement, multi-line only.
2935        if self.is_multi_line() && event.button == MouseButton::Left {
2936            if event.modifiers.alt
2937                && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2938            {
2939                // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2940                // Mark selecting so the drag handler extends the block.
2941                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2942                self.selecting = true;
2943                self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2944                return;
2945            } else if event.modifiers.alt {
2946                self.add_cursor_at(offset, cx);
2947                // Keep click-to-add behavior, but use this press as the block
2948                // anchor if the user continues dragging with the left button.
2949                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2950                return;
2951            }
2952        }
2953
2954        if event.modifiers.shift {
2955            self.select_to_with_affinity(offset, line_end_affinity, cx);
2956        } else {
2957            self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2958        }
2959    }
2960
2961    pub(super) fn on_mouse_up(
2962        &mut self,
2963        event: &MouseUpEvent,
2964        window: &mut Window,
2965        cx: &mut Context<Self>,
2966    ) {
2967        if event.button == MouseButton::Right {
2968            if let Some((position, offset)) = self.pending_context_menu.take() {
2969                self.handle_right_click_menu(position, offset, window, cx);
2970            }
2971        }
2972        if self.active_selection().is_empty() {
2973            self.active_selection_mut().reversed = false;
2974        }
2975        self.selecting = false;
2976        self.selected_word_range = None;
2977        self.column_select_start = None;
2978        self.auto_scroll.stop();
2979    }
2980
2981    pub(super) fn on_mouse_move(
2982        &mut self,
2983        event: &MouseMoveEvent,
2984        window: &mut Window,
2985        cx: &mut Context<Self>,
2986    ) {
2987        // `last_bounds` is moved by the scroll offset; `input_bounds` is the visible area.
2988        let within_bounds = self.input_bounds.contains(&event.position);
2989
2990        if !within_bounds {
2991            // Clear hover when mouse leaves the input
2992            M::clear_hover_state(self, cx);
2993            return;
2994        }
2995
2996        // Show diagnostic popover on mouse move
2997        let (offset, _) = self.index_for_mouse_position(event.position);
2998        M::on_mouse_move(self, offset, event, window, cx);
2999
3000        if self.is_code_editor() {
3001            // Keep the current popover while the pointer stays on the same
3002            // diagnostic, so moving over a squiggle neither repaints nor
3003            // rebuilds the popover.
3004            match self
3005                .mode
3006                .diagnostics()
3007                .and_then(|set| set.for_offset(offset))
3008            {
3009                Some(diagnostic) => {
3010                    if self.diagnostic_popover.as_deref() != Some(diagnostic) {
3011                        self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
3012                        cx.notify();
3013                    }
3014                }
3015                None => {
3016                    if self.diagnostic_popover.take().is_some() {
3017                        cx.notify();
3018                    }
3019                }
3020            }
3021        }
3022    }
3023
3024    pub(super) fn on_scroll_wheel(
3025        &mut self,
3026        event: &ScrollEvent,
3027        window: &mut Window,
3028        cx: &mut Context<Self>,
3029    ) {
3030        let line_height = self
3031            .last_layout
3032            .as_ref()
3033            .map(|layout| layout.line_height)
3034            .unwrap_or(window.line_height());
3035        let delta = event.delta.pixel_delta(line_height);
3036
3037        let old_offset = self.scroll_handle.offset();
3038        let old_y_f64 = self.effective_scroll_y_f64();
3039        let precise = matches!(event.delta, gpui::ScrollDelta::Pixels(_));
3040        if !precise || !self.scroll_bounce || cx.reduce_motion() || !self.overflows_vertically() {
3041            let displaced = self.overscroll.offset() != 0.;
3042            self.overscroll.reset();
3043            if displaced {
3044                cx.notify();
3045            }
3046        }
3047        let bounces = self.scroll_bounce
3048            && precise
3049            && !cx.reduce_motion()
3050            && delta.y.abs() >= delta.x.abs()
3051            && self.overflows_vertically();
3052        if bounces {
3053            let mut overscroll = std::mem::take(&mut self.overscroll);
3054            let stretched = overscroll.packet(
3055                delta.y.as_f32(),
3056                event.touch_phase,
3057                self.input_bounds.size.height.as_f32(),
3058                cx.background_executor().now(),
3059                |dy| {
3060                    let before_x = self.scroll_handle.offset().x;
3061                    let before_y = self.effective_scroll_y_f64();
3062                    self.update_scroll_offset_parts(
3063                        before_x + delta.x,
3064                        before_y + f64::from(dy),
3065                        cx,
3066                    );
3067                    (self.scroll_y_f64 - before_y) as f32
3068                },
3069            );
3070            self.overscroll = overscroll;
3071            if stretched {
3072                cx.notify();
3073            }
3074        } else {
3075            self.overscroll
3076                .touch_phase(event.touch_phase, cx.background_executor().now());
3077            // Axis drift must not drop the end of a vertical drag.
3078            if matches!(
3079                event.touch_phase,
3080                gpui::TouchPhase::Ended | gpui::TouchPhase::Cancelled
3081            ) && self.overscroll.offset() != 0.
3082            {
3083                self.overscroll.packet(
3084                    0.,
3085                    event.touch_phase,
3086                    self.input_bounds.size.height.as_f32(),
3087                    cx.background_executor().now(),
3088                    |_| 0.,
3089                );
3090                cx.notify();
3091            }
3092            self.update_scroll_offset_parts(
3093                old_offset.x + delta.x,
3094                old_y_f64 + f64::from(f32::from(delta.y)),
3095                cx,
3096            );
3097        }
3098
3099        // Text that has room to scroll keeps a scroll over it even where the
3100        // text ends, so reaching the end does not scroll the region around the
3101        // input; text that fits leaves the scroll to that region.
3102        if self.scroll_handle.offset() != old_offset
3103            || (self.scroll_y_f64 - old_y_f64).abs() > f64::EPSILON
3104            || self.overflows_along(delta)
3105        {
3106            cx.stop_propagation();
3107        }
3108
3109        if self.diagnostic_popover.take().is_some() {
3110            cx.notify();
3111        }
3112        // The handles follow the text; the menu would sit over whatever
3113        // scrolls underneath it, so it steps aside until the finger lifts.
3114        self.edit_menu_on_scroll(event.touch_phase, cx);
3115    }
3116
3117    /// Whether the text takes a wheel event moving by `delta` from the
3118    /// scroll areas around it: it has room to scroll along the axis the
3119    /// event mostly moves on. Unlike [`Self::overflows_along`], an event that
3120    /// moves on neither axis, such as a gesture's start or end, goes to text
3121    /// that can scroll vertically.
3122    pub(super) fn takes_scroll(&self, delta: Point<Pixels>) -> bool {
3123        if delta.y.abs() >= delta.x.abs() {
3124            self.overflows_vertically()
3125        } else {
3126            self.scroll_size.width > self.input_bounds.size.width
3127        }
3128    }
3129
3130    /// Whether the text has room to scroll along the axis `delta` mostly
3131    /// moves on. A trackpad swipe drifts a little off its axis, so the drift
3132    /// alone does not claim the scroll.
3133    fn overflows_along(&self, delta: Point<Pixels>) -> bool {
3134        if delta.y.abs() >= delta.x.abs() {
3135            delta.y != px(0.) && self.overflows_vertically()
3136        } else {
3137            self.scroll_size.width > self.input_bounds.size.width
3138        }
3139    }
3140
3141    /// Whether multi-line text is taller than the input.
3142    fn overflows_vertically(&self) -> bool {
3143        self.is_multi_line()
3144            && self.content_height_f64() > f64::from(f32::from(self.input_bounds.size.height))
3145    }
3146
3147    pub(super) fn effective_scroll_y_f64(&self) -> f64 {
3148        let handle_y = self.scroll_handle.offset().y;
3149        if handle_y != self.last_synced_handle_y.get() {
3150            f64::from(f32::from(handle_y))
3151        } else {
3152            self.scroll_y_f64
3153        }
3154    }
3155
3156    pub(super) fn update_scroll_offset_parts(
3157        &mut self,
3158        mut x: Pixels,
3159        mut y_f64: f64,
3160        cx: &mut Context<Self>,
3161    ) {
3162        let content_height_f64 = self.content_height_f64();
3163        let viewport_height_f64 = f64::from(f32::from(self.input_bounds.size.height));
3164        y_f64 = if self.is_single_line() {
3165            0.0
3166        } else {
3167            super::element::clamp_vertical_scroll_offset_f64(
3168                y_f64,
3169                content_height_f64,
3170                viewport_height_f64,
3171            )
3172        };
3173        x = clamp_horizontal_scroll_offset(
3174            x,
3175            self.scroll_size.width,
3176            self.input_bounds.size.width,
3177            self.text_align,
3178        );
3179        let handle_y = px(y_f64 as f32);
3180        let prev_handle = self.scroll_handle.offset();
3181        let y_changed = (self.scroll_y_f64 - y_f64).abs() > f64::EPSILON
3182            || self.last_synced_handle_y.get() != handle_y
3183            || prev_handle.y != handle_y;
3184        self.scroll_y_f64 = y_f64;
3185        self.last_synced_handle_y.set(handle_y);
3186        let next_handle = point(x, handle_y);
3187        if prev_handle != next_handle || y_changed {
3188            if prev_handle != next_handle {
3189                self.scroll_handle.set_offset(next_handle);
3190            }
3191            cx.notify();
3192        }
3193    }
3194
3195    #[allow(dead_code)]
3196    pub(super) fn update_scroll_offset(
3197        &mut self,
3198        offset: Option<Point<Pixels>>,
3199        cx: &mut Context<Self>,
3200    ) {
3201        let (x, y_f64) = match offset {
3202            Some(offset) => (offset.x, f64::from(f32::from(offset.y))),
3203            None => (self.scroll_handle.offset().x, self.effective_scroll_y_f64()),
3204        };
3205        self.update_scroll_offset_parts(x, y_f64, cx);
3206    }
3207
3208    /// Scroll to make the given offset visible.
3209    ///
3210    /// If `direction` is Some, will keep edges at the same side.
3211    pub(crate) fn scroll_to(
3212        &mut self,
3213        offset: usize,
3214        direction: Option<MoveDirection>,
3215        cx: &mut Context<Self>,
3216    ) {
3217        let padding = if direction.is_some() {
3218            ScrollPadding::SurroundingLines
3219        } else {
3220            ScrollPadding::Minimal
3221        };
3222        self.scroll_to_with_padding(offset, direction, padding, cx);
3223    }
3224
3225    /// Reveal an offset with independently chosen direction restriction and padding.
3226    /// Search uses surrounding lines without restricting movement to match order.
3227    pub(crate) fn scroll_to_with_padding(
3228        &mut self,
3229        offset: usize,
3230        direction: Option<MoveDirection>,
3231        padding: ScrollPadding,
3232        cx: &mut Context<Self>,
3233    ) {
3234        let Some(last_layout) = self.last_layout.as_ref() else {
3235            return;
3236        };
3237        let Some(bounds) = self.last_bounds.as_ref() else {
3238            return;
3239        };
3240
3241        let mut scroll_offset = self.scroll_handle.offset();
3242        let was_y_f64 = self.effective_scroll_y_f64();
3243        let line_height = last_layout.line_height;
3244
3245        let point = self.text.offset_to_point(offset);
3246
3247        let row = point.row;
3248
3249        // Resolve the wrapped row even when the target is outside the last layout.
3250        let display_row = self
3251            .display_map
3252            .offset_to_display_row(offset, self.line_end_affinity_at(offset));
3253        let line_height_f64 = f64::from(f32::from(line_height));
3254        let row_offset_y_f64 = line_height_f64 * (display_row as f64);
3255
3256        // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
3257        // in layout_cursors, so shifting the text here would cause a first-click visual jump.
3258        let safety_margin = match last_layout.text_align {
3259            TextAlign::Left => RIGHT_MARGIN,
3260            TextAlign::Right => px(0.),
3261            TextAlign::Center => CURSOR_WIDTH,
3262        };
3263        if let Some(vi) = last_layout
3264            .visible_buffer_lines
3265            .iter()
3266            .position(|&line| line == row)
3267        {
3268            let line = &last_layout.lines[vi];
3269            let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
3270            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
3271                let bounds_width = bounds.size.width - last_layout.line_number_width;
3272                let col_offset_x = pos.x;
3273                if col_offset_x - safety_margin < -scroll_offset.x {
3274                    // If the position is out of the visible area, scroll to make it visible
3275                    scroll_offset.x = -col_offset_x + safety_margin;
3276                } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
3277                    scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
3278                }
3279            }
3280        }
3281
3282        // Scroll the row into view. Use the same edge clearance helper as
3283        // `TextElement::layout_cursors` so both scroll-into-view paths agree
3284        // (a mismatch flickered on `Down` at end-of-buffer with a small
3285        // `cursor_surrounding_lines` override).
3286        let edge_height =
3287            if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
3288                super::element::cursor_surrounding_padding(
3289                    self.mode.is_auto_grow(),
3290                    self.cursor_surrounding_lines,
3291                    super::element::viewport_visible_lines(bounds.size.height, line_height),
3292                    line_height,
3293                )
3294            } else {
3295                px(0.)
3296            };
3297        let mut target_y_f64 = super::element::reveal_row_f64(
3298            was_y_f64,
3299            row_offset_y_f64,
3300            line_height_f64,
3301            f64::from(f32::from(bounds.size.height)),
3302            f64::from(f32::from(edge_height)),
3303        );
3304
3305        // Avoid necessary scroll, when it was already in the correct position.
3306        if direction == Some(MoveDirection::Up) {
3307            target_y_f64 = target_y_f64.max(was_y_f64);
3308        } else if direction == Some(MoveDirection::Down) {
3309            target_y_f64 = target_y_f64.min(was_y_f64);
3310        }
3311
3312        // Clamp the deferred target into the same safe range that
3313        // `update_scroll_offset` enforces on persist, so paint never shows an
3314        // over-scrolled frame before the post-paint clamp pulls it back.
3315        target_y_f64 = super::element::clamp_vertical_scroll_offset_f64(
3316            target_y_f64,
3317            self.content_height_f64(),
3318            f64::from(f32::from(self.input_bounds.size.height)),
3319        );
3320        scroll_offset.x = scroll_offset.x.min(px(0.));
3321        scroll_offset.y = px(target_y_f64 as f32);
3322        self.deferred_scroll_offset = Some(scroll_offset);
3323        self.deferred_scroll_y_f64 = Some(target_y_f64);
3324        cx.notify();
3325    }
3326
3327    pub(super) fn show_character_palette(
3328        &mut self,
3329        _: &ShowCharacterPalette,
3330        window: &mut Window,
3331        _: &mut Context<Self>,
3332    ) {
3333        window.show_character_palette();
3334    }
3335
3336    /// The text of every non-empty selection, in document order.
3337    fn selected_texts(&self) -> Vec<String> {
3338        let mut selections: Vec<CursorSelection> = self
3339            .selections
3340            .iter()
3341            .copied()
3342            .filter(|sel| !sel.is_empty())
3343            .collect();
3344        selections.sort_by_key(|sel| sel.start);
3345        selections
3346            .iter()
3347            .map(|sel| self.text.slice(*sel).to_string())
3348            .collect()
3349    }
3350
3351    pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
3352        if self.selections.iter().all(|sel| sel.is_empty()) {
3353            // Nothing selected here: let Root copy the window's text selection.
3354            cx.propagate();
3355            return;
3356        }
3357        if !self.is_copyable() {
3358            return;
3359        }
3360
3361        let texts = self.selected_texts();
3362
3363        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3364    }
3365
3366    pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
3367        if !self.is_copyable() {
3368            return;
3369        }
3370
3371        let texts = self.selected_texts();
3372
3373        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3374
3375        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3376        self.replace_text_in_range_silent(None, "", window, cx);
3377    }
3378
3379    pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
3380        if !self.is_editable() {
3381            return;
3382        }
3383        if let Some(clipboard) = cx.read_from_clipboard() {
3384            self.insert_clipboard(clipboard, window, cx);
3385            return;
3386        }
3387        // The synchronous read is empty on platforms whose clipboard is
3388        // asynchronous and permission-gated (the web), so fall back to the
3389        // real read. It has to start here, still inside the user activation
3390        // that dispatched `Paste`, or the browser refuses the read.
3391        let read = cx.read_from_clipboard_async();
3392        let target = self.paste_target();
3393        cx.spawn_in(window, async move |this, cx| match read.await {
3394            Ok(Some(clipboard)) => {
3395                this.update_in(cx, |this, window, cx| {
3396                    // The read can sit behind a permission prompt for as
3397                    // long as the user likes. If they edited, moved the
3398                    // caret or left the input meanwhile, the paste would
3399                    // land where they no longer mean it to; drop it, as the
3400                    // browser's own paste event only reaches the focused
3401                    // input too.
3402                    if this.is_editable()
3403                        && this.focus_handle.is_focused(window)
3404                        && this.paste_target() == target
3405                    {
3406                        this.insert_clipboard(clipboard, window, cx);
3407                    }
3408                })
3409                .ok();
3410            }
3411            Ok(None) => {}
3412            Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
3413        })
3414        .detach();
3415    }
3416
3417    /// Where a paste would go right now: the document as edited so far and
3418    /// the selections it would replace. Two equal targets mean an edit made
3419    /// for one still applies to the other.
3420    fn paste_target(&self) -> PasteTarget {
3421        PasteTarget {
3422            document_revision: self.document_revision,
3423            selections: self.selections.iter().copied().collect(),
3424        }
3425    }
3426
3427    /// Inserts the clipboard text the way `Paste` does: one atomic edit,
3428    /// newlines dropped on a single-line input, one line per selection when
3429    /// the counts match on a multi-line one. A clipboard without text (an
3430    /// image, say) is left alone rather than replacing the selection with
3431    /// nothing.
3432    fn insert_clipboard(
3433        &mut self,
3434        clipboard: ClipboardItem,
3435        window: &mut Window,
3436        cx: &mut Context<Self>,
3437    ) {
3438        let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
3439            return;
3440        };
3441        // A paste is one atomic edit, never part of a typing run.
3442        self.undo_manager.set_pending_intent(EditIntent::Atomic);
3443
3444        if !self.is_multi_line() {
3445            new_text = new_text.replace('\n', "");
3446            self.replace_text_in_range_silent(None, &new_text, window, cx);
3447            return;
3448        }
3449
3450        // Distribute one clipboard line per selection when the counts match.
3451        // Otherwise insert the whole clipboard text at each cursor.
3452        if !self.selections.is_single() {
3453            self.selections.merge_overlapping();
3454        }
3455        let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
3456        let count = self.selections.len();
3457        if count > 1 && lines.len() == count {
3458            let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3459            selections.sort_by_key(|sel| sel.start);
3460            let edits: Vec<(Range<usize>, String)> = selections
3461                .iter()
3462                .zip(lines)
3463                .map(|(sel, line)| (sel.start..sel.end, line))
3464                .collect();
3465            self.replace_text_in_ranges(&edits, window, cx);
3466        } else {
3467            self.replace_text_in_range_silent(None, &new_text, window, cx);
3468        }
3469        self.scroll_to(self.cursor(), None, cx);
3470    }
3471
3472    /// The intent of a batch the caller did not label: inserting text at
3473    /// collapsed cursors is typing, anything else stands on its own.
3474    fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
3475        if !new_text.is_empty()
3476            && !new_text.contains(['\n', '\r'])
3477            && edits.iter().all(|(range, _)| range.is_empty())
3478        {
3479            EditIntent::Typing
3480        } else {
3481            EditIntent::Atomic
3482        }
3483    }
3484
3485    /// Where a cursor stood before an edit made with this intent.
3486    ///
3487    /// Backspace and forward delete expand a collapsed cursor over the text
3488    /// they are about to remove, so the recorded cursor has to collapse back to
3489    /// the side it came from for undo to restore it where the user left it.
3490    fn collapse_for_intent(
3491        intent: EditIntent,
3492        mut selection: CursorSelection,
3493        range: &Range<usize>,
3494    ) -> CursorSelection {
3495        match intent {
3496            EditIntent::Backspace => selection.place_at(range.end, None),
3497            EditIntent::DeleteForward => selection.place_at(range.start, None),
3498            EditIntent::Typing | EditIntent::Atomic => {}
3499        }
3500        selection
3501    }
3502
3503    /// Whether an edit rewrites the character before a collapsed cursor, as the
3504    /// macOS Korean IME does on each keystroke instead of marking text.
3505    fn rewrites_typed_char(
3506        &self,
3507        selection: CursorSelection,
3508        range: &Range<usize>,
3509        old_text: &str,
3510        new_text: &str,
3511    ) -> bool {
3512        !self.silent_replace_text
3513            && selection.is_collapsed()
3514            && selection.cursor_offset() == range.end
3515            && old_text.chars().count() == 1
3516            && !old_text.contains(['\n', '\r'])
3517            && !new_text.contains(['\n', '\r'])
3518    }
3519
3520    fn push_history(
3521        &mut self,
3522        text: &Rope,
3523        range: &Range<usize>,
3524        new_text: &str,
3525        requested_intent: Option<EditIntent>,
3526        selection_before: CursorSelection,
3527        selection_after: Option<CursorSelection>,
3528    ) -> bool {
3529        self.document_revision = self.document_revision.wrapping_add(1);
3530        let token_delta = self.edit_tokens(range, new_text.len());
3531        if self.undo_manager.is_ignoring() {
3532            return false;
3533        }
3534
3535        let range =
3536            text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
3537        let old_text = text.slice(range.clone()).to_string();
3538        let new_range = range.start..range.start + new_text.len();
3539
3540        let intent = requested_intent.unwrap_or_else(|| {
3541            if range.is_empty()
3542                && old_text.is_empty()
3543                && !new_text.is_empty()
3544                && !new_text.contains(['\n', '\r'])
3545                || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
3546            {
3547                EditIntent::Typing
3548            } else {
3549                EditIntent::Atomic
3550            }
3551        });
3552
3553        let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
3554        let selection_after =
3555            selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
3556
3557        let open_transaction = self.undo_manager.has_open_transaction();
3558        let mut change = Change::new(range, &old_text, new_range, new_text);
3559        change.token_delta = token_delta;
3560        let recorded = self.undo_manager.record_transaction(change, intent);
3561        // A batch records its own cursor sets. This covers a change that is a
3562        // transaction on its own.
3563        if recorded && !open_transaction {
3564            self.undo_manager
3565                .record_selections(vec![selection_before], vec![selection_after]);
3566        }
3567        recorded
3568    }
3569
3570    pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
3571        self.replay_history(true, window, cx);
3572    }
3573
3574    pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
3575        self.replay_history(false, window, cx);
3576    }
3577
3578    fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
3579        if !self.is_editable() {
3580            return;
3581        }
3582        let replay = if undo {
3583            self.undo_manager.undo()
3584        } else {
3585            self.undo_manager.redo()
3586        };
3587        let Some(replay) = replay else {
3588            return;
3589        };
3590        let token_aware = self.inline_tokens.is_some()
3591            || replay
3592                .changes
3593                .iter()
3594                .any(|change| change.token_delta.is_some());
3595        let emit_events = self.emit_events;
3596        if token_aware {
3597            self.emit_events = false;
3598            self.last_input_edits.clear();
3599        }
3600        self.replaying_history = token_aware;
3601        self.undo_manager.set_ignoring(true);
3602        for change in &replay.changes {
3603            let (range, text) = if undo {
3604                (change.new_range.into(), &change.old_text)
3605            } else {
3606                (change.old_range.into(), &change.new_text)
3607            };
3608            let range_utf16 = self.range_to_utf16(&range);
3609            self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
3610            self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
3611        }
3612        self.restore_selections(replay.selections);
3613        self.mode
3614            .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
3615        if token_aware {
3616            // Token replay bypasses IME normalization; a stale marked range
3617            // would otherwise describe text that no longer exists.
3618            self.ime_marked_range = None;
3619        }
3620        self.undo_manager.set_ignoring(false);
3621        self.replaying_history = false;
3622        self.emit_events = emit_events;
3623        if token_aware {
3624            if emit_events {
3625                self.emit_change(cx);
3626            } else {
3627                self.last_input_edits.clear();
3628            }
3629        }
3630        cx.notify();
3631    }
3632
3633    /// Restore a set of selections captured in a transaction, clamping offsets
3634    /// to the current text length and out of tokens. `None` leaves the current
3635    /// selections as the replay left them.
3636    fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
3637        let Some(selections) = selections else {
3638            return;
3639        };
3640
3641        let len = self.text.len();
3642        let restored: Vec<CursorSelection> = selections
3643            .into_iter()
3644            .map(|mut sel| {
3645                let (start, end) = (sel.start.min(len), sel.end.min(len));
3646                let start_bias = if start == end {
3647                    Bias::Right
3648                } else {
3649                    Bias::Left
3650                };
3651                sel.start = self.token_boundary(start, start_bias);
3652                sel.end = self.token_boundary(end, Bias::Right);
3653                sel
3654            })
3655            .collect();
3656        self.selections.replace_all(restored);
3657        self.selections.merge_overlapping();
3658    }
3659
3660    /// Get byte offset of the text under the pointer at the right-click that last opened
3661    /// the context menu.
3662    ///
3663    /// A right-click inside the selection keeps the selection and the cursor, so a custom
3664    /// context menu reads this to find the word under the pointer. The offset is the
3665    /// UTF-8 offset.
3666    pub fn context_menu_offset(&self) -> Option<usize> {
3667        self.context_menu_offset
3668    }
3669
3670    /// Get byte offset of the cursor.
3671    ///
3672    /// The offset is the UTF-8 offset.
3673    pub fn cursor(&self) -> usize {
3674        if let Some(ime_marked_range) = &self.ime_marked_range {
3675            return ime_marked_range.end;
3676        }
3677
3678        self.selections.active().cursor_offset()
3679    }
3680
3681    /// Returns the active selection.
3682    pub(super) fn active_selection(&self) -> &CursorSelection {
3683        self.selections.active()
3684    }
3685
3686    /// Returns a mutable reference to the active selection.
3687    pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
3688        self.selections.active_mut()
3689    }
3690
3691    /// Sets the active selection to the given range, keeping its `reversed`
3692    /// and `column_anchor` state untouched.
3693    pub(super) fn set_selection(&mut self, start: usize, end: usize) {
3694        let range = self.normalize_token_range(start..end);
3695        let (start, end) = (range.start, range.end);
3696        let active = self.active_selection_mut();
3697        active.start = start;
3698        active.end = end;
3699    }
3700
3701    /// Collapses the active selection to a cursor at the given offset,
3702    /// clearing `reversed`.
3703    pub(super) fn set_cursor_to(&mut self, offset: usize) {
3704        let offset = self.token_boundary(offset, Bias::Right);
3705        let active = self.active_selection_mut();
3706        active.start = offset;
3707        active.end = offset;
3708        active.reversed = false;
3709    }
3710
3711    /// Visible row range in the last laid-out viewport, `None` before first layout.
3712    pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3713        self.last_layout.as_ref().map(|l| l.visible_range.clone())
3714    }
3715
3716    /// Current scroll offset of the editor viewport.
3717    pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
3718        let mut offset = self.scroll_handle.offset();
3719        offset.y = px(self.effective_scroll_y_f64() as f32);
3720        offset
3721    }
3722
3723    /// Set scroll offset of the editor viewport.
3724    ///
3725    /// The offset will be clamped to the valid range, and applied after the next layout.
3726    pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
3727        self.deferred_scroll_offset = Some(offset);
3728        self.deferred_scroll_y_f64 = Some(f64::from(f32::from(offset.y)));
3729        cx.notify();
3730    }
3731
3732    /// Authoritative vertical scroll offset in `f64` pixels (`<= 0.0`).
3733    pub fn scroll_y_f64(&self) -> f64 {
3734        self.effective_scroll_y_f64()
3735    }
3736
3737    /// Set vertical scroll offset in `f64` pixels without `f32` quantization.
3738    pub fn set_scroll_y_f64(&mut self, y: f64, cx: &mut Context<Self>) {
3739        let x = self
3740            .deferred_scroll_offset
3741            .map_or_else(|| self.scroll_handle.offset().x, |offset| offset.x);
3742        self.deferred_scroll_offset = Some(point(x, px(y as f32)));
3743        self.deferred_scroll_y_f64 = Some(y);
3744        cx.notify();
3745    }
3746
3747    /// Scroll vertically by `delta_y` in `f64` pixels without `f32` quantization.
3748    pub fn scroll_by_y_f64(&mut self, delta_y: f64, cx: &mut Context<Self>) {
3749        let current_x = self.scroll_handle.offset().x;
3750        let next_y = self.effective_scroll_y_f64() + delta_y;
3751        self.update_scroll_offset_parts(current_x, next_y, cx);
3752    }
3753
3754    /// Authoritative vertical scrollable content height in `f64` pixels.
3755    pub fn content_height_f64(&self) -> f64 {
3756        if self.scroll_height_f64 > 0.0 {
3757            self.scroll_height_f64
3758        } else {
3759            f64::from(f32::from(self.scroll_size.height))
3760        }
3761    }
3762
3763    /// Laid-out line height; `None` before first layout.
3764    pub fn line_height(&self) -> Option<gpui::Pixels> {
3765        self.last_layout.as_ref().map(|l| l.line_height)
3766    }
3767
3768    /// Returns the active selection as a byte range into the text.
3769    ///
3770    /// With multiple cursors, this reads only the active selection.
3771    ///
3772    /// The range is empty (`start == end`) when no text is selected; in
3773    /// that case the offset equals `cursor()`. Byte offsets are measured
3774    /// in the underlying rope's byte units.
3775    pub fn selected_range(&self) -> std::ops::Range<usize> {
3776        (*self.selections.active()).into()
3777    }
3778
3779    /// Whether the active selection's caret is at the start of its range.
3780    ///
3781    /// Collapsed selections are not reversed. Use this with [`Self::selected_range`]
3782    /// and [`Self::set_selected_range_with_direction`] to restore a selection.
3783    pub fn is_selection_reversed(&self) -> bool {
3784        let selection = self.selections.active();
3785        !selection.is_empty() && selection.reversed
3786    }
3787
3788    pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3789        self.undo_manager.break_transaction_coalescing();
3790        self.selections.remove_all_but_active();
3791        self.set_selection(0, self.text.len());
3792        cx.notify();
3793    }
3794
3795    /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
3796    ///
3797    /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
3798    /// clipped to the preceding character boundary.
3799    pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3800        self.set_selected_range_with_direction(range, false, cx);
3801    }
3802
3803    /// Set the selected UTF-8 byte range and the active caret direction.
3804    ///
3805    /// With `reversed`, the caret is at the start and the anchor is at the end.
3806    /// Empty ranges collapse to a caret regardless of direction. Range clipping,
3807    /// token boundaries and removal of additional cursors follow
3808    /// [`Self::set_selected_range`].
3809    pub fn set_selected_range_with_direction(
3810        &mut self,
3811        range: Range<usize>,
3812        reversed: bool,
3813        cx: &mut Context<Self>,
3814    ) {
3815        let range = self.normalize_token_range(range);
3816        let end_bias = if range.start == range.end {
3817            Bias::Left
3818        } else {
3819            Bias::Right
3820        };
3821        let start = self.text.clip_offset(range.start, Bias::Left);
3822        let end = self.text.clip_offset(range.end, end_bias);
3823
3824        let (anchor, head) = if reversed { (end, start) } else { (start, end) };
3825        self.move_to(anchor, None, cx);
3826        self.active_selection_mut().reversed = false;
3827        self.selected_word_range = None;
3828        self.select_to(head, cx);
3829    }
3830
3831    /// Add `range` as an additional selection, keeping the existing ones —
3832    /// the programmatic equivalent of Alt-clicking another cursor into the
3833    /// text.
3834    ///
3835    /// The range is clipped to the text and expanded to character
3836    /// boundaries, like [`Self::set_selected_range`]. A range already
3837    /// covered by a selection adds nothing. Overlapping selections are merged.
3838    /// On a single-line input there is no second cursor to add, so the call
3839    /// replaces the selection instead.
3840    /// The view scrolls to the new selection.
3841    pub fn add_selection(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3842        if !self.is_multi_line() {
3843            self.set_selected_range(range, cx);
3844            return;
3845        }
3846
3847        let range = self.normalize_token_range(range);
3848        let end_bias = if range.start == range.end {
3849            Bias::Left
3850        } else {
3851            Bias::Right
3852        };
3853        let start = self.cursor_boundary(range.start, Bias::Left);
3854        // Match set_selected_range: expand UTF-8 boundaries first, then place
3855        // the selection endpoint without splitting a CRLF newline.
3856        let end = self.cursor_boundary(self.text.clip_offset(range.end, end_bias), Bias::Left);
3857
3858        for sel in self.selections.iter() {
3859            if sel.start <= start && end <= sel.end {
3860                return;
3861            }
3862        }
3863
3864        self.undo_manager.break_transaction_coalescing();
3865        self.selected_word_range = None;
3866        self.pause_blink_cursor(cx);
3867        M::hide_context_menu(self, cx);
3868        M::clear_inline_completion(self, cx);
3869        let id = self.selections.generate_id();
3870        let mut selection = CursorSelection::new(id, start, end);
3871        selection.column_anchor = self.preferred_column_for(end);
3872        self.selections.add(selection);
3873        self.selections.merge_overlapping();
3874        self.scroll_to(end, None, cx);
3875        cx.notify();
3876    }
3877
3878    /// Resolve a mouse position to a byte offset in the text.
3879    ///
3880    /// Also reports the caret's line-end affinity for that offset: `true` when the position
3881    /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
3882    /// end of that row rather than at the start of the next one. Callers that place or extend a
3883    /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
3884    /// caret one row below the pointer.
3885    pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3886        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3887        (offset, line_end_affinity)
3888    }
3889
3890    /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
3891    /// how many columns the pointer sits past the end of that row.
3892    ///
3893    /// Only a columnar selection needs the third value; everywhere else a position past
3894    /// the end of a row means the end of that row, and
3895    /// [`Self::index_for_mouse_position`] is the call to make.
3896    pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3897        // If the text is empty, always return 0
3898        if self.text.len() == 0 {
3899            return (0, false, 0);
3900        }
3901
3902        let (Some(bounds), Some(last_layout)) =
3903            (self.last_bounds.as_ref(), self.last_layout.as_ref())
3904        else {
3905            return (0, false, 0);
3906        };
3907
3908        let line_height = last_layout.line_height;
3909        let line_number_width = last_layout.line_number_width;
3910
3911        // TIP: About the IBeam cursor
3912        //
3913        // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3914
3915        // The position is relative to the bounds of the text input
3916        //
3917        // bounds.origin:
3918        //
3919        // - included the input padding.
3920        // - included the scroll offset.
3921        let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3922
3923        let mut row_offset: isize = 0;
3924        // Position relative to the last line walked, kept for a pointer that ends up
3925        // below every line.
3926        let mut last_line_pos = None;
3927
3928        // Traverse visible buffer lines (compact, no hidden entries)
3929        for (vi, (line_layout, _buffer_line)) in last_layout
3930            .lines
3931            .iter()
3932            .zip(last_layout.visible_buffer_lines.iter())
3933            .enumerate()
3934        {
3935            let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3936            let y_offset = last_layout.local_row_y(row_offset);
3937
3938            // Calculate line origin for this display row
3939            let line_origin = point(px(0.), y_offset);
3940            let pos = inner_position - line_origin;
3941
3942            // Return offset by use closest_index_for_x if is single line mode.
3943            if self.is_single_line() {
3944                let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3945                // A single line never wraps, so there is no boundary to disambiguate.
3946                return (
3947                    self.resolve_index(line_start_offset + local_index),
3948                    false,
3949                    0,
3950                );
3951            }
3952
3953            // Check if mouse is in this line's bounds
3954            if let Some((local_index, line_end_affinity)) =
3955                line_layout.closest_index_for_position(pos, last_layout)
3956            {
3957                return (
3958                    self.resolve_index(line_start_offset + local_index),
3959                    line_end_affinity,
3960                    line_layout.columns_past_line_end(pos, last_layout),
3961                );
3962            } else if pos.y < px(0.) {
3963                // Mouse is above this line, return start of this line
3964                return (self.resolve_index(line_start_offset), false, 0);
3965            }
3966
3967            row_offset += line_layout.wrapped_lines.len() as isize;
3968            last_line_pos = Some(pos);
3969        }
3970
3971        // Clamp to the last laid-out row. Returning the end of the whole document
3972        // would select unseen text before drag autoscroll has reached it.
3973        let last_position = last_layout
3974            .lines
3975            .last()
3976            .zip(last_line_pos)
3977            .zip(last_layout.visible_line_byte_offsets.last())
3978            .map(|((line_layout, pos), line_start)| {
3979                let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3980                let pos = point(pos.x, last_row_top);
3981                (
3982                    self.resolve_index(line_start + line_layout.len()),
3983                    false,
3984                    line_layout.columns_past_line_end(pos, last_layout),
3985                )
3986            });
3987
3988        last_position.unwrap_or((self.text.len(), false, 0))
3989    }
3990
3991    /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3992    /// is masked.
3993    fn resolve_index(&self, index: usize) -> usize {
3994        if self.masked {
3995            self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3996        } else {
3997            index.min(self.text.len())
3998        }
3999    }
4000
4001    /// Returns a y offsetted point for the line origin.
4002    /// Select the text from the current cursor position to the given offset.
4003    ///
4004    /// The offset is the UTF-8 offset.
4005    ///
4006    /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
4007    /// Extend a single selection so its moving end lands at `offset`, flipping
4008    /// `reversed` when the ends cross. When a sticky `word_range` is given the
4009    /// selection is kept covering it.
4010    fn extend_selection(
4011        sel: &mut CursorSelection,
4012        offset: usize,
4013        word_range: Option<CursorSelection>,
4014    ) {
4015        if sel.reversed {
4016            sel.start = offset;
4017        } else {
4018            sel.end = offset;
4019        }
4020
4021        if sel.end < sel.start {
4022            sel.reversed = !sel.reversed;
4023            std::mem::swap(&mut sel.start, &mut sel.end);
4024        }
4025
4026        if let Some(word_range) = word_range {
4027            if sel.start > word_range.start {
4028                sel.start = word_range.start;
4029            }
4030            if sel.end < word_range.end {
4031                sel.end = word_range.end;
4032            }
4033        }
4034    }
4035
4036    /// Extend only the active selection to `offset`. Used by mouse drag.
4037    pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
4038        self.select_to_with_affinity(offset, false, cx);
4039    }
4040
4041    /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
4042    ///
4043    /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
4044    /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
4045    /// the text rather than from a visual position, so the caret has no reason to keep sticking
4046    /// to the end of a wrapped row.
4047    pub(crate) fn select_to_with_affinity(
4048        &mut self,
4049        offset: usize,
4050        line_end_affinity: bool,
4051        cx: &mut Context<Self>,
4052    ) {
4053        M::clear_inline_completion(self, cx);
4054
4055        self.cursor_line_end_affinity = line_end_affinity;
4056        let offset = self.cursor_boundary(offset, Bias::Left);
4057        let word_range = self.selected_word_range;
4058        Self::extend_selection(self.active_selection_mut(), offset, word_range);
4059        let range = self.normalize_token_range(self.selected_range());
4060        self.set_selection(range.start, range.end);
4061
4062        if self.active_selection().is_empty() {
4063            self.update_preferred_column();
4064        }
4065        cx.notify()
4066    }
4067
4068    /// Extend every selection to the offset produced by `f`, then merge any
4069    /// selections that now overlap. Used by keyboard selection commands.
4070    fn select_all_cursors_to(
4071        &mut self,
4072        f: impl Fn(&Self, &CursorSelection) -> usize,
4073        cx: &mut Context<Self>,
4074    ) {
4075        self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
4076    }
4077
4078    /// Extend selections with caret affinity, preserving their column anchors even
4079    /// when vertical movement collapses a selection to a cursor.
4080    fn select_all_cursors_to_with_affinity(
4081        &mut self,
4082        f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
4083        preserve_column: bool,
4084        cx: &mut Context<Self>,
4085    ) {
4086        self.pause_blink_cursor(cx);
4087        self.undo_manager.break_transaction_coalescing();
4088        M::clear_inline_completion(self, cx);
4089
4090        let mut active_affinity = false;
4091        let new_selections: Vec<CursorSelection> = self
4092            .selections
4093            .iter()
4094            .map(|sel| {
4095                let (offset, affinity) = f(self, sel);
4096                if sel.id == self.active_selection().id {
4097                    active_affinity = affinity;
4098                }
4099                let offset = self.cursor_boundary(offset, Bias::Left);
4100                let mut new_sel = *sel;
4101                Self::extend_selection(&mut new_sel, offset, None);
4102                let range = self.normalize_token_range(new_sel.start..new_sel.end);
4103                new_sel.start = range.start;
4104                new_sel.end = range.end;
4105                if !preserve_column {
4106                    new_sel.column_anchor =
4107                        self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
4108                } else if new_sel.column_anchor.is_none() {
4109                    new_sel.column_anchor = self.preferred_column_for_with_affinity(
4110                        sel.cursor_offset(),
4111                        self.line_end_affinity_for(sel),
4112                    );
4113                }
4114                new_sel
4115            })
4116            .collect();
4117        self.cursor_line_end_affinity = active_affinity;
4118        self.selections.replace_all(new_selections);
4119        self.selections.merge_overlapping();
4120
4121        self.scroll_to(self.cursor(), None, cx);
4122        cx.notify()
4123    }
4124
4125    /// Unselects the currently selected text.
4126    pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4127        self.undo_manager.break_transaction_coalescing();
4128        let offset = self.cursor();
4129        self.set_cursor_to(offset);
4130        cx.notify()
4131    }
4132
4133    #[inline]
4134    pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
4135        self.text.offset_utf16_to_offset(offset)
4136    }
4137
4138    #[inline]
4139    pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
4140        self.text.offset_to_offset_utf16(offset)
4141    }
4142
4143    #[inline]
4144    pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
4145        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
4146    }
4147
4148    #[inline]
4149    pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
4150        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
4151    }
4152
4153    /// If offset falls on a hidden (folded) line, clamp backward to the end of
4154    /// the fold header line (last visible position before the fold).
4155    fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
4156        let line = self.text.offset_to_point(offset).row;
4157        if self.display_map.is_buffer_line_hidden(line) {
4158            for fold in self.display_map.folded_ranges() {
4159                if line > fold.start_line && line <= fold.end_line {
4160                    return self.text.line_end_offset(fold.start_line);
4161                }
4162            }
4163        }
4164        offset
4165    }
4166
4167    /// If offset falls on a hidden (folded) line, clamp forward to the start of
4168    /// the fold end line (first visible position after the fold).
4169    fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
4170        let line = self.text.offset_to_point(offset).row;
4171        if self.display_map.is_buffer_line_hidden(line) {
4172            for fold in self.display_map.folded_ranges() {
4173                if line > fold.start_line && line <= fold.end_line {
4174                    return self.text.line_start_offset(fold.end_line);
4175                }
4176            }
4177        }
4178        offset
4179    }
4180
4181    /// Clip a cursor/selection offset without splitting a CRLF newline. This does
4182    /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
4183    pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
4184        let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
4185        if offset > 0
4186            && self.text.char_at(offset - 1) == Some('\r')
4187            && self.text.char_at(offset) == Some('\n')
4188        {
4189            if bias == Bias::Left {
4190                offset - 1
4191            } else {
4192                offset + 1
4193            }
4194        } else {
4195            offset
4196        }
4197    }
4198
4199    pub(super) fn previous_boundary(&self, offset: usize) -> usize {
4200        let offset =
4201            self.cursor_boundary(previous_grapheme_boundary(&self.text, offset), Bias::Left);
4202        self.clamp_offset_to_visible_backward(offset)
4203    }
4204
4205    pub(super) fn next_boundary(&self, offset: usize) -> usize {
4206        let offset = self.cursor_boundary(next_grapheme_boundary(&self.text, offset), Bias::Right);
4207        self.clamp_offset_to_visible_forward(offset)
4208    }
4209
4210    /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
4211    pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
4212        (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
4213            && !self.disabled
4214            && self.blink_cursor.read(cx).visible()
4215            && window.is_window_active()
4216    }
4217
4218    fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4219        self.blink_cursor.update(cx, |cursor, cx| {
4220            cursor.start(cx);
4221        });
4222        cx.emit(InputEvent::Focus);
4223    }
4224
4225    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4226        self.cancel_mouse_gesture(cx);
4227        self.revealed_viewport = None;
4228        if M::is_context_menu_open(self, cx) {
4229            return;
4230        }
4231
4232        M::hide_context_menu(self, cx);
4233        self.undo_manager.break_transaction_coalescing();
4234
4235        // NOTE: Do not cancel select, when blur.
4236        // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
4237
4238        M::clear_hover_state(self, cx);
4239        self.diagnostic_popover = None;
4240        M::clear_inline_completion(self, cx);
4241        self.dismiss_touch_selection(cx);
4242        self.blink_cursor.update(cx, |cursor, cx| {
4243            cursor.stop(cx);
4244        });
4245        self.clamp_number_value(window, cx);
4246        cx.emit(InputEvent::Blur);
4247        cx.notify();
4248    }
4249
4250    /// Clamp the number value to the `min`/`max` range, used on blur.
4251    ///
4252    /// Out-of-range values are allowed while typing (e.g. `1` is an
4253    /// intermediate state of `15` when min is 10), and clamped on blur.
4254    fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4255        if !self.is_single_line() {
4256            return;
4257        }
4258        if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4259            return;
4260        }
4261        if self.number_min.is_none() && self.number_max.is_none() {
4262            return;
4263        }
4264
4265        let Ok(value) = self.unmask_value().parse::<f64>() else {
4266            return;
4267        };
4268
4269        let clamped = match (self.number_min, self.number_max) {
4270            (Some(min), _) if value < min => min,
4271            (_, Some(max)) if value > max => max,
4272            _ => return,
4273        };
4274
4275        // The clamped value must pass the `pattern`/`validate` check,
4276        // otherwise keep the value as is.
4277        let new_text = clamped.to_string();
4278        if !self.is_valid_input(&new_text, cx) {
4279            return;
4280        }
4281
4282        let range = self.range_to_utf16(&(0..self.text.len()));
4283        self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
4284    }
4285
4286    pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
4287        self.blink_cursor.update(cx, |cursor, cx| {
4288            cursor.pause(cx);
4289        });
4290    }
4291
4292    pub(super) fn cancel_mouse_gesture(&mut self, cx: &mut Context<Self>) {
4293        let was_dragging = self.selecting || self.column_select_start.is_some();
4294        self.selecting = false;
4295        self.column_select_start = None;
4296        self.auto_scroll.stop();
4297        if was_dragging {
4298            cx.notify();
4299        }
4300    }
4301
4302    pub(super) fn on_drag_move(
4303        &mut self,
4304        event: &MouseMoveEvent,
4305        window: &mut Window,
4306        cx: &mut Context<Self>,
4307    ) {
4308        if event.pressed_button != Some(MouseButton::Left) {
4309            self.cancel_mouse_gesture(cx);
4310            return;
4311        }
4312        if self.text.len() == 0 {
4313            return;
4314        }
4315
4316        if self.last_layout.is_none() {
4317            return;
4318        }
4319
4320        if !self.focus_handle.is_focused(window) {
4321            return;
4322        }
4323
4324        if !self.selecting {
4325            return;
4326        }
4327
4328        self.auto_scroll.last_drag_position = Some(event.position);
4329        let (offset, line_end_affinity, columns_past_line_end) =
4330            self.resolve_mouse_position(event.position);
4331        if let Some(start) = self.column_select_start {
4332            let end = ColumnarPoint::new(offset, columns_past_line_end);
4333            self.build_columnar_selection(start, end, cx);
4334        } else {
4335            self.select_to_with_affinity(offset, line_end_affinity, cx);
4336        }
4337
4338        if !self.is_single_line() {
4339            let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
4340            // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
4341            let scroll_delta = delta.map(|d| -d);
4342            self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
4343                state.scroll_by_y_f64(f64::from(f32::from(delta)), cx);
4344                if let Some(pos) = state.auto_scroll.last_drag_position {
4345                    let (offset, line_end_affinity, columns_past_line_end) =
4346                        state.resolve_mouse_position(pos);
4347                    if let Some(start) = state.column_select_start {
4348                        let end = ColumnarPoint::new(offset, columns_past_line_end);
4349                        state.build_columnar_selection(start, end, cx);
4350                    } else {
4351                        state.select_to_with_affinity(offset, line_end_affinity, cx);
4352                    }
4353                }
4354            });
4355        }
4356    }
4357
4358    /// Normalize the inserted text before applying it to the input.
4359    ///
4360    /// For number inputs (with [`MaskPattern::Number`]), this converts
4361    /// full-width number characters into their ASCII equivalents,
4362    /// e.g. `12。5` -> `12.5`.
4363    ///
4364    /// A single-line input drops line breaks and tabs: a one-line field has
4365    /// no line to break and no column to indent, and a tab in it is invisible.
4366    pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
4367        let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4368            normalize_number_input(new_text)
4369        } else {
4370            Cow::Borrowed(new_text)
4371        };
4372
4373        if self.is_single_line() && normalized.contains(['\n', '\r', '\t']) {
4374            Cow::Owned(normalized.replace(['\n', '\r', '\t'], ""))
4375        } else {
4376            normalized
4377        }
4378    }
4379
4380    pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
4381        if new_text.is_empty() {
4382            return true;
4383        }
4384
4385        if let Some(validate) = &self.validate {
4386            if !validate(new_text, cx) {
4387                return false;
4388            }
4389        }
4390
4391        if !self.mask_pattern.is_valid(new_text) {
4392            return false;
4393        }
4394
4395        let Some(pattern) = &self.pattern else {
4396            return true;
4397        };
4398
4399        pattern.is_match(new_text)
4400    }
4401
4402    /// Set the mask pattern for formatting the input text.
4403    ///
4404    /// The pattern can contain:
4405    /// - 9: Any digit or dot
4406    /// - A: Any letter
4407    /// - *: Any character
4408    /// - Other characters will be treated as literal mask characters
4409    ///
4410    /// Example: "(999)999-999" for phone numbers
4411    pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
4412        self.mask_pattern = pattern.into();
4413        self.mask_pattern_set = true;
4414        if let Some(placeholder) = self.mask_pattern.placeholder() {
4415            self.placeholder = placeholder.into();
4416        }
4417        self
4418    }
4419
4420    pub fn set_mask_pattern(
4421        &mut self,
4422        pattern: impl Into<MaskPattern>,
4423        _: &mut Window,
4424        cx: &mut Context<Self>,
4425    ) {
4426        self.mask_pattern = pattern.into();
4427        self.mask_pattern_set = true;
4428        if let Some(placeholder) = self.mask_pattern.placeholder() {
4429            self.placeholder = placeholder.into();
4430        }
4431        cx.notify();
4432    }
4433
4434    /// Apply the default numeric mask unless the caller explicitly selected a mask.
4435    pub fn ensure_number_mask(&mut self) {
4436        if self.mask_pattern_set {
4437            return;
4438        }
4439        self.mask_pattern = MaskPattern::Number {
4440            separator: None,
4441            fraction: None,
4442        };
4443    }
4444
4445    pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
4446        let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
4447        self.input_bounds = new_bounds;
4448
4449        // Update display_map wrap_width if changed.
4450        if let Some(last_layout) = self.last_layout.as_ref() {
4451            if wrap_width_changed {
4452                let wrap_width = if !self.soft_wrap {
4453                    // None to disable wrapping (will use Pixels::MAX)
4454                    None
4455                } else {
4456                    last_layout.wrap_width
4457                };
4458
4459                self.display_map.on_layout_changed(wrap_width, cx);
4460                if self.is_multi_line() {
4461                    self.mode.update_auto_grow(&self.display_map);
4462                }
4463                cx.notify();
4464            }
4465        }
4466    }
4467
4468    /// Return the active selection's text, borrowed out of the [`Rope`]
4469    /// the state owns.
4470    ///
4471    /// See [`Self::selected_value`] when an owned string is wanted.
4472    pub fn selected_text(&self) -> RopeSlice<'_> {
4473        let range_utf16 = self.range_to_utf16(&self.selected_range());
4474        let range = self.range_from_utf16(&range_utf16);
4475        self.text.slice(range)
4476    }
4477
4478    /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
4479    ///
4480    /// Returns `None` when the requested range is not currently laid out or visible.
4481    pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
4482        let Some(last_layout) = self.last_layout.as_ref() else {
4483            return None;
4484        };
4485
4486        let Some(last_bounds) = self.last_bounds else {
4487            return None;
4488        };
4489
4490        let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
4491        let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
4492
4493        let Some(start_pos) = start_pos else {
4494            return None;
4495        };
4496        let Some(end_pos) = end_pos else {
4497            return None;
4498        };
4499
4500        Some(Bounds::from_corners(
4501            last_bounds.origin + start_pos,
4502            last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
4503        ))
4504    }
4505
4506    /// Replace text in range in silent.
4507    ///
4508    /// This will not trigger any UI interaction, such as auto-completion.
4509    pub(crate) fn replace_text_in_range_silent(
4510        &mut self,
4511        range_utf16: Option<Range<usize>>,
4512        new_text: &str,
4513        window: &mut Window,
4514        cx: &mut Context<Self>,
4515    ) {
4516        self.silent_replace_text = true;
4517        self.replace_text_in_range(range_utf16, new_text, window, cx);
4518        self.silent_replace_text = false;
4519    }
4520
4521    /// Apply a batch of edits as one atomic history transaction.
4522    ///
4523    /// `edits` are `(byte range in the current pre-edit document, replacement)`
4524    /// pairs.
4525    pub(crate) fn replace_text_in_ranges(
4526        &mut self,
4527        edits: &[(Range<usize>, String)],
4528        window: &mut Window,
4529        cx: &mut Context<Self>,
4530    ) {
4531        if !self.is_editable() || edits.is_empty() {
4532            return;
4533        }
4534
4535        // Every edit invalidates provider responses for the previous document,
4536        // including deletion and indentation which do not trigger completion.
4537        M::hide_context_menu(self, cx);
4538        M::clear_inline_completion(self, cx);
4539
4540        // Sort descending by start so applying front-of-vec first edits the
4541        // highest offsets first, leaving lower offsets unchanged.
4542        let mut sorted: Vec<(Range<usize>, &str)> = edits
4543            .iter()
4544            .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
4545            .collect();
4546        sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
4547        if !self.token_spans().is_empty() {
4548            let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
4549            for (range, text) in sorted {
4550                if let Some(last) = merged
4551                    .last_mut()
4552                    .filter(|last| range.end > last.0.start || range == last.0)
4553                {
4554                    last.0.start = range.start.min(last.0.start);
4555                    last.0.end = range.end.max(last.0.end);
4556                } else {
4557                    merged.push((range, text));
4558                }
4559            }
4560            sorted = merged;
4561        }
4562
4563        #[cfg(debug_assertions)]
4564        for pair in sorted.windows(2) {
4565            debug_assert!(
4566                pair[1].0.end <= pair[0].0.start,
4567                "replace_text_in_ranges requires disjoint ranges"
4568            );
4569        }
4570
4571        // Wrap multiple edits in one explicit transaction so they undo as a
4572        // unit. A single edit records directly, which keeps it eligible for
4573        // the undo manager's typing coalescing.
4574        let requested_intent = self.undo_manager.take_pending_intent();
4575        let selection_before = *self.active_selection();
4576        let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
4577        // Snapshot the cursors before applying, so undo can restore them. A
4578        // delete has already expanded them over the text it removes, so they
4579        // collapse back to where the user left them.
4580        let selections_before: Vec<CursorSelection> = self
4581            .selections
4582            .iter()
4583            .map(|selection| {
4584                Self::collapse_for_intent(
4585                    requested_intent.unwrap_or(EditIntent::Atomic),
4586                    *selection,
4587                    &(selection.start..selection.end),
4588                )
4589            })
4590            .collect();
4591        let group = sorted.len() > 1;
4592        if group {
4593            self.undo_manager.begin_transaction();
4594        }
4595
4596        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4597        let mut recorded = false;
4598        // Several edits reach the highlighter as one batch, so it reparses
4599        // once for the change instead of once per edit.
4600        let mut highlighter_edits = Vec::new();
4601        // Token-aware history replay applies several replacements but emits one
4602        // `Change` at the end, so its edits accumulate instead of being
4603        // discarded with each silent replacement.
4604        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4605        if !accumulate_replay_edits {
4606            self.last_input_edits.clear();
4607        }
4608        for (range, new_text) in &sorted {
4609            let old_text = self.text.clone();
4610            self.mode.adjust_auto_closed_pair(range, new_text.len());
4611            self.text.replace(range.clone(), new_text);
4612
4613            M::adjust_annotations(self, range, new_text.len());
4614            recorded |= self.push_history(
4615                &old_text,
4616                range,
4617                new_text,
4618                requested_intent,
4619                selection_before,
4620                None,
4621            );
4622
4623            // Incremental, single-range updates must run per edit.
4624            self.display_map
4625                .adjust_folds_for_edit(&old_text, range, new_text);
4626            if *range == (0..old_text.len()) {
4627                self.adopt_gutter_wrap_width(&old_text, window);
4628            }
4629            self.display_map
4630                .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
4631
4632            let edit = super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
4633            if self.emit_events || self.replaying_history {
4634                self.last_input_edits.push((edit, self.text.clone()));
4635            }
4636
4637            if group {
4638                if self.is_code_editor() {
4639                    highlighter_edits.push((edit, self.text.clone()));
4640                }
4641            } else {
4642                self.mode.update_highlighter(
4643                    super::mode::HighlighterUpdate {
4644                        selected_range: range,
4645                        old_text: &old_text,
4646                        new_text: &self.text,
4647                        change_text: new_text,
4648                        force: true,
4649                        input_edit: Some(edit),
4650                    },
4651                    window,
4652                    cx,
4653                );
4654
4655                self.update_fold_candidates_incremental(range, new_text);
4656            }
4657        }
4658
4659        if group {
4660            self.mode
4661                .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
4662
4663            // Fold candidates are read from the reparsed document, so each
4664            // edit is located where it ended up once every edit was applied.
4665            // `sorted` runs from the highest offset down.
4666            let mut shift = 0isize;
4667            for (range, new_text) in sorted.iter().rev() {
4668                let start = (range.start as isize + shift) as usize;
4669                self.update_fold_candidates_incremental(&(start..start), new_text);
4670                shift += new_text.len() as isize - range.len() as isize;
4671            }
4672
4673            self.undo_manager.commit_transaction();
4674        }
4675
4676        // One observable update per batch instead of one per edit.
4677        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4678            diagnostics.reset(&self.text)
4679        }
4680        M::refresh_language_features(self, window, cx);
4681        self.update_search(cx);
4682
4683        // Compute the resulting cursors.
4684        // One collapsed cursor per edit, at the end of its inserted text.
4685        let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
4686        ascending.sort_by_key(|edit| edit.0.start);
4687        let text_len = self.text.len();
4688        let mut delta: isize = 0;
4689        let mut edit_results = Vec::with_capacity(ascending.len());
4690        for (range, new_text) in &ascending {
4691            let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
4692            edit_results.push((range.clone(), offset));
4693            delta += new_text.len() as isize - (range.end as isize - range.start as isize);
4694        }
4695
4696        let mut used = vec![false; edit_results.len()];
4697        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
4698        for selection in original_selections {
4699            if let Ok(index) = edit_results
4700                .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
4701                    (range.start, range.end)
4702                })
4703                && !used[index]
4704            {
4705                let offset = edit_results[index].1;
4706                used[index] = true;
4707                let mut selection = selection;
4708                selection.place_at(offset, None);
4709                new_selections.push(selection);
4710            }
4711        }
4712        for (index, (_, offset)) in edit_results.into_iter().enumerate() {
4713            if !used[index] {
4714                new_selections.push(CursorSelection::new(
4715                    self.selections.generate_id(),
4716                    offset,
4717                    offset,
4718                ));
4719            }
4720        }
4721        self.selections.replace_all(new_selections);
4722        self.selections.merge_overlapping();
4723
4724        // Record the cursor snapshots for undo/redo restore.
4725        let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
4726        if recorded {
4727            self.undo_manager.record_auto_closed_pairs(
4728                auto_closed_pairs_before,
4729                self.mode.auto_closed_pairs().clone(),
4730            );
4731            self.undo_manager
4732                .record_selections(selections_before, selections_after);
4733        }
4734
4735        self.ime_marked_range.take();
4736        self.update_preferred_column();
4737        self.dismiss_touch_selection(cx);
4738        if self.is_multi_line() {
4739            self.mode.update_auto_grow(&self.display_map);
4740        }
4741        if self.emit_events {
4742            self.emit_change(cx);
4743        }
4744        cx.notify();
4745    }
4746
4747    /// Replacing the whole text can change how many digits the line-number gutter shows, and so
4748    /// the wrap width the next layout picks. Adopting that width before the new text is wrapped
4749    /// saves wrapping all of it again at that layout.
4750    fn adopt_gutter_wrap_width(&mut self, old_text: &Rope, window: &mut Window) {
4751        let Some(wrap_width) = self.display_map.wrap_width() else {
4752            return;
4753        };
4754        let old_digits = line_number_len(old_text.lines_len());
4755        let new_digits = line_number_len(self.text.lines_len());
4756        if !self.mode.line_number() || old_digits == new_digits {
4757            return;
4758        }
4759        let (font, font_size) = self.display_map.font();
4760        let font = font.clone();
4761        let old_width = line_number_digits_width(old_digits, font.clone(), font_size, window);
4762        let new_width = line_number_digits_width(new_digits, font, font_size, window);
4763        self.display_map
4764            .prepare_wrap_width(wrap_width - (new_width - old_width));
4765    }
4766
4767    /// Update fold candidates from tree-sitter syntax tree (full extraction).
4768    /// Used only on initial load or language changes.
4769    fn update_fold_candidates(&mut self) {
4770        if !self.mode.is_folding() {
4771            return;
4772        }
4773
4774        let Some(highlighter_rc) = self.mode.highlighter() else {
4775            return;
4776        };
4777
4778        let highlighter = highlighter_rc.borrow();
4779        let Some(highlighter) = highlighter.as_ref() else {
4780            return;
4781        };
4782
4783        let fold_ranges = highlighter.fold_ranges(&self.text);
4784        self.display_map.set_fold_candidates(fold_ranges);
4785    }
4786
4787    /// Incrementally update fold candidates after a text edit.
4788    /// Only traverses the edited region of the syntax tree instead of the full tree.
4789    fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
4790        if !self.mode.is_folding() {
4791            return;
4792        }
4793
4794        let Some(highlighter_rc) = self.mode.highlighter() else {
4795            return;
4796        };
4797
4798        let highlighter = highlighter_rc.borrow();
4799        let Some(highlighter) = highlighter.as_ref() else {
4800            return;
4801        };
4802
4803        // The new byte range in the updated text after the edit
4804        let new_end = edit_range.start + new_text.len();
4805        self.display_map.update_fold_candidates_for_edit(
4806            |range, text| highlighter.fold_ranges_for_edit(range, text),
4807            edit_range.start..new_end,
4808            &self.text,
4809        );
4810    }
4811}
4812
4813impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4814    fn accepts_text_input(&self, window: &mut Window, _cx: &mut Context<Self>) -> bool {
4815        self.focus_handle.is_focused(window)
4816    }
4817
4818    fn text_for_range(
4819        &mut self,
4820        range_utf16: Range<usize>,
4821        adjusted_range: &mut Option<Range<usize>>,
4822        _window: &mut Window,
4823        _cx: &mut Context<Self>,
4824    ) -> Option<String> {
4825        let range = self.range_from_utf16(&range_utf16);
4826        let range_utf16 = self.range_to_utf16(&range);
4827        let utf16_len = range_utf16.len();
4828        adjusted_range.replace(range_utf16);
4829        if self.masked {
4830            // Keep the redacted text aligned with the platform's UTF-16 range.
4831            return Some(MASK_CHAR.to_string().repeat(utf16_len));
4832        }
4833        Some(self.text.slice(range).to_string())
4834    }
4835
4836    fn selected_text_range(
4837        &mut self,
4838        _ignore_disabled_input: bool,
4839        _window: &mut Window,
4840        _cx: &mut Context<Self>,
4841    ) -> Option<UTF16Selection> {
4842        Some(UTF16Selection {
4843            range: self.range_to_utf16(&self.selected_range()),
4844            reversed: self.active_selection().reversed,
4845        })
4846    }
4847
4848    /// The whole document's length in UTF-16 units.
4849    ///
4850    /// Platforms use this to learn that the handler has a document at all:
4851    /// the iOS backend only makes the view first responder, and so only shows
4852    /// the on-screen keyboard, when it can tell the document's range.
4853    fn text_length_utf16(
4854        &mut self,
4855        _window: &mut Window,
4856        _cx: &mut Context<Self>,
4857    ) -> Option<usize> {
4858        Some(self.offset_to_utf16(self.text.len()))
4859    }
4860
4861    /// Select the given range, as the platform's own text UI asks when it
4862    /// drives the selection: a native selection handle, or the macOS IME.
4863    ///
4864    /// The end that moved becomes the cursor, so dragging the start handle
4865    /// leaves a reversed selection and keeps the moving end in view. Text and
4866    /// undo history are left alone.
4867    fn set_selected_text_range(
4868        &mut self,
4869        range_utf16: Range<usize>,
4870        _window: &mut Window,
4871        cx: &mut Context<Self>,
4872    ) {
4873        let previous = self.selected_range();
4874        let was_reversed = self.active_selection().reversed;
4875        let range = self.range_from_utf16(&range_utf16);
4876        let range = range.start.min(range.end)..range.start.max(range.end);
4877        self.set_selected_range(range, cx);
4878
4879        let range = self.selected_range();
4880        let reversed = if range == previous {
4881            was_reversed
4882        } else if !range.is_empty() && range.end == previous.start {
4883            true
4884        } else if !range.is_empty() && range.start == previous.end {
4885            false
4886        } else {
4887            !range.is_empty() && range.start != previous.start && range.end == previous.end
4888        };
4889        self.active_selection_mut().reversed = reversed;
4890        self.scroll_to(self.cursor(), None, cx);
4891        cx.notify();
4892    }
4893
4894    fn marked_text_range(
4895        &self,
4896        _window: &mut Window,
4897        _cx: &mut Context<Self>,
4898    ) -> Option<Range<usize>> {
4899        self.ime_marked_range
4900            .map(|range| self.range_to_utf16(&range.into()))
4901    }
4902
4903    fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
4904        self.ime_marked_range = None;
4905        self.undo_manager.commit_transaction();
4906        // Unmarking keeps the preedit as committed text, which marked edits
4907        // never reported. Android keyboards compose every word and often end
4908        // with only this call (hiding the keyboard, moving the caret).
4909        if self.ime_original_text.as_ref() == Some(&self.text) {
4910            self.ime_original_text = None;
4911        } else if self.ime_original_text.is_some() && self.emit_events {
4912            self.emit_change(cx);
4913        }
4914    }
4915
4916    /// Replace text in range.
4917    ///
4918    /// - If the new text is invalid, it will not be replaced.
4919    /// - If `range_utf16` is not provided, the current selected range will be used.
4920    fn replace_text_in_range(
4921        &mut self,
4922        range_utf16: Option<Range<usize>>,
4923        new_text: &str,
4924        window: &mut Window,
4925        cx: &mut Context<Self>,
4926    ) {
4927        let requested_intent = self.undo_manager.take_pending_intent();
4928        if !self.is_editable() {
4929            return;
4930        }
4931        let selection_before = *self.active_selection();
4932        // Committing a composition ends the transaction it opened, whether or
4933        // not the platform follows up with `unmark_text`.
4934        let ends_composition = self.ime_marked_range.is_some();
4935
4936        self.pause_blink_cursor(cx);
4937
4938        // NOTE: The normalization keeps the UTF-16 length, but may change the
4939        // UTF-8 byte length, so all the byte-offset calculations below must
4940        // use the normalized text.
4941        let new_text = if self.replaying_history {
4942            Cow::Borrowed(new_text)
4943        } else {
4944            self.normalize_input(new_text)
4945        };
4946        let new_text: &str = &new_text;
4947
4948        let range = range_utf16
4949            .as_ref()
4950            .map(|range_utf16| self.range_from_utf16(range_utf16))
4951            .or(self.ime_marked_range.map(|range| {
4952                let range = self.range_to_utf16(&(range.start..range.end));
4953                self.range_from_utf16(&range)
4954            }))
4955            .unwrap_or(self.selected_range());
4956        let range = self.normalize_token_range(range);
4957
4958        // Skip-over as a pure cursor move: a typed closer that already follows
4959        // the cursor moves past it without touching text or history, so Undo
4960        // never exposes a transient duplicate. Only for interactive single
4961        // keystrokes (current selection, no IME mark, not silent replays).
4962        // `take_pending_intent` above already consumed any request.
4963        if range.is_empty()
4964            && range.start == self.cursor()
4965            && self.ime_marked_range.is_none()
4966            && !self.silent_replace_text
4967            && self.is_code_editor()
4968            && self.selections.is_single()
4969            && self.active_selection().is_empty()
4970        {
4971            if let Some(target) = self.skip_over_target(new_text) {
4972                self.set_cursor_to(target);
4973                self.update_preferred_column();
4974                cx.notify();
4975                return;
4976            }
4977        }
4978
4979        if self.is_multi_line() {
4980            let multi_cursor = range_utf16.is_none()
4981                && self.ime_marked_range.is_none()
4982                && !self.selections.is_single();
4983            if multi_cursor {
4984                self.selections.merge_overlapping();
4985                let mut edits: Vec<(Range<usize>, String)> = self
4986                    .selections
4987                    .iter()
4988                    .map(|sel| (sel.start..sel.end, new_text.to_string()))
4989                    .collect();
4990                edits.sort_by_key(|(range, _)| range.start);
4991                // One keystroke across several cursors is one batch, committed
4992                // with the intent of the keystroke so a run of them coalesces
4993                // into one undo just like single-cursor typing.
4994                let intent =
4995                    requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
4996                self.undo_manager.begin_transaction_with(intent);
4997                self.undo_manager.set_pending_intent(intent);
4998                self.replace_text_in_ranges(&edits, window, cx);
4999                self.undo_manager.commit_transaction();
5000            } else {
5001                if range_utf16.is_some() {
5002                    self.selections.remove_all_but_active();
5003                }
5004                if let Some(intent) = requested_intent {
5005                    self.undo_manager.set_pending_intent(intent);
5006                }
5007                if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
5008                    // One edit keeps the pair atomic even at undo coalescing limits.
5009                    let replacement = format!("{new_text}{closer}");
5010                    self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
5011                    let cursor = range.start + new_text.len();
5012                    self.mode.track_auto_closed_pair(
5013                        cursor - open_len..cursor,
5014                        cursor..cursor + closer.len(),
5015                    );
5016                    self.undo_manager
5017                        .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
5018                    self.set_cursor_to(cursor);
5019                    self.update_preferred_column();
5020                    self.undo_manager.record_selections(
5021                        vec![selection_before],
5022                        self.selections.iter().copied().collect(),
5023                    );
5024                } else {
5025                    self.replace_text_in_ranges(
5026                        &[(range.clone(), new_text.to_string())],
5027                        window,
5028                        cx,
5029                    );
5030                }
5031            }
5032            if ends_composition {
5033                self.undo_manager.commit_transaction();
5034            }
5035
5036            if !self.silent_replace_text {
5037                M::on_text_typed(self, &range, new_text, window, cx);
5038            }
5039            return;
5040        }
5041
5042        // Single-line path
5043        let old_text = self.text.clone();
5044        // Token-aware history replay applies several replacements but emits one
5045        // `Change` at the end, so its edits accumulate instead of being
5046        // discarded with each silent replacement.
5047        let accumulate_replay_edits = self.replaying_history && !self.emit_events;
5048        if !accumulate_replay_edits {
5049            self.last_input_edits.clear();
5050        }
5051        self.mode.adjust_auto_closed_pair(&range, new_text.len());
5052        self.text.replace(range.clone(), new_text);
5053
5054        let mut new_offset = (range.start + new_text.len()).min(self.text.len());
5055
5056        // True if the mask has changed the text, e.g. regrouping the
5057        // separators or completing a leading dot.
5058        let mut mask_changed = false;
5059
5060        if self.is_single_line() {
5061            let pending_text = self.text.to_string();
5062            // Check if the new text is valid.
5063            //
5064            // Only reject the edit if the old text was valid, to avoid
5065            // trapping a pre-existing invalid text (e.g. a `default_value`
5066            // that does not conform), the user can still edit to fix it.
5067            if !self.replaying_history
5068                && !self.validated_token_edit
5069                && !self.is_valid_input(&pending_text, cx)
5070                && self.is_valid_input(&old_text.to_string(), cx)
5071            {
5072                self.text = old_text;
5073                return;
5074            }
5075
5076            if !self.replaying_history && !self.mask_pattern.is_none() {
5077                let mask_text = self.mask_pattern.mask(&pending_text);
5078                mask_changed = mask_text.as_str() != pending_text;
5079                self.text = Rope::from(mask_text.as_str());
5080                let new_text_len =
5081                    (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
5082                new_offset = (range.start + new_text_len).min(mask_text.len());
5083            }
5084        }
5085
5086        if mask_changed {
5087            // Masking rewrites the whole document, so ranges recorded against
5088            // the old text no longer point at anything.
5089            M::reset_annotations(self);
5090        } else {
5091            M::adjust_annotations(self, &range, new_text.len());
5092        }
5093        if mask_changed {
5094            // A segment-based history entry no longer matches the masked
5095            // document, record a whole-document change instead, so that
5096            // undo/redo can restore the text exactly.
5097            self.push_history(
5098                &old_text,
5099                &(0..old_text.len()),
5100                &self.text.to_string(),
5101                Some(EditIntent::Atomic),
5102                selection_before,
5103                Some((new_offset..new_offset).into()),
5104            );
5105        } else {
5106            self.push_history(
5107                &old_text,
5108                &range,
5109                &new_text,
5110                requested_intent,
5111                selection_before,
5112                None,
5113            );
5114        }
5115        if let Some(diagnostics) = self.mode.diagnostics_mut() {
5116            diagnostics.reset(&self.text)
5117        }
5118        // Adjust folds before updating wrap map: remove overlapping folds and shift others
5119        self.display_map
5120            .adjust_folds_for_edit(&old_text, &range, new_text);
5121        self.display_map
5122            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5123
5124        let edit = if mask_changed {
5125            Self::full_input_edit(&old_text, &self.text)
5126        } else {
5127            super::mode::replacement_input_edit(&old_text, &self.text, &range, new_text)
5128        };
5129        if self.emit_events || self.replaying_history {
5130            self.last_input_edits.push((edit, self.text.clone()));
5131        }
5132
5133        self.mode.update_highlighter::<M>(
5134            super::mode::HighlighterUpdate {
5135                selected_range: &range,
5136                old_text: &old_text,
5137                new_text: &self.text,
5138                change_text: &new_text,
5139                force: true,
5140                input_edit: Some(edit),
5141            },
5142            window,
5143            cx,
5144        );
5145
5146        self.update_fold_candidates_incremental(&range, new_text);
5147        M::refresh_language_features(self, window, cx);
5148        self.set_cursor_to(new_offset);
5149        self.ime_marked_range.take();
5150        // A commit ends the IME composition: macOS delivers `insertText:` for
5151        // the confirmed candidate without a following `unmarkText`, so close
5152        // the transaction here. Leaving it open would keep merging every later
5153        // edit into the same change, which then carries the text and selection
5154        // of the first composition.
5155        if ends_composition {
5156            self.undo_manager
5157                .record_selections(vec![selection_before], vec![*self.active_selection()]);
5158            self.undo_manager.commit_transaction();
5159        }
5160        self.update_preferred_column();
5161        self.update_search(cx);
5162        self.dismiss_touch_selection(cx);
5163        if self.is_multi_line() {
5164            self.mode.update_auto_grow(&self.display_map);
5165        }
5166        if !self.silent_replace_text {
5167            M::on_text_typed(self, &range, &new_text, window, cx);
5168        }
5169        if self.emit_events {
5170            self.emit_change(cx);
5171        }
5172        cx.notify();
5173    }
5174
5175    /// Mark text is the IME temporary insert on typing.
5176    fn replace_and_mark_text_in_range(
5177        &mut self,
5178        range_utf16: Option<Range<usize>>,
5179        new_text: &str,
5180        new_selected_range_utf16: Option<Range<usize>>,
5181        window: &mut Window,
5182        cx: &mut Context<Self>,
5183    ) {
5184        let requested_intent = self.undo_manager.take_pending_intent();
5185        if !self.is_editable() {
5186            return;
5187        }
5188        let selection_before = *self.active_selection();
5189
5190        let starts_composition = self.ime_marked_range.is_none();
5191        if starts_composition {
5192            // Even a canceled preedit separates the typing gestures on either
5193            // side; its no-op transaction must not reconnect those gestures.
5194            self.undo_manager.break_transaction_coalescing();
5195            self.undo_manager.begin_transaction();
5196        }
5197
5198        // Collapse any extra cursors so we never leave stale secondary cursors behind.
5199        self.selections.remove_all_but_active();
5200
5201        M::reset_language_features(self);
5202
5203        // See the same NOTE in `replace_text_in_range`.
5204        let new_text = if self.replaying_history {
5205            Cow::Borrowed(new_text)
5206        } else {
5207            self.normalize_input(new_text)
5208        };
5209        let new_text: &str = &new_text;
5210
5211        let range = range_utf16
5212            .as_ref()
5213            .map(|range_utf16| self.range_from_utf16(range_utf16))
5214            .or(self.ime_marked_range.map(|range| {
5215                let range = self.range_to_utf16(&(range.start..range.end));
5216                self.range_from_utf16(&range)
5217            }))
5218            .unwrap_or(self.selected_range());
5219        let range = self.normalize_token_range(range);
5220
5221        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
5222        let old_text = self.text.clone();
5223        // Marked text does not emit `InputEvent::Change`, so no edit belongs to
5224        // the most recent change after it.
5225        self.last_input_edits.clear();
5226        self.mode.adjust_auto_closed_pair(&range, new_text.len());
5227        self.text.replace(range.clone(), new_text);
5228
5229        if self.is_single_line() {
5230            let pending_text = self.text.to_string();
5231            // See the same NOTE in `replace_text_in_range`.
5232            if !self.replaying_history
5233                && !self.validated_token_edit
5234                && !self.is_valid_input(&pending_text, cx)
5235                && self.is_valid_input(&old_text.to_string(), cx)
5236            {
5237                self.text = old_text;
5238                if starts_composition {
5239                    self.undo_manager.commit_transaction();
5240                }
5241                return;
5242            }
5243        }
5244
5245        if self.ime_original_text.is_none() {
5246            self.ime_original_text = Some(old_text.clone());
5247        }
5248        M::adjust_annotations(self, &range, new_text.len());
5249        if let Some(diagnostics) = self.mode.diagnostics_mut() {
5250            diagnostics.reset(&self.text)
5251        }
5252        // Adjust folds before updating wrap map: remove overlapping folds and shift others
5253        self.display_map
5254            .adjust_folds_for_edit(&old_text, &range, new_text);
5255        self.display_map
5256            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5257
5258        self.mode.update_highlighter::<M>(
5259            super::mode::HighlighterUpdate {
5260                selected_range: &range,
5261                old_text: &old_text,
5262                new_text: &self.text,
5263                change_text: &new_text,
5264                force: true,
5265                input_edit: None,
5266            },
5267            window,
5268            cx,
5269        );
5270
5271        self.update_fold_candidates_incremental(&range, new_text);
5272        M::refresh_language_features(self, window, cx);
5273        if new_text.is_empty() {
5274            // Cancel selection, when cancel IME input.
5275            self.set_cursor_to(range.start);
5276            self.ime_marked_range = None;
5277        } else {
5278            self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
5279            let new_range = new_selected_range_utf16
5280                .as_ref()
5281                .map(|range_utf16| {
5282                    let new_text = Rope::from(new_text);
5283                    range.start + new_text.offset_utf16_to_offset(range_utf16.start)
5284                        ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
5285                })
5286                .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
5287            self.set_selection(new_range.start, new_range.end);
5288        }
5289        if self.is_multi_line() {
5290            self.mode.update_auto_grow(&self.display_map);
5291        }
5292        if self.push_history(
5293            &old_text,
5294            &range,
5295            new_text,
5296            requested_intent,
5297            selection_before,
5298            Some(*self.active_selection()),
5299        ) {
5300            self.undo_manager
5301                .record_selections(vec![selection_before], vec![*self.active_selection()]);
5302            self.undo_manager.record_auto_closed_pairs(
5303                auto_closed_pairs_before,
5304                self.mode.auto_closed_pairs().clone(),
5305            );
5306        }
5307        if new_text.is_empty() {
5308            self.undo_manager.commit_transaction();
5309        }
5310        cx.notify();
5311    }
5312
5313    /// Used to position IME candidates.
5314    fn bounds_for_range(
5315        &mut self,
5316        range_utf16: Range<usize>,
5317        bounds: Bounds<Pixels>,
5318        _window: &mut Window,
5319        _cx: &mut Context<Self>,
5320    ) -> Option<Bounds<Pixels>> {
5321        let last_layout = self.last_layout.as_ref()?;
5322        let line_height = last_layout.line_height;
5323        let line_number_width = last_layout.line_number_width;
5324        let range = self.range_from_utf16(&range_utf16);
5325
5326        let mut start_origin = None;
5327        let mut end_origin = None;
5328        let line_number_origin = point(line_number_width, px(0.));
5329        let mut row_offset: isize = 0;
5330
5331        let start_row = self
5332            .text
5333            .offset_to_point(range.start.min(self.text.len()))
5334            .row;
5335        let end_row = self
5336            .text
5337            .offset_to_point(range.end.min(self.text.len()))
5338            .row;
5339
5340        for (vi, line) in last_layout.lines.iter().enumerate() {
5341            if start_origin.is_some() && end_origin.is_some() {
5342                break;
5343            }
5344
5345            let y_offset = last_layout.local_row_y(row_offset);
5346            let buffer_line = last_layout.visible_buffer_lines[vi];
5347            let index_offset = last_layout.visible_line_byte_offsets[vi];
5348
5349            if start_origin.is_none() && buffer_line == start_row {
5350                let local_offset = range.start.saturating_sub(index_offset).min(line.len());
5351                let p = line
5352                    .position_for_index(local_offset, last_layout, false)
5353                    .unwrap_or_else(|| point(px(0.), px(0.)));
5354                start_origin = Some(p + point(px(0.), y_offset));
5355            }
5356
5357            if end_origin.is_none() && buffer_line == end_row {
5358                let local_offset = range.end.saturating_sub(index_offset).min(line.len());
5359                let p = line
5360                    .position_for_index(local_offset, last_layout, false)
5361                    .unwrap_or_else(|| point(px(0.), px(0.)));
5362                end_origin = Some(p + point(px(0.), y_offset));
5363            }
5364
5365            row_offset += line.wrapped_lines.len() as isize;
5366        }
5367
5368        let start_origin = start_origin.or_else(|| {
5369            let offset = self.last_cursor.or(Some(self.cursor()))?;
5370            let (_, _, origin) = self.line_and_position_for_offset(offset);
5371            origin.map(|origin| origin - line_number_origin)
5372        })?;
5373        let mut end_origin = end_origin.unwrap_or(start_origin);
5374        // Ensure at same line.
5375        end_origin.y = start_origin.y;
5376        if end_origin.x <= start_origin.x {
5377            end_origin.x = start_origin.x + px(1.);
5378        }
5379
5380        Some(Bounds::from_corners(
5381            bounds.origin + line_number_origin + start_origin,
5382            // + line_height for show IME panel under the cursor line.
5383            bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
5384        ))
5385    }
5386
5387    fn character_index_for_point(
5388        &mut self,
5389        point: gpui::Point<Pixels>,
5390        _window: &mut Window,
5391        _cx: &mut Context<Self>,
5392    ) -> Option<usize> {
5393        let last_layout = self.last_layout.as_ref()?;
5394        // The same origin as `resolve_mouse_position`: past the gutter, at the first
5395        // visible line.
5396        let inner_point = self.last_bounds?.localize(&point)?
5397            - gpui::point(last_layout.line_number_width, last_layout.visible_top);
5398
5399        let mut row_offset: usize = 0;
5400        for (vi, line) in last_layout.lines.iter().enumerate() {
5401            let offset = last_layout.visible_line_byte_offsets[vi];
5402            let line_top = last_layout.line_height * (row_offset as f32);
5403            let line_point = inner_point - gpui::point(px(0.), line_top);
5404            if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
5405                return Some(self.offset_to_utf16(self.resolve_index(offset + utf8_index)));
5406            }
5407            row_offset += line.wrapped_lines.len();
5408        }
5409
5410        None
5411    }
5412
5413    fn text_input_configuration(
5414        &mut self,
5415        _window: &mut Window,
5416        _cx: &mut Context<Self>,
5417    ) -> TextInputConfiguration {
5418        InputBaseState::text_input_configuration(self)
5419    }
5420}
5421
5422impl<M: InputModeKind> Focusable for InputBaseState<M> {
5423    fn focus_handle(&self, _cx: &App) -> FocusHandle {
5424        self.focus_handle.clone()
5425    }
5426}
5427
5428impl<M: InputModeKind> Render for InputBaseState<M> {
5429    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5430        self.render_with_line_numbers((), window, cx)
5431    }
5432}
5433
5434impl<M: InputModeKind> InputBaseState<M> {
5435    pub(crate) fn render_with_line_numbers<R: EditorLineNumberRenderer>(
5436        &mut self,
5437        line_number_renderer: R,
5438        window: &mut Window,
5439        cx: &mut Context<Self>,
5440    ) -> impl IntoElement {
5441        // Before anything reads it: the element resolves this style during
5442        // layout and paint, and both happen after this call in the same frame.
5443        self.editor_style = self
5444            .projected_editor_style
5445            .resolved(&crate::Theme::global(cx).tokens);
5446        let entity = cx.entity();
5447        let exposed_text = self
5448            .accessibility
5449            .as_ref()
5450            .is_some_and(|accessibility| {
5451                accessibility.value_exposed
5452                    && !self.masked
5453                    && (window.is_a11y_active() || cfg!(feature = "test-support"))
5454            })
5455            .then(|| self.text.to_string());
5456        let text_runs = self.accessibility_text_runs(exposed_text.as_deref(), window);
5457        if self._pending_update {
5458            self.mode.update_highlighter::<M>(
5459                super::mode::HighlighterUpdate {
5460                    selected_range: &(0..0),
5461                    old_text: &self.text,
5462                    new_text: &self.text,
5463                    change_text: "",
5464                    force: false,
5465                    input_edit: None,
5466                },
5467                window,
5468                cx,
5469            );
5470
5471            self.update_fold_candidates();
5472            M::refresh_language_features(self, window, cx);
5473            self._pending_update = false;
5474        }
5475
5476        let element = div()
5477            .id(EDITOR_ELEMENT_ID)
5478            .key_context(CONTEXT)
5479            .when_some(self.accessibility.as_ref(), |this, accessibility| {
5480                this.when_some(accessibility.role, |this, role| this.role(role))
5481                    .when_some(accessibility.label.clone(), |this, label| {
5482                        this.aria_label(label)
5483                    })
5484                    .when_some(accessibility.placeholder.clone(), |this, placeholder| {
5485                        this.aria_placeholder(placeholder)
5486                    })
5487                    .when_some(accessibility.accessibility_id.clone(), |this, id| {
5488                        this.accessibility_id(id)
5489                    })
5490                    .when_some(exposed_text, |this, text| this.aria_value(text))
5491                    .when_some(text_runs, |this, runs| {
5492                        this.a11y_synthetic_children(move |builder| runs.push(builder))
5493                    })
5494                    .on_a11y_action(gpui::AccessibleAction::Focus, {
5495                        let entity = entity.clone();
5496                        move |_, window, cx| {
5497                            entity.update(cx, |state, cx| {
5498                                state.handle_accessibility_focus(window, cx)
5499                            });
5500                        }
5501                    })
5502                    .when(self.is_editable(), |this| {
5503                        this.on_a11y_action(gpui::AccessibleAction::SetValue, {
5504                            let entity = entity.clone();
5505                            move |data, window, cx| {
5506                                entity.update(cx, |state, cx| {
5507                                    state.handle_accessibility_set_value(data, window, cx)
5508                                });
5509                            }
5510                        })
5511                    })
5512            })
5513            .when(self.is_editable(), |this| {
5514                this.on_action(window.listener_for(&entity, InputBaseState::backspace))
5515                    .on_action(window.listener_for(&entity, InputBaseState::delete))
5516                    .on_action(
5517                        window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
5518                    )
5519                    .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
5520                    .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
5521                    .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
5522                    .on_action(window.listener_for(&entity, InputBaseState::enter))
5523                    .on_action(window.listener_for(&entity, InputBaseState::escape))
5524                    .on_action(window.listener_for(&entity, InputBaseState::paste))
5525                    .on_action(window.listener_for(&entity, InputBaseState::cut))
5526                    .on_action(window.listener_for(&entity, InputBaseState::undo))
5527                    .on_action(window.listener_for(&entity, InputBaseState::redo))
5528                    .when(self.is_multi_line(), |this| {
5529                        this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
5530                            .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
5531                            .on_action(window.listener_for(&entity, InputBaseState::indent_block))
5532                            .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
5533                    })
5534            })
5535            .on_action(window.listener_for(&entity, InputBaseState::left))
5536            .on_action(window.listener_for(&entity, InputBaseState::right))
5537            .on_action(window.listener_for(&entity, InputBaseState::select_left))
5538            .on_action(window.listener_for(&entity, InputBaseState::select_right))
5539            .when(self.is_multi_line(), |this| {
5540                this.on_action(window.listener_for(&entity, InputBaseState::up))
5541                    .on_action(window.listener_for(&entity, InputBaseState::down))
5542                    .on_action(window.listener_for(&entity, InputBaseState::select_up))
5543                    .on_action(window.listener_for(&entity, InputBaseState::select_down))
5544                    .on_action(window.listener_for(&entity, InputBaseState::page_up))
5545                    .on_action(window.listener_for(&entity, InputBaseState::page_down))
5546                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
5547                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
5548            })
5549            .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
5550            .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
5551            .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
5552            .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
5553            .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
5554            .on_action(window.listener_for(&entity, InputBaseState::home))
5555            .on_action(window.listener_for(&entity, InputBaseState::end))
5556            .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
5557            .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
5558            .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
5559            .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
5560            .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
5561            .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
5562            .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
5563            .on_action({
5564                let entity = entity.clone();
5565                move |_: &ActivateToken, window, cx| {
5566                    let state = entity.read(cx);
5567                    let activation = state
5568                        .token_spans()
5569                        .iter()
5570                        .find(|span| span.range() == state.selected_range())
5571                        .and_then(|span| {
5572                            state.range_to_bounds(&span.range()).and_then(|bounds| {
5573                                state.token_activation(
5574                                    span.range().start,
5575                                    bounds,
5576                                    gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
5577                                        bounds,
5578                                        ..Default::default()
5579                                    }),
5580                                )
5581                            })
5582                        });
5583                    if let Some((listener, event)) = activation {
5584                        listener(&event, window, cx);
5585                    }
5586                }
5587            })
5588            .on_action(window.listener_for(&entity, InputBaseState::copy))
5589            .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
5590            .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
5591            .on_mouse_down(
5592                MouseButton::Left,
5593                window.listener_for(&entity, InputBaseState::on_mouse_down),
5594            )
5595            .on_mouse_down(
5596                MouseButton::Right,
5597                window.listener_for(&entity, InputBaseState::on_mouse_down),
5598            )
5599            .on_mouse_up(
5600                MouseButton::Left,
5601                window.listener_for(&entity, InputBaseState::on_mouse_up),
5602            )
5603            .on_mouse_up(
5604                MouseButton::Right,
5605                window.listener_for(&entity, InputBaseState::on_mouse_up),
5606            )
5607            .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
5608            .on_scroll(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
5609            .when(self.is_multi_line() && !self.disabled, |this| {
5610                this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
5611            })
5612            .when(!self.disabled, |this| {
5613                if self.is_multi_line() && window.modifiers().alt {
5614                    this.cursor_crosshair()
5615                } else {
5616                    this.cursor_text()
5617                }
5618            })
5619            .flex_1()
5620            // A single line fills the frame and sits at its vertical center,
5621            // so the frame needs no layout of its own to hold it. It is never
5622            // shorter than its line, though: this root clips (overflow-x
5623            // hidden clips both axes), and a frame whose padding leaves less
5624            // than a line, like Component's Input, would cut off descenders.
5625            .map(|this| {
5626                if self.is_multi_line() {
5627                    this.h_full()
5628                } else {
5629                    this.min_h_full().flex().items_center()
5630                }
5631            })
5632            .flex_grow_1()
5633            .overflow_x_hidden()
5634            .when(self.is_multi_line(), |this| {
5635                this.pt(self.editor_paddings.top)
5636                    .pr(self.editor_paddings.right)
5637                    .pb(self.editor_paddings.bottom)
5638                    .pl(self.editor_paddings.left)
5639            })
5640            .child(
5641                TextElement::new(entity.clone())
5642                    .with_line_number_renderer(line_number_renderer)
5643                    .placeholder(self.placeholder.clone()),
5644            )
5645            .when(self.shows_scrollbar(), |this| {
5646                this.child(EditorScrollbar::new(entity.clone()))
5647            });
5648
5649        // Actions only one mode handles are registered by that mode, where
5650        // `Self` is concrete enough to name its own entity type.
5651        M::register_actions(element, &entity, window)
5652            .test_support()
5653            .track_focus(&self.focus_handle)
5654    }
5655}
5656
5657#[cfg(test)]
5658mod tests {
5659    use super::*;
5660
5661    #[gpui::test]
5662    fn test_set_value_waits_for_the_first_layout(cx: &mut TestAppContext) {
5663        cx.update(crate::init);
5664        let (state, cx) = cx.add_window_view(|window, cx| {
5665            let mut state = crate::input::InputState::new(window, cx);
5666            state.set_value("hello", window, cx);
5667            // Made outside drawing, the state only has a placeholder font to shape with.
5668            assert_eq!(state.display_map().wrap_row_count(), 0);
5669            state
5670        });
5671        cx.update(|window, cx| window.draw(cx).clear(cx));
5672        state.read_with(cx, |state, _| {
5673            assert_eq!(state.value(), "hello");
5674            assert_eq!(state.display_map().wrap_row_count(), 1);
5675        });
5676    }
5677
5678    #[gpui::test]
5679    fn accessibility_actions_recheck_live_editability(cx: &mut TestAppContext) {
5680        cx.update(crate::init);
5681        let (state, cx) = cx.add_window_view(|window, cx| {
5682            crate::input::InputState::new(window, cx).default_value("initial")
5683        });
5684        let changes = Rc::new(Cell::new(0));
5685        let observed = changes.clone();
5686        let _subscription = cx.update(|_, cx| {
5687            cx.subscribe(&state, move |_, event: &InputEvent, _| {
5688                if matches!(event, InputEvent::Change) {
5689                    observed.set(observed.get() + 1);
5690                }
5691            })
5692        });
5693        cx.update(|window, cx| {
5694            state.update(cx, |state, cx| {
5695                state.handle_accessibility_set_value(None, window, cx);
5696                state.handle_accessibility_focus(window, cx);
5697                assert!(state.focus_handle.is_focused(window));
5698            });
5699            window.draw(cx).clear(cx);
5700        });
5701        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5702        assert_eq!(changes.get(), 0);
5703
5704        let action = gpui::accesskit::ActionData::Value("updated🦀".into());
5705        cx.update(|window, cx| {
5706            state.update(cx, |state, cx| {
5707                state.handle_accessibility_set_value(Some(&action), window, cx)
5708            });
5709        });
5710        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5711        assert_eq!(changes.get(), 1);
5712        for disabled in [false, true] {
5713            cx.update(|window, cx| {
5714                window.blur(cx);
5715                state.update(cx, |state, cx| {
5716                    state.set_disabled(disabled, cx);
5717                    state.set_readonly(!disabled, cx);
5718                    state.handle_accessibility_focus(window, cx);
5719                    assert_eq!(state.focus_handle.is_focused(window), !disabled);
5720                    let rejected = gpui::accesskit::ActionData::Value("rejected".into());
5721                    state.handle_accessibility_set_value(Some(&rejected), window, cx);
5722                });
5723            });
5724            assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5725            assert_eq!(changes.get(), 1);
5726        }
5727        cx.update(|window, cx| {
5728            state.update(cx, |state, cx| {
5729                state.set_disabled(false, cx);
5730                state.set_readonly(false, cx);
5731                state.handle_accessibility_focus(window, cx);
5732            });
5733            window.draw(cx).clear(cx);
5734            window.dispatch_action(Box::new(Undo), cx);
5735        });
5736        assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5737        cx.update(|window, cx| {
5738            state.update(cx, |state, cx| {
5739                state.set_masked(true, window, cx);
5740                state.handle_accessibility_set_value(Some(&action), window, cx);
5741            });
5742        });
5743        assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5744    }
5745
5746    #[gpui::test]
5747    fn accessibility_set_value_preserves_exact_editor_text(cx: &mut TestAppContext) {
5748        cx.update(crate::init);
5749        let (editor, cx) = cx.add_window_view(|window, cx| {
5750            crate::input::EditorState::new(window, cx).language("rust")
5751        });
5752        let action = gpui::accesskit::ActionData::Value("(".into());
5753        cx.update(|window, cx| {
5754            editor.update(cx, |editor, cx| {
5755                editor.handle_accessibility_set_value(Some(&action), window, cx)
5756            });
5757        });
5758        assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "(");
5759    }
5760
5761    #[gpui::test]
5762    fn revealing_a_password_keeps_text_assistance_disabled(cx: &mut TestAppContext) {
5763        cx.update(crate::init);
5764        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5765            let state = cx.new(|cx| crate::input::InputState::new(window, cx).masked(true));
5766            let hidden = state.read(cx).text_input_configuration();
5767            assert!(!hidden.autocorrect && !hidden.suggestions);
5768            assert_eq!(hidden.autocapitalize, Autocapitalize::None);
5769
5770            // The component's reveal button uses this same state transition.
5771            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5772            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5773            state.update(cx, |state, cx| state.toggle_masked(window, cx));
5774            assert_eq!(state.read(cx).text_input_configuration(), hidden);
5775            gpui::EmptyView
5776        });
5777    }
5778
5779    #[gpui::test]
5780    fn text_input_configuration_follows_the_input(cx: &mut TestAppContext) {
5781        use crate::input::{InputState, TextareaState};
5782
5783        cx.update(crate::init);
5784        let mut states = None;
5785        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5786            states = Some((
5787                cx.new(|cx| InputState::new(window, cx)),
5788                cx.new(|cx| InputState::new(window, cx).masked(true)),
5789                cx.new(|cx| TextareaState::new(window, cx)),
5790                cx.new(|cx| {
5791                    InputState::new(window, cx)
5792                        .input_action(TextInputAction::Search)
5793                        .autocorrect(true)
5794                        .autocapitalize(Autocapitalize::Words)
5795                }),
5796            ));
5797            gpui::EmptyView
5798        });
5799        let (plain, masked, textarea, search) = states.unwrap();
5800
5801        cx.read(|cx| {
5802            assert_eq!(
5803                plain.read(cx).text_input_configuration(),
5804                TextInputConfiguration {
5805                    input_action: TextInputAction::Done,
5806                    ..Default::default()
5807                }
5808            );
5809            assert_eq!(
5810                masked.read(cx).text_input_configuration(),
5811                TextInputConfiguration {
5812                    input_action: TextInputAction::Done,
5813                    ..Default::default()
5814                }
5815            );
5816            assert_eq!(
5817                textarea.read(cx).text_input_configuration(),
5818                TextInputConfiguration {
5819                    input_action: TextInputAction::Enter,
5820                    ..Default::default()
5821                }
5822            );
5823            let search = search.read(cx).text_input_configuration();
5824            assert_eq!(search.input_action, TextInputAction::Search);
5825            assert_eq!(search.autocapitalize, Autocapitalize::Words);
5826            assert!(search.autocorrect);
5827            assert!(search.suggestions);
5828        });
5829    }
5830
5831    #[gpui::test]
5832    fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) {
5833        use crate::input::{CompletionProvider, EditorState};
5834        use gpui::Task;
5835        use lsp_types::{CompletionContext, CompletionResponse};
5836        use std::cell::RefCell;
5837
5838        #[derive(Default)]
5839        struct Provider {
5840            starts: RefCell<Vec<usize>>,
5841            queries: RefCell<Vec<(usize, String)>>,
5842        }
5843
5844        impl CompletionProvider for Provider {
5845            fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
5846                self.starts.borrow_mut().push(offset);
5847                true
5848            }
5849
5850            fn completions(
5851                &self,
5852                _: &Rope,
5853                offset: usize,
5854                trigger: CompletionContext,
5855                _: &mut Window,
5856                _: &mut App,
5857            ) -> Task<anyhow::Result<CompletionResponse>> {
5858                self.queries
5859                    .borrow_mut()
5860                    .push((offset, trigger.trigger_character.unwrap()));
5861                Task::ready(Ok(CompletionResponse::Array(vec![])))
5862            }
5863        }
5864
5865        cx.update(crate::init);
5866        let mut editor = None;
5867        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5868            editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
5869            gpui::EmptyView
5870        });
5871        let editor = editor.unwrap();
5872        let provider = Rc::new(Provider::default());
5873        window
5874            .update(cx, |_, window, cx| {
5875                editor.update(cx, |state, cx| {
5876                    state.extras.lsp.completion_provider = Some(provider.clone());
5877                    state
5878                        .extras
5879                        .context_menu_content
5880                        .completion
5881                        .trigger_start_offset = Some(0);
5882                    state.extras.context_menu_content.completion.query = "aa".into();
5883                    state.set_cursor_to(1);
5884                    state.add_cursor_at(0, cx);
5885
5886                    state.replace_text_in_range(None, "中", window, cx);
5887
5888                    assert_eq!(state.value(), "中a中a");
5889                    assert_eq!(provider.starts.borrow().as_slice(), &[4]);
5890                    assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
5891                });
5892            })
5893            .unwrap();
5894    }
5895
5896    #[gpui::test]
5897    fn selected_range_restores_unicode_direction_without_splitting_characters(
5898        cx: &mut TestAppContext,
5899    ) {
5900        use crate::input::EditorState;
5901        cx.update(crate::init);
5902        cx.open_window(size(px(400.), px(100.)), |window, cx| {
5903            let _state = cx.new(|cx| {
5904                let mut state = EditorState::new(window, cx).default_value("中😀a");
5905                state.set_selected_range_with_direction(3..8, true, cx);
5906                let selected = state.selected_text_range(false, window, cx).unwrap();
5907                assert_eq!(selected.range, 1..4);
5908                assert!(selected.reversed);
5909                assert_eq!(state.selected_range(), 3..8);
5910                assert!(state.is_selection_reversed());
5911                let range = state.selected_range();
5912                let reversed = state.is_selection_reversed();
5913                state.set_selected_range_with_direction(range, reversed, cx);
5914                assert!(state.is_selection_reversed());
5915                state.set_selected_range(3..8, cx);
5916                let selected = state.selected_text_range(false, window, cx).unwrap();
5917                assert_eq!(selected.range, 1..4);
5918                assert!(!selected.reversed);
5919                assert!(!state.is_selection_reversed());
5920                // A reversed Rust Range remains empty for existing callers.
5921                state.set_selected_range(Range { start: 8, end: 3 }, cx);
5922                assert_eq!(state.selected_range(), 8..8);
5923                assert!(!state.is_selection_reversed());
5924                state.set_selected_range_with_direction(4..4, true, cx);
5925                assert!(!state.is_selection_reversed());
5926                assert_eq!(
5927                    state.selected_text_range(false, window, cx).unwrap().range,
5928                    1..1
5929                );
5930                state
5931            });
5932            gpui::EmptyView
5933        });
5934    }
5935
5936    #[gpui::test]
5937    fn test_set_tokens_keeps_text_selection_and_history(cx: &mut TestAppContext) {
5938        use crate::input::{InlineToken, InlineTokenError, InputContent};
5939        let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
5940        let bold = |text: &str| {
5941            InputContent::new(text.to_string())
5942                .with_token(2..7, InlineToken::new("bold", "**b**"))
5943                .unwrap()
5944        };
5945        view.window_handle
5946            .update(cx, |_, window, cx| {
5947                view.input.update(cx, |state, cx| {
5948                    state.set_selected_range(9..9, cx);
5949                    state.insert("!", window, cx);
5950                    state.set_selected_range(9..9, cx);
5951                    state.set_tokens(bold("a **b** c!"), cx).unwrap();
5952                    assert_eq!(state.value(), "a **b** c!");
5953                    assert_eq!(state.selected_range(), 9..9);
5954                    assert_eq!(state.tokens().len(), 1);
5955
5956                    assert_eq!(
5957                        state.set_tokens(bold("a **b** c"), cx),
5958                        Err(InlineTokenError::TextMismatch)
5959                    );
5960                    state
5961                        .set_tokens(InputContent::new("a **b** c!"), cx)
5962                        .unwrap();
5963                    assert!(state.tokens().is_empty());
5964                    state.set_selected_range(4..4, cx);
5965                    assert_eq!(
5966                        state.set_tokens(bold("a **b** c!"), cx),
5967                        Err(InlineTokenError::SplitsSelection)
5968                    );
5969                    state.undo(&Undo, window, cx);
5970                    assert_eq!(state.value(), "a **b** c");
5971                });
5972            })
5973            .unwrap();
5974    }
5975
5976    #[gpui::test]
5977    fn test_set_tokens_rejects_a_token_through_any_cursor(cx: &mut TestAppContext) {
5978        use crate::input::{InlineToken, InlineTokenError, InputContent};
5979        let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
5980        view.window_handle
5981            .update(cx, |_, _, cx| {
5982                view.input.update(cx, |state, cx| {
5983                    state.set_selected_range(9..9, cx);
5984                    let id = state.selections.generate_id();
5985                    state.selections.add(CursorSelection::new(id, 4, 4));
5986                    let content = InputContent::new("a **b** c")
5987                        .with_token(2..7, InlineToken::new("bold", "**b**"))
5988                        .unwrap();
5989                    assert_eq!(
5990                        state.set_tokens(content, cx),
5991                        Err(InlineTokenError::SplitsSelection)
5992                    );
5993                    assert!(state.tokens().is_empty());
5994                });
5995            })
5996            .unwrap();
5997    }
5998
5999    #[gpui::test]
6000    fn test_set_tokens_undo_redo_replays_edits_inside_and_before_a_token(cx: &mut TestAppContext) {
6001        use crate::input::{InlineToken, InputContent};
6002        let view = InputView::build_textarea(cx, |state| state.default_value("a **** c"));
6003        let bold = |text: &str, range: Range<usize>| {
6004            InputContent::new(text.to_string())
6005                .with_token(range, InlineToken::new("bold", "**b**"))
6006                .unwrap()
6007        };
6008        view.window_handle
6009            .update(cx, |_, window, cx| {
6010                view.input.update(cx, |state, cx| {
6011                    state.set_selected_range(4..4, cx);
6012                    state.insert("b", window, cx);
6013                    state.set_selected_range(9..9, cx);
6014                    state.set_tokens(bold("a **b** c", 2..7), cx).unwrap();
6015
6016                    state.undo(&Undo, window, cx);
6017                    assert_eq!(state.value(), "a **** c");
6018                    assert!(state.tokens().is_empty());
6019                    state.redo(&Redo, window, cx);
6020                    assert_eq!(state.value(), "a **b** c");
6021                    assert!(state.tokens().is_empty());
6022                    assert_eq!(state.selected_range(), 5..5);
6023
6024                    state.set_selected_range(0..0, cx);
6025                    state.insert("z", window, cx);
6026                    state.set_selected_range(10..10, cx);
6027                    state.set_tokens(bold("za **b** c", 3..8), cx).unwrap();
6028
6029                    state.undo(&Undo, window, cx);
6030                    assert_eq!(state.value(), "a **b** c");
6031                    let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
6032                    assert_eq!(ranges, vec![2..7]);
6033                    state.redo(&Redo, window, cx);
6034                    assert_eq!(state.value(), "za **b** c");
6035                    let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
6036                    assert_eq!(ranges, vec![3..8]);
6037                });
6038            })
6039            .unwrap();
6040    }
6041
6042    #[gpui::test]
6043    fn test_set_tokens_refreshes_the_token_layout(cx: &mut TestAppContext) {
6044        use crate::input::{InlineToken, InputContent};
6045        let view = InputView::build_textarea(cx, |state| state.default_value("@a x @a y"));
6046        let mention = || InlineToken::new("a", "@a");
6047        view.window_handle
6048            .update(cx, |_, _, cx| {
6049                view.input.update(cx, |state, cx| {
6050                    let content = InputContent::new("@a x @a y")
6051                        .with_token(0..2, mention())
6052                        .and_then(|content| content.with_token(5..7, mention()))
6053                        .unwrap();
6054                    state.set_tokens(content, cx).unwrap();
6055                });
6056            })
6057            .unwrap();
6058        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6059        visual.update(|window, cx| window.draw(cx).clear(cx));
6060        view.input.update(&mut visual, |state, cx| {
6061            let content = InputContent::new("@a x @a y")
6062                .with_token(5..7, mention())
6063                .unwrap();
6064            state.set_tokens(content, cx).unwrap();
6065        });
6066        visual.update(|window, cx| window.draw(cx).clear(cx));
6067        view.input.read_with(&visual, |state, _| {
6068            let cache = state.token_layout_cache.as_ref().unwrap();
6069            let ranges: Vec<_> = cache
6070                .metrics
6071                .iter()
6072                .map(|(range, _)| range.clone())
6073                .collect();
6074            assert_eq!(ranges, vec![5..7]);
6075        });
6076    }
6077
6078    #[gpui::test]
6079    fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
6080        use crate::input::{InlineToken, InlineTokenPresentation};
6081        let width = Rc::new(Cell::new(4000.));
6082        let render_width = width.clone();
6083        let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
6084        view.window_handle
6085            .update(cx, |_, window, cx| {
6086                view.input.update(cx, |state, cx| {
6087                    state
6088                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6089                        .unwrap();
6090                    state
6091                        .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
6092                        .unwrap();
6093                    state.set_token_presentation(
6094                        InlineTokenPresentation::default()
6095                            .token(move |_, _, _| div().w(px(render_width.get()))),
6096                    );
6097                });
6098            })
6099            .unwrap();
6100        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6101        visual.update(|window, cx| window.draw(cx).clear(cx));
6102        view.input.read_with(&visual, |state, _| {
6103            assert_eq!(state.display_map.wrap_row_count(), 2);
6104            let first = state.range_to_bounds(&(0..2)).unwrap();
6105            let second = state.range_to_bounds(&(2..4)).unwrap();
6106            assert!(second.origin.y > first.origin.y);
6107            assert_eq!(
6108                state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
6109                2
6110            );
6111        });
6112        width.set(100.);
6113        view.input.update(&mut visual, |_, cx| cx.notify());
6114        visual.update(|window, cx| window.draw(cx).clear(cx));
6115        view.input.read_with(&visual, |state, _| {
6116            assert_eq!(state.display_map.wrap_row_count(), 1)
6117        });
6118    }
6119
6120    #[gpui::test]
6121    fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
6122        use crate::input::{InlineToken, InlineTokenPresentation};
6123        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6124        let target = view.input.clone();
6125        view.window_handle
6126            .update(cx, |_, window, cx| {
6127                view.input.update(cx, |state, cx| {
6128                    state
6129                        .replace_range_with_token(
6130                            7..13,
6131                            InlineToken::new("a", "@alice"),
6132                            window,
6133                            cx,
6134                        )
6135                        .unwrap();
6136                    state.set_token_presentation(
6137                        InlineTokenPresentation::default()
6138                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6139                            .on_token_click(move |_, window, cx| {
6140                                target.update(cx, |state, cx| {
6141                                    state.set_value("activated", window, cx)
6142                                })
6143                            }),
6144                    );
6145                    state.focus(window, cx);
6146                    state.set_selected_range(7..13, cx);
6147                });
6148            })
6149            .unwrap();
6150        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6151        visual.update(|window, cx| window.draw(cx).clear(cx));
6152        visual.update(|window, cx| {
6153            let state = view.input.read(cx);
6154            let bounds = state.range_to_bounds(&(7..13)).unwrap();
6155            assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
6156            let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
6157            let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
6158            assert_eq!((left, right), (7, 13));
6159            window.dispatch_action(Box::new(ActivateToken), cx);
6160        });
6161        visual.run_until_parked();
6162        view.input.read_with(&visual, |state, _| {
6163            assert_eq!(state.value().as_ref(), "activated")
6164        });
6165    }
6166
6167    #[gpui::test]
6168    fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
6169        use crate::input::InlineToken;
6170        cx.update(crate::init);
6171        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6172        view.window_handle
6173            .update(cx, |_, window, cx| {
6174                view.input.update(cx, |state, cx| {
6175                    state
6176                        .replace_range_with_token(
6177                            7..13,
6178                            InlineToken::new("a", "@alice"),
6179                            window,
6180                            cx,
6181                        )
6182                        .unwrap();
6183                    state.set_selected_range(0..0, cx);
6184                });
6185            })
6186            .unwrap();
6187        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6188        visual.update(|window, cx| window.draw(cx).clear(cx));
6189        let bounds = view
6190            .input
6191            .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
6192        visual.simulate_click(bounds.center(), gpui::Modifiers::default());
6193        visual.run_until_parked();
6194        view.input.read_with(&visual, |state, _| {
6195            assert_eq!(state.selected_range(), 7..13, "a click selects the token");
6196        });
6197    }
6198
6199    #[gpui::test]
6200    fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) {
6201        use crate::input::{InlineToken, InlineTokenPresentation};
6202        use gpui::{Bounds, point, px, size};
6203        cx.update(crate::init);
6204        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6205        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6206        view.window_handle
6207            .update(cx, |_, window, cx| {
6208                view.input.update(cx, |state, cx| {
6209                    state
6210                        .replace_range_with_token(
6211                            7..13,
6212                            InlineToken::new("a", "@alice"),
6213                            window,
6214                            cx,
6215                        )
6216                        .unwrap();
6217                    state.set_token_presentation(
6218                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6219                    );
6220                    state.set_selected_range(0..0, cx);
6221                });
6222            })
6223            .unwrap();
6224        view.window_handle
6225            .update(cx, |_, _, cx| {
6226                view.input.update(cx, |state, _| {
6227                    let (_, entered) = state
6228                        .token_hover(7, bounds, true, None)
6229                        .expect("hover enters an enabled token");
6230                    assert!(entered.is_hovered());
6231                    assert_eq!(entered.token().id().as_ref(), "a");
6232                    assert_eq!(entered.range(), 7..13);
6233                    assert_eq!(entered.bounds(), bounds);
6234                    let (_, left) = state
6235                        .token_hover(7, bounds, false, None)
6236                        .expect("hover leaves the same token");
6237                    assert!(!left.is_hovered());
6238                    assert_eq!(state.selected_range(), 0..0, "hover never selects");
6239                    assert!(state.token_hover(99, bounds, true, None).is_none());
6240                });
6241            })
6242            .unwrap();
6243
6244        // Disabled tokens suppress hover, matching click; readonly allows it.
6245        view.window_handle
6246            .update(cx, |_, _, cx| {
6247                view.input.update(cx, |state, cx| {
6248                    state.set_disabled(true, cx);
6249                });
6250            })
6251            .unwrap();
6252        view.window_handle
6253            .update(cx, |_, _, cx| {
6254                view.input.update(cx, |state, _| {
6255                    assert!(state.token_hover(7, bounds, true, None).is_none())
6256                })
6257            })
6258            .unwrap();
6259        view.window_handle
6260            .update(cx, |_, _, cx| {
6261                view.input.update(cx, |state, cx| {
6262                    state.set_disabled(false, cx);
6263                    state.set_readonly(true, cx);
6264                });
6265            })
6266            .unwrap();
6267        view.window_handle
6268            .update(cx, |_, _, cx| {
6269                view.input.update(cx, |state, _| {
6270                    assert!(state.token_hover(7, bounds, true, None).is_some())
6271                })
6272            })
6273            .unwrap();
6274
6275        // Without a hover listener there is no hover activation.
6276        view.window_handle
6277            .update(cx, |_, _, cx| {
6278                view.input.update(cx, |state, _| {
6279                    state.set_token_presentation(InlineTokenPresentation::default());
6280                });
6281            })
6282            .unwrap();
6283        view.window_handle
6284            .update(cx, |_, _, cx| {
6285                view.input.update(cx, |state, _| {
6286                    assert!(state.token_hover(7, bounds, true, None).is_none())
6287                })
6288            })
6289            .unwrap();
6290    }
6291
6292    #[gpui::test]
6293    fn test_inline_token_hover_exit_delivered_when_token_removed(cx: &mut TestAppContext) {
6294        use crate::input::{InlineToken, InlineTokenPresentation};
6295        use std::cell::RefCell;
6296        use std::rc::Rc;
6297        cx.update(crate::init);
6298        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6299        let events: Rc<RefCell<Vec<(SharedString, bool)>>> = Rc::new(RefCell::new(Vec::new()));
6300        let sink = events.clone();
6301        view.window_handle
6302            .update(cx, |_, window, cx| {
6303                view.input.update(cx, |state, cx| {
6304                    state
6305                        .replace_range_with_token(
6306                            7..13,
6307                            InlineToken::new("a", "@alice"),
6308                            window,
6309                            cx,
6310                        )
6311                        .unwrap();
6312                    state.set_token_presentation(
6313                        InlineTokenPresentation::default()
6314                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6315                            .on_token_hover(move |event, _, _| {
6316                                sink.borrow_mut()
6317                                    .push((event.token().id().clone(), event.is_hovered()));
6318                            }),
6319                    );
6320                });
6321            })
6322            .unwrap();
6323        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6324        visual.update(|window, cx| window.draw(cx).clear(cx));
6325        let known_bounds = view.input.read_with(&visual, |state, _| {
6326            state
6327                .token_bounds
6328                .get(&7)
6329                .copied()
6330                .expect("placed token bounds")
6331        });
6332        visual.simulate_mouse_move(known_bounds.center(), None, gpui::Modifiers::default());
6333        visual.run_until_parked();
6334        visual.update(|window, cx| window.draw(cx).clear(cx));
6335        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6336
6337        // Remove the token while the pointer is still over its stale row: the
6338        // exit must fire even though the token element that owns the hover
6339        // mask is gone.
6340        view.window_handle
6341            .update(cx, |_, window, cx| {
6342                view.input
6343                    .update(cx, |state, cx| state.set_value("no tokens", window, cx));
6344            })
6345            .unwrap();
6346        visual.run_until_parked();
6347        visual.update(|window, cx| window.draw(cx).clear(cx));
6348        assert_eq!(
6349            events.borrow().as_slice(),
6350            &[("a".into(), true), ("a".into(), false)]
6351        );
6352    }
6353
6354    #[gpui::test]
6355    fn test_inline_token_hover_bounds_stay_single_row_at_wrap_boundary(cx: &mut TestAppContext) {
6356        use crate::input::{InlineToken, InlineTokenPresentation};
6357        cx.update(crate::init);
6358        let view = InputView::build_textarea(cx, |state| {
6359            state
6360                .rows(4)
6361                .default_value("aaaa bbbb cccc dddd @alice eeee ffff")
6362        });
6363        view.window_handle
6364            .update(cx, |_, window, cx| {
6365                view.input.update(cx, |state, cx| {
6366                    state
6367                        .replace_range_with_token(
6368                            20..26,
6369                            InlineToken::new("a", "@alice"),
6370                            window,
6371                            cx,
6372                        )
6373                        .unwrap();
6374                    state.set_token_presentation(
6375                        InlineTokenPresentation::default()
6376                            .token(|_, _, _| div().w(px(60.)).h(px(20.))),
6377                    );
6378                });
6379            })
6380            .unwrap();
6381        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6382        visual.update(|window, cx| window.draw(cx).clear(cx));
6383        let (placed, ranged, line_height) = view.input.read_with(&visual, |state, _| {
6384            (
6385                state
6386                    .token_bounds
6387                    .get(&20)
6388                    .copied()
6389                    .expect("placed token bounds"),
6390                state.range_to_bounds(&(20..26)),
6391                state.last_layout.as_ref().unwrap().line_height,
6392            )
6393        });
6394        // The laid-out element always occupies exactly one row of height, even
6395        // when the range-extent path resolves the same end boundary onto the
6396        // next visual row at a soft-wrap edge.
6397        assert!(placed.size.height <= line_height + px(1.), "{placed:?}");
6398        assert!(
6399            placed.size.width <= px(61.) && placed.size.width > px(0.),
6400            "{placed:?}"
6401        );
6402        if let Some(ranged) = ranged {
6403            assert!(
6404                ranged.size.height >= placed.size.height - px(1.),
6405                "{ranged:?} vs {placed:?}"
6406            );
6407        }
6408    }
6409
6410    #[gpui::test]
6411    fn test_inline_token_hover_same_offset_replacement_exits_predecessor(cx: &mut TestAppContext) {
6412        use crate::input::{InlineToken, InlineTokenPresentation};
6413        use std::{cell::RefCell, rc::Rc};
6414        cx.update(crate::init);
6415        let view = InputView::build(cx, |state| state.default_value("@alice!"));
6416        let events = Rc::new(RefCell::new(Vec::new()));
6417        let sink = events.clone();
6418        view.window_handle
6419            .update(cx, |_, window, cx| {
6420                view.input.update(cx, |state, cx| {
6421                    state
6422                        .replace_range_with_token(0..6, InlineToken::new("a", "@alice"), window, cx)
6423                        .unwrap();
6424                    state.set_token_presentation(
6425                        InlineTokenPresentation::default()
6426                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6427                            .on_token_hover(move |event, _, _| {
6428                                sink.borrow_mut()
6429                                    .push((event.token().id().clone(), event.is_hovered()));
6430                            }),
6431                    );
6432                });
6433            })
6434            .unwrap();
6435        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6436        visual.update(|window, cx| window.draw(cx).clear(cx));
6437        let bounds = view
6438            .input
6439            .read_with(&visual, |state, _| state.token_bounds[&0]);
6440        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6441        visual.run_until_parked();
6442        visual.update(|window, cx| window.draw(cx).clear(cx));
6443        assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6444
6445        view.window_handle
6446            .update(cx, |_, window, cx| {
6447                view.input.update(cx, |state, cx| {
6448                    state
6449                        .replace_range_with_token(0..6, InlineToken::new("b", "@alice"), window, cx)
6450                        .unwrap();
6451                });
6452            })
6453            .unwrap();
6454        visual.run_until_parked();
6455        visual.update(|window, cx| window.draw(cx).clear(cx));
6456        visual.simulate_mouse_move(
6457            bounds.center() + gpui::point(px(1.), px(0.)),
6458            None,
6459            gpui::Modifiers::default(),
6460        );
6461        visual.run_until_parked();
6462        visual.update(|window, cx| window.draw(cx).clear(cx));
6463        assert_eq!(
6464            events.borrow().as_slice(),
6465            &[("a".into(), true), ("a".into(), false), ("b".into(), true)]
6466        );
6467        // Disabling keeps the token mounted; re-enabling must reset GPUI's
6468        // retained hover state even with a stationary pointer.
6469        view.input
6470            .update(&mut visual, |state, cx| state.set_disabled(true, cx));
6471        visual.update(|window, cx| window.draw(cx).clear(cx));
6472        visual.run_until_parked();
6473        assert_eq!(events.borrow().last(), Some(&("b".into(), false)));
6474        view.input
6475            .update(&mut visual, |state, cx| state.set_disabled(false, cx));
6476        visual.update(|window, cx| window.draw(cx).clear(cx));
6477        visual.run_until_parked();
6478        visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6479        visual.run_until_parked();
6480        assert_eq!(
6481            events.borrow().as_slice(),
6482            &[
6483                ("a".into(), true),
6484                ("a".into(), false),
6485                ("b".into(), true),
6486                ("b".into(), false),
6487                ("b".into(), true)
6488            ]
6489        );
6490        visual.simulate_mouse_move(
6491            bounds.bottom_right() + gpui::point(px(10.), px(10.)),
6492            None,
6493            gpui::Modifiers::default(),
6494        );
6495        visual.run_until_parked();
6496        assert_eq!(
6497            events.borrow().as_slice(),
6498            &[
6499                ("a".into(), true),
6500                ("a".into(), false),
6501                ("b".into(), true),
6502                ("b".into(), false),
6503                ("b".into(), true),
6504                ("b".into(), false)
6505            ]
6506        );
6507    }
6508
6509    #[gpui::test]
6510    fn test_inline_token_hover_older_exit_keeps_newer_snapshot(cx: &mut TestAppContext) {
6511        use crate::input::{InlineToken, InlineTokenPresentation};
6512        use gpui::{Bounds, point, px, size};
6513        cx.update(crate::init);
6514        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6515        let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6516        view.window_handle
6517            .update(cx, |_, window, cx| {
6518                view.input.update(cx, |state, cx| {
6519                    state
6520                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6521                        .unwrap();
6522                    state
6523                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6524                        .unwrap();
6525                    state.set_token_presentation(
6526                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6527                    );
6528                    // The pointer moves A -> B; GPUI dispatches B's enter
6529                    // before A's exit.
6530                    state
6531                        .token_hover(0, bounds, true, None)
6532                        .expect("hover enters A");
6533                    state
6534                        .token_hover(3, bounds, true, None)
6535                        .expect("hover enters B");
6536                    let (_, exit_a) = state.token_hover(0, bounds, false, None).expect("A exits");
6537                    assert!(!exit_a.is_hovered());
6538                    // B's snapshot must survive A's late exit.
6539                    assert_eq!(
6540                        state
6541                            .hovered_token
6542                            .as_ref()
6543                            .expect("B still hovered")
6544                            .span
6545                            .token()
6546                            .id()
6547                            .as_ref(),
6548                        "b"
6549                    );
6550                    // Removing B afterwards still produces B's reconciled exit.
6551                    state.set_value("no tokens", window, cx);
6552                    state.token_bounds.clear();
6553                    let (listener, exit_b) = state.reconcile_token_hover().expect("B must exit");
6554                    assert!(!exit_b.is_hovered());
6555                    assert_eq!(exit_b.token().id().as_ref(), "b");
6556                    drop(listener);
6557                });
6558            })
6559            .unwrap();
6560    }
6561
6562    #[gpui::test]
6563    fn test_inline_token_hover_late_exit_matches_replaced_token(cx: &mut TestAppContext) {
6564        use crate::input::{InlineToken, InlineTokenPresentation};
6565        cx.update(crate::init);
6566        let view = InputView::build(cx, |state| state.default_value("@a"));
6567        view.window_handle
6568            .update(cx, |_, window, cx| {
6569                view.input.update(cx, |state, cx| {
6570                    let a = InlineToken::new("a", "@a");
6571                    let b = InlineToken::new("b", "@a");
6572                    state
6573                        .replace_range_with_token(0..2, a.clone(), window, cx)
6574                        .unwrap();
6575                    state.set_token_presentation(
6576                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6577                    );
6578                    let bounds = gpui::Bounds::default();
6579                    state.token_hover(0, bounds, true, Some(&a)).unwrap();
6580                    state
6581                        .replace_range_with_token(0..2, b.clone(), window, cx)
6582                        .unwrap();
6583                    state.token_hover(0, bounds, true, Some(&b)).unwrap();
6584                    let (_, exit_a) = state.token_hover(0, bounds, false, Some(&a)).unwrap();
6585                    assert_eq!(exit_a.token().id().as_ref(), "a");
6586                    assert_eq!(state.hovered_token.as_ref().unwrap().span.token(), &b);
6587                    let (_, exit_b) = state.token_hover(0, bounds, false, Some(&b)).unwrap();
6588                    assert_eq!(exit_b.token().id().as_ref(), "b");
6589                    assert!(state.pending_token_hover_exits.is_empty());
6590                });
6591            })
6592            .unwrap();
6593    }
6594
6595    #[gpui::test]
6596    fn test_inline_token_hover_exit_keeps_entry_utf16_after_edit(cx: &mut TestAppContext) {
6597        use crate::input::{InlineToken, InlineTokenPresentation};
6598        use gpui::EntityInputHandler as _;
6599        cx.update(crate::init);
6600        let view = InputView::build(cx, |state| state.default_value("🙂 @a"));
6601        view.window_handle
6602            .update(cx, |_, window, cx| {
6603                view.input.update(cx, |state, cx| {
6604                    state
6605                        .replace_range_with_token(5..7, InlineToken::new("a", "@a"), window, cx)
6606                        .unwrap();
6607                    state.set_token_presentation(
6608                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6609                    );
6610                    let bounds = gpui::Bounds::default();
6611                    let (_, enter) = state.token_hover(5, bounds, true, None).unwrap();
6612                    assert_eq!(enter.range_utf16(), (3, 5));
6613                    state.replace_text_in_range(Some(0..2), "abcd", window, cx);
6614                    assert_eq!(state.token_spans()[0].range(), 5..7);
6615                    let (_, exit) = state.token_hover(5, bounds, false, None).unwrap();
6616                    assert_eq!(exit.range_utf16(), (3, 5));
6617                });
6618            })
6619            .unwrap();
6620    }
6621
6622    #[gpui::test]
6623    fn test_text_length_utf16(cx: &mut TestAppContext) {
6624        use gpui::EntityInputHandler as _;
6625        cx.update(crate::init);
6626        // "🙂" is 2 UTF-16 units and 4 bytes; "й" is 1 UTF-16 unit and 2 bytes.
6627        let view = InputView::build(cx, |state| state.default_value("🙂 й"));
6628        view.window_handle
6629            .update(cx, |_, window, cx| {
6630                view.input.update(cx, |state, cx| {
6631                    assert_eq!(state.text_length_utf16(window, cx), Some(4));
6632                    state.replace_text_in_range(None, "ab", window, cx);
6633                    assert_eq!(state.text_length_utf16(window, cx), Some(6));
6634                });
6635            })
6636            .unwrap();
6637    }
6638
6639    #[gpui::test]
6640    fn test_set_selected_text_range(cx: &mut TestAppContext) {
6641        use gpui::EntityInputHandler as _;
6642        cx.update(crate::init);
6643        // "🙂" is 2 UTF-16 units and 4 bytes.
6644        let view = InputView::build(cx, |state| state.default_value("🙂 hello world"));
6645        view.window_handle
6646            .update(cx, |_, window, cx| {
6647                view.input.update(cx, |state, cx| {
6648                    fn selection(
6649                        state: &mut InputBaseState<InputMode>,
6650                        window: &mut Window,
6651                        cx: &mut Context<InputBaseState<InputMode>>,
6652                    ) -> (Range<usize>, bool) {
6653                        let selection = state.selected_text_range(false, window, cx).unwrap();
6654                        (selection.range, selection.reversed)
6655                    }
6656
6657                    state.set_selected_text_range(3..8, window, cx);
6658                    assert_eq!(state.selected_range(), 5..10);
6659                    assert_eq!(selection(state, window, cx), (3..8, false));
6660
6661                    // Dragging the end handle keeps the selection forward.
6662                    state.set_selected_text_range(3..14, window, cx);
6663                    assert_eq!(selection(state, window, cx), (3..14, false));
6664                    assert_eq!(state.cursor(), 16);
6665
6666                    // Dragging the start handle reverses it, so the start is the cursor.
6667                    state.set_selected_text_range(9..14, window, cx);
6668                    assert_eq!(selection(state, window, cx), (9..14, true));
6669                    assert_eq!(state.cursor(), 11);
6670
6671                    // A repeated range keeps its direction.
6672                    state.set_selected_text_range(9..14, window, cx);
6673                    assert_eq!(selection(state, window, cx), (9..14, true));
6674
6675                    // Out of range clamps; a backwards range is normalized.
6676                    state.set_selected_text_range(100..9, window, cx);
6677                    assert_eq!(selection(state, window, cx), (9..14, true));
6678
6679                    // Either handle can cross the stationary end.
6680                    state.set_selected_text_range(3..8, window, cx);
6681                    state.set_selected_text_range(2..3, window, cx);
6682                    assert_eq!(selection(state, window, cx), (2..3, true));
6683                    assert_eq!(state.cursor(), 4);
6684                    state.set_selected_text_range(3..8, window, cx);
6685                    state.set_selected_text_range(8..9, window, cx);
6686                    assert_eq!(selection(state, window, cx), (8..9, false));
6687                    assert_eq!(state.cursor(), 11);
6688
6689                    // Collapsing places a forward cursor and leaves the text alone.
6690                    state.set_selected_text_range(2..2, window, cx);
6691                    assert_eq!(selection(state, window, cx), (2..2, false));
6692                    assert_eq!(state.value(), "🙂 hello world");
6693                });
6694            })
6695            .unwrap();
6696    }
6697
6698    #[gpui::test]
6699    fn test_inline_token_hover_callback_edit_preserves_both_exits(cx: &mut TestAppContext) {
6700        use crate::input::{InlineToken, InlineTokenPresentation};
6701        cx.update(crate::init);
6702        let view = InputView::build(cx, |state| state.default_value("@a @b"));
6703        view.window_handle
6704            .update(cx, |_, window, cx| {
6705                view.input.update(cx, |state, cx| {
6706                    state
6707                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6708                        .unwrap();
6709                    state
6710                        .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6711                        .unwrap();
6712                    state.set_token_presentation(
6713                        InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6714                    );
6715                    let bounds = gpui::Bounds::default();
6716                    state.token_hover(0, bounds, true, None).unwrap();
6717                    state.token_hover(3, bounds, true, None).unwrap();
6718                    // Model an edit in B's enter callback before A's queued exit.
6719                    state.set_value("gone", window, cx);
6720                    let (_, exit_a) = state.token_hover(0, bounds, false, None).unwrap();
6721                    assert_eq!(exit_a.token().id().as_ref(), "a");
6722                    let (_, exit_b) = state.reconcile_token_hover().unwrap();
6723                    assert_eq!(exit_b.token().id().as_ref(), "b");
6724                    assert!(state.token_hover(0, bounds, false, None).is_none());
6725                    assert!(state.reconcile_token_hover().is_none());
6726                });
6727            })
6728            .unwrap();
6729    }
6730
6731    #[gpui::test]
6732    fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
6733        let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
6734        view.window_handle
6735            .update(cx, |_, window, cx| {
6736                view.input.update(cx, |state, cx| {
6737                    let token =
6738                        crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
6739                    state
6740                        .replace_range_with_token(4..10, token.clone(), window, cx)
6741                        .unwrap();
6742                    assert_eq!(state.value().as_ref(), "问 @alice!");
6743                    assert_eq!(state.tokens()[0].range(), 4..10);
6744                    assert_eq!(state.next_end_of_word_at(4), 10);
6745                    assert_eq!(state.previous_start_of_word_at(10), 4);
6746                    state.undo(&Undo, window, cx);
6747                    assert!(
6748                        state.tokens().is_empty(),
6749                        "identity-only association is undoable"
6750                    );
6751                    assert_eq!(state.value().as_ref(), "问 @alice!");
6752                    state.redo(&Redo, window, cx);
6753                    assert_eq!(state.tokens()[0].token(), &token);
6754                    state.set_selected_range(6..7, cx);
6755                    assert_eq!(state.selected_range(), 4..10);
6756                    state.replace("", window, cx);
6757                    assert_eq!(state.value().as_ref(), "问 !");
6758                    assert!(state.tokens().is_empty());
6759                    state.undo(&Undo, window, cx);
6760                    assert_eq!(state.tokens()[0].token(), &token);
6761                    state.set_selected_range(0..0, cx);
6762                    state.replace("🙂", window, cx);
6763                    assert_eq!(state.tokens()[0].range(), 8..14);
6764                    state.undo(&Undo, window, cx);
6765                    assert_eq!(state.tokens()[0].range(), 4..10);
6766                    let before = state.content();
6767                    state
6768                        .replace_range_with_token(0..0, token.clone(), window, cx)
6769                        .expect("the same reference may occur twice");
6770                    assert_eq!(state.value().as_ref(), "@alice问 @alice!");
6771                    assert_eq!(state.tokens().len(), 2);
6772                    assert_eq!(state.tokens()[1].token(), &token);
6773                    state.undo(&Undo, window, cx);
6774                    assert_eq!(state.content(), before);
6775                    state.set_value(before.text().clone(), window, cx);
6776                    assert!(state.tokens().is_empty());
6777                    assert!(!state.undo_manager.has_undos());
6778                });
6779            })
6780            .unwrap();
6781    }
6782
6783    #[gpui::test]
6784    fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
6785        use crate::input::{InlineToken, InlineTokenError, InputContent};
6786        let view = InputView::build_textarea(cx, |state| state);
6787        view.window_handle
6788            .update(cx, |_, window, cx| {
6789                view.input.update(cx, |state, cx| {
6790                    let content = InputContent::new("@a@b\n后面")
6791                        .with_token(0..2, InlineToken::new("a", "@a"))
6792                        .unwrap()
6793                        .with_token(2..4, InlineToken::new("b", "@b"))
6794                        .unwrap();
6795                    state.set_value(content.clone(), window, cx);
6796                    state.set_selected_range(2..2, cx);
6797                    assert_eq!(state.previous_boundary(2), 0);
6798                    assert_eq!(state.next_boundary(2), 4);
6799                    state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
6800                    assert_eq!(state.value().as_ref(), "中@b\n后面");
6801                    assert_eq!(state.tokens().len(), 1);
6802                    assert_eq!(
6803                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6804                        Err(InlineTokenError::CompositionActive)
6805                    );
6806                    state.replace_text_in_range(None, "中文", window, cx);
6807                    state.undo(&Undo, window, cx);
6808                    assert_eq!(state.content(), content);
6809                    state.redo(&Redo, window, cx);
6810                    assert_eq!(state.value().as_ref(), "中文@b\n后面");
6811                    state.undo(&Undo, window, cx);
6812                    state.replace_all("plain", window, cx);
6813                    assert!(state.tokens().is_empty());
6814                    state.undo(&Undo, window, cx);
6815                    assert_eq!(state.content(), content);
6816                });
6817            })
6818            .unwrap();
6819        let view = InputView::build(cx, |state| state);
6820        view.window_handle
6821            .update(cx, |_, window, cx| {
6822                view.input.update(cx, |state, cx| {
6823                    assert_eq!(
6824                        InputContent::new("a\u{301}")
6825                            .with_token(0..1, InlineToken::new("bad", "a"))
6826                            .err(),
6827                        Some(InlineTokenError::InvalidBoundary)
6828                    );
6829                    assert_eq!(
6830                        InputContent::new("@a@a")
6831                            .with_token(0..2, InlineToken::new("a", "@a"))
6832                            .unwrap()
6833                            .with_token(1..3, InlineToken::new("x", "a@"))
6834                            .err(),
6835                        Some(InlineTokenError::OverlappingTokens)
6836                    );
6837                    state
6838                        .replace_with_token(InlineToken::new("a", "@a"), window, cx)
6839                        .unwrap();
6840                    let before = state.content();
6841                    state.set_masked(true, window, cx);
6842                    assert!(!state.tokens_visible());
6843                    assert_eq!(
6844                        state.replace_with_token(InlineToken::new("b", "b"), window, cx),
6845                        Err(InlineTokenError::UnsupportedMode)
6846                    );
6847                    assert_eq!(state.content(), before);
6848                    state.undo(&Undo, window, cx);
6849                    assert!(state.tokens().is_empty());
6850                    state.redo(&Redo, window, cx);
6851                    assert_eq!(state.content(), before);
6852                    assert!(!state.tokens_visible());
6853                });
6854            })
6855            .unwrap();
6856    }
6857
6858    use crate::theme::Theme;
6859    use gpui::{TestAppContext, VisualTestContext, size};
6860
6861    use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TabSize, TextareaMode};
6862
6863    fn set_test_syntax_provider(
6864        provider: Rc<dyn crate::input::SyntaxContextProvider>,
6865        cx: &mut App,
6866    ) {
6867        struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
6868        impl crate::input::LanguageProvider for TestLanguages {
6869            fn syntax_context_provider(
6870                &self,
6871                _: &str,
6872            ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
6873                Some(self.0.clone())
6874            }
6875        }
6876        crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
6877    }
6878
6879    struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
6880
6881    impl<M: InputModeKind> Render for TestRoot<M> {
6882        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6883            div().size_full().child(self.0.clone())
6884        }
6885    }
6886
6887    struct InputView<M: InputModeKind> {
6888        input: Entity<InputBaseState<M>>,
6889        window_handle: gpui::WindowHandle<TestRoot<M>>,
6890    }
6891
6892    /// Helper to open a state of one mode in a window for testing.
6893    impl<M: InputModeKind> InputView<M> {
6894        fn build_with(
6895            cx: &mut TestAppContext,
6896            make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
6897            + 'static,
6898        ) -> Self {
6899            let mut input: Option<Entity<InputBaseState<M>>> = None;
6900
6901            let window = cx.update(|cx| {
6902                cx.open_window(Default::default(), |window, cx| {
6903                    // Set up the theme first
6904                    cx.set_global(Theme::default());
6905                    // Initialize input keybindings
6906                    super::super::init(cx);
6907
6908                    input = Some(cx.new(|cx| make(window, cx)));
6909
6910                    cx.new(|_| TestRoot(input.clone().unwrap()))
6911                })
6912                .unwrap()
6913            });
6914
6915            Self {
6916                input: input.unwrap(),
6917                window_handle: window,
6918            }
6919        }
6920    }
6921
6922    impl InputView<EditorMode> {
6923        /// An editor state, for the tests that exercise code-editor behavior.
6924        fn new(cx: &mut TestAppContext) -> Self {
6925            Self::build_editor(cx, |state| state)
6926        }
6927
6928        fn build_editor(
6929            cx: &mut TestAppContext,
6930            f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
6931        ) -> Self {
6932            Self::build_with(cx, move |window, cx| {
6933                f(crate::input::EditorState::new(window, cx).language("sql"))
6934            })
6935        }
6936    }
6937
6938    impl InputView<TextareaMode> {
6939        fn build_textarea(
6940            cx: &mut TestAppContext,
6941            f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
6942        ) -> Self {
6943            Self::build_with(cx, move |window, cx| {
6944                f(crate::input::TextareaState::new(window, cx))
6945            })
6946        }
6947    }
6948
6949    impl InputView<InputMode> {
6950        /// A single-line state, the default these tests were written against.
6951        fn build(
6952            cx: &mut TestAppContext,
6953            f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
6954        ) -> Self {
6955            Self::build_with(cx, move |window, cx| {
6956                f(crate::input::InputState::new(window, cx))
6957            })
6958        }
6959    }
6960
6961    /// Sends one trackpad packet straight to the input.
6962    fn swipe<M: InputModeKind>(
6963        view: &InputView<M>,
6964        cx: &mut VisualTestContext,
6965        dy: f32,
6966        phase: gpui::TouchPhase,
6967    ) {
6968        cx.update(|window, cx| {
6969            view.input.update(cx, |state, cx| {
6970                state.on_scroll_wheel(
6971                    &ScrollEvent {
6972                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(dy))),
6973                        touch_phase: phase,
6974                        ..Default::default()
6975                    },
6976                    window,
6977                    cx,
6978                )
6979            })
6980        });
6981    }
6982
6983    fn long_text() -> String {
6984        (0..60)
6985            .map(|n| format!("line {n}"))
6986            .collect::<Vec<_>>()
6987            .join("\n")
6988    }
6989
6990    #[gpui::test]
6991    fn test_scroll_bounce_stretches_past_the_end_and_springs_back(cx: &mut TestAppContext) {
6992        use gpui::TouchPhase::{Ended, Moved, Started};
6993
6994        let view = InputView::build_textarea(cx, |state| {
6995            state.scroll_bounce(true).default_value(long_text())
6996        });
6997        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
6998        cx.update(|window, cx| window.draw(cx).clear(cx));
6999        let drawn_at = |cx: &mut VisualTestContext| {
7000            view.input
7001                .read_with(cx, |state, _| state.last_bounds.unwrap().origin.y)
7002        };
7003
7004        swipe(&view, &mut cx, -20., Started);
7005        swipe(&view, &mut cx, -100_000., Moved);
7006        let (end, stretch) = view.input.read_with(&cx, |state, _| {
7007            (state.scroll_handle.offset().y, state.overscroll.offset())
7008        });
7009        assert!(end < px(0.), "the text scrolled to its end");
7010        assert!(stretch < 0., "the rest stretched the edge: {stretch}");
7011        cx.update(|window, cx| window.draw(cx).clear(cx));
7012        let stretched_at = drawn_at(&mut cx);
7013
7014        swipe(&view, &mut cx, 0., Ended);
7015        for _ in 0..120 {
7016            cx.executor()
7017                .advance_clock(std::time::Duration::from_millis(16));
7018            cx.update(|window, cx| window.draw(cx).clear(cx));
7019        }
7020        view.input.read_with(&cx, |state, _| {
7021            assert_eq!(state.overscroll.offset(), 0., "the edge sprang back");
7022            assert_eq!(
7023                state.scroll_handle.offset().y,
7024                end,
7025                "scrolling stayed exact"
7026            );
7027        });
7028        let moved = (stretched_at - drawn_at(&mut cx)).as_f32();
7029        assert!(
7030            (moved - stretch).abs() < 0.001,
7031            "the stretch only moved where the text was drawn: {moved} vs {stretch}"
7032        );
7033    }
7034
7035    /// Swipes far past the end of the text and returns where the text
7036    /// scrolled to and how far its edge stretched.
7037    fn swipe_past_the_end(
7038        view: &InputView<TextareaMode>,
7039        cx: &mut VisualTestContext,
7040    ) -> (Pixels, f32) {
7041        use gpui::TouchPhase::{Moved, Started};
7042
7043        cx.update(|window, cx| window.draw(cx).clear(cx));
7044        swipe(view, cx, -20., Started);
7045        swipe(view, cx, -100_000., Moved);
7046        view.input.read_with(cx, |state, _| {
7047            (state.scroll_handle.offset().y, state.overscroll.offset())
7048        })
7049    }
7050
7051    #[gpui::test]
7052    fn test_scroll_bounce_stays_put_under_reduced_motion(cx: &mut TestAppContext) {
7053        cx.update(|cx| cx.set_reduce_motion(true));
7054        let view = InputView::build_textarea(cx, |state| {
7055            state.scroll_bounce(true).default_value(long_text())
7056        });
7057        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7058        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7059        assert!(end < px(0.), "the text still scrolls");
7060        assert_eq!(stretch, 0., "the edge does not stretch");
7061    }
7062
7063    #[gpui::test]
7064    fn test_scroll_bounce_follows_the_platform_by_default(cx: &mut TestAppContext) {
7065        let view = InputView::build_textarea(cx, |state| state.default_value(long_text()));
7066        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7067        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7068        assert!(end < px(0.), "the text scrolls");
7069        assert_eq!(
7070            stretch != 0.,
7071            crate::ScrollBounce::enabled_by_default(),
7072            "the edge stretches where the platform's scroll views do"
7073        );
7074    }
7075
7076    #[gpui::test]
7077    fn test_scroll_bounce_leaves_text_that_fits(cx: &mut TestAppContext) {
7078        let view = InputView::build_textarea(cx, |state| {
7079            state.scroll_bounce(true).default_value("one line")
7080        });
7081        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7082        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7083        assert_eq!((end, stretch), (px(0.), 0.));
7084    }
7085
7086    #[gpui::test]
7087    fn test_scroll_bounce_resets_when_replacement_text_fits(cx: &mut TestAppContext) {
7088        let view = InputView::build_textarea(cx, |state| {
7089            state.scroll_bounce(true).default_value(long_text())
7090        });
7091        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7092        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7093        assert!(stretch < 0.);
7094        cx.update(|window, cx| {
7095            view.input
7096                .update(cx, |state, cx| state.set_value("short", window, cx));
7097            window.draw(cx).clear(cx);
7098        });
7099        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
7100        view.input.read_with(&cx, |state, _| {
7101            assert_eq!(state.overscroll.offset(), 0.);
7102            assert_eq!(state.scroll_handle.offset().y, px(0.));
7103        });
7104    }
7105
7106    #[gpui::test]
7107    fn test_scroll_bounce_releases_when_the_end_packet_is_horizontal(cx: &mut TestAppContext) {
7108        let view = InputView::build_textarea(cx, |state| {
7109            state.scroll_bounce(true).default_value(long_text())
7110        });
7111        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7112        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7113        assert!(stretch < 0.);
7114        cx.update(|window, cx| {
7115            view.input.update(cx, |state, cx| {
7116                state.on_scroll_wheel(
7117                    &ScrollEvent {
7118                        delta: gpui::ScrollDelta::Pixels(point(px(1.), px(0.))),
7119                        touch_phase: gpui::TouchPhase::Ended,
7120                        ..Default::default()
7121                    },
7122                    window,
7123                    cx,
7124                );
7125            });
7126        });
7127        for _ in 0..120 {
7128            cx.executor()
7129                .advance_clock(std::time::Duration::from_millis(16));
7130            cx.update(|window, cx| window.draw(cx).clear(cx));
7131        }
7132        assert_eq!(
7133            view.input
7134                .read_with(&cx, |state, _| state.overscroll.offset()),
7135            0.
7136        );
7137    }
7138
7139    #[gpui::test]
7140    fn test_scroll_bounce_ordinary_mouse_wheel_does_not_stretch(cx: &mut TestAppContext) {
7141        let view = InputView::build_textarea(cx, |state| {
7142            state.scroll_bounce(true).default_value(long_text())
7143        });
7144        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7145        cx.update(|window, cx| {
7146            window.draw(cx).clear(cx);
7147            view.input.update(cx, |state, cx| {
7148                state.on_scroll_wheel(
7149                    &ScrollEvent {
7150                        delta: gpui::ScrollDelta::Lines(point(0., -100_000.)),
7151                        touch_phase: gpui::TouchPhase::Moved,
7152                        ..Default::default()
7153                    },
7154                    window,
7155                    cx,
7156                );
7157                assert!(state.scroll_handle.offset().y < px(0.));
7158                assert_eq!(state.overscroll.offset(), 0.);
7159            });
7160        });
7161    }
7162
7163    #[gpui::test]
7164    fn test_scroll_bounce_new_wheel_input_interrupts_the_return(cx: &mut TestAppContext) {
7165        let view = InputView::build_textarea(cx, |state| {
7166            state.scroll_bounce(true).default_value(long_text())
7167        });
7168        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7169        let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7170        assert!(stretch < 0.);
7171        swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
7172        cx.executor()
7173            .advance_clock(std::time::Duration::from_millis(16));
7174        cx.update(|window, cx| {
7175            window.draw(cx).clear(cx);
7176            view.input.update(cx, |state, cx| {
7177                state.on_scroll_wheel(
7178                    &ScrollEvent {
7179                        delta: gpui::ScrollDelta::Lines(point(0., 2.)),
7180                        touch_phase: gpui::TouchPhase::Moved,
7181                        ..Default::default()
7182                    },
7183                    window,
7184                    cx,
7185                );
7186                assert!(state.scroll_handle.offset().y > end);
7187                assert_eq!(state.overscroll.offset(), 0.);
7188            });
7189        });
7190    }
7191
7192    #[gpui::test]
7193    fn test_turning_scroll_bounce_off_drops_the_stretch(cx: &mut TestAppContext) {
7194        let view = InputView::build_textarea(cx, |state| {
7195            state.scroll_bounce(true).default_value(long_text())
7196        });
7197        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7198        let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7199        assert!(stretch < 0., "the edge stretched: {stretch}");
7200        view.input
7201            .update(&mut cx, |state, cx| state.set_scroll_bounce(false, cx));
7202        assert_eq!(
7203            view.input
7204                .read_with(&cx, |state, _| state.overscroll.offset()),
7205            0.
7206        );
7207    }
7208
7209    /// The frame is laid out by the application, which should not have to
7210    /// center a single line inside it.
7211    #[gpui::test]
7212    fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
7213        struct Frame(Entity<InputBaseState<InputMode>>);
7214        impl Render for Frame {
7215            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7216                crate::input::InputBase::new("frame")
7217                    .h(px(60.))
7218                    .child(crate::input::Input::new(&self.0))
7219            }
7220        }
7221
7222        cx.update(crate::init);
7223        let mut input = None;
7224        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7225            let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
7226            input = Some(state.clone());
7227            Frame(state)
7228        });
7229        let input = input.unwrap();
7230        let mut cx = VisualTestContext::from_window(window.into(), cx);
7231        cx.update(|window, cx| window.draw(cx).clear(cx));
7232
7233        input.read_with(&cx, |state, _| {
7234            let line = state.input_bounds;
7235            assert_eq!(line.center().y, px(30.), "line {line:?}");
7236        });
7237    }
7238
7239    #[gpui::test]
7240    fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
7241        use std::{cell::Cell, rc::Rc};
7242
7243        cx.update(crate::init);
7244        let mut input = None;
7245        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7246            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7247            gpui::EmptyView
7248        });
7249        let input = input.unwrap();
7250        input.update(cx, |state, cx| {
7251            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7252            state.scroll_size = size(px(100.), px(20.));
7253            state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
7254        });
7255        let notifications = Rc::new(Cell::new(0));
7256        let count = notifications.clone();
7257        let _subscription =
7258            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7259
7260        window
7261            .update(cx, |_, window, cx| {
7262                input.update(cx, |state, cx| {
7263                    state.on_scroll_wheel(
7264                        &ScrollEvent {
7265                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7266                            ..Default::default()
7267                        },
7268                        window,
7269                        cx,
7270                    );
7271                    assert_eq!(state.scroll_handle.offset(), Point::default());
7272                    assert!(state.diagnostic_popover().is_none());
7273                });
7274            })
7275            .unwrap();
7276        assert_eq!(
7277            notifications.get(),
7278            1,
7279            "clearing a diagnostic must notify even when scrolling is clamped"
7280        );
7281        window
7282            .update(cx, |_, window, cx| {
7283                input.update(cx, |state, cx| {
7284                    state.on_scroll_wheel(
7285                        &ScrollEvent {
7286                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7287                            ..Default::default()
7288                        },
7289                        window,
7290                        cx,
7291                    );
7292                });
7293            })
7294            .unwrap();
7295        assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
7296    }
7297
7298    /// Replacing the text with one whose line numbers need another digit narrows the wrap width
7299    /// by that digit up front, so the next layout does not wrap the new text a second time.
7300    #[gpui::test]
7301    fn replacing_the_text_wraps_at_the_width_its_line_numbers_leave(cx: &mut TestAppContext) {
7302        struct Panel(Entity<crate::input::EditorState>);
7303        impl Render for Panel {
7304            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7305                div().size_full().child(self.0.clone())
7306            }
7307        }
7308        cx.update(crate::init);
7309        let mut input = None;
7310        let window = cx.open_window(size(px(400.), px(300.)), |window, cx| {
7311            let state = cx.new(|cx| {
7312                crate::input::EditorState::new(window, cx)
7313                    .line_number(true)
7314                    .soft_wrap(true)
7315            });
7316            input = Some(state.clone());
7317            Panel(state)
7318        });
7319        cx.run_until_parked();
7320        let input = input.unwrap();
7321        let wrap_width = |cx: &mut TestAppContext| {
7322            input.read_with(cx, |state, _| state.display_map.wrap_width())
7323        };
7324        let three_digits = wrap_width(cx).expect("a soft wrapped editor has a wrap width");
7325
7326        let predicted = window
7327            .update(cx, |_, window, cx| {
7328                input.update(cx, |state, cx| {
7329                    state.set_value("line\n".repeat(1_000), window, cx);
7330                    state.display_map.wrap_width()
7331                })
7332            })
7333            .unwrap()
7334            .unwrap();
7335        assert!(
7336            predicted < three_digits,
7337            "a fourth digit must narrow the text"
7338        );
7339        cx.run_until_parked();
7340        assert_eq!(
7341            wrap_width(cx),
7342            Some(predicted),
7343            "the layout must keep the width the text was wrapped at"
7344        );
7345    }
7346
7347    /// Hover must reach the whole visible editor after scrolling, not only
7348    /// the part that overlaps the unscrolled text bounds.
7349    #[gpui::test]
7350    fn test_hover_reaches_bottom_of_scrolled_editor(cx: &mut TestAppContext) {
7351        use crate::input::{Diagnostic, Position};
7352        struct Frame(Entity<crate::input::EditorState>);
7353        impl Render for Frame {
7354            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7355                crate::input::InputBase::new("frame")
7356                    .h(px(100.))
7357                    .child(crate::input::Editor::new(&self.0))
7358            }
7359        }
7360
7361        cx.update(crate::init);
7362        let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
7363        let mut input = None;
7364        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7365            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
7366            input = Some(state.clone());
7367            Frame(state)
7368        });
7369        let input = input.unwrap();
7370        let mut cx = VisualTestContext::from_window(window.into(), cx);
7371        input.update(&mut cx, |state, _| {
7372            state.diagnostics_mut().unwrap().push(Diagnostic::new(
7373                Position::new(0, 0)..Position::new(100, 0),
7374                "everywhere",
7375            ));
7376        });
7377        cx.update(|window, cx| window.draw(cx).clear(cx));
7378        cx.update(|window, cx| {
7379            input.update(cx, |state, cx| {
7380                state.on_scroll_wheel(
7381                    &ScrollEvent {
7382                        delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-400.))),
7383                        ..Default::default()
7384                    },
7385                    window,
7386                    cx,
7387                );
7388            })
7389        });
7390        cx.update(|window, cx| window.draw(cx).clear(cx));
7391
7392        let bounds = input.read_with(&cx, |state, _| state.input_bounds);
7393        cx.simulate_mouse_move(
7394            point(bounds.center().x, bounds.bottom() - px(5.)),
7395            None,
7396            gpui::Modifiers::default(),
7397        );
7398        assert!(
7399            input.read_with(&cx, |state, _| state.diagnostic_popover().is_some()),
7400            "no hover at the bottom of a scrolled editor, bounds {bounds:?}"
7401        );
7402    }
7403
7404    #[gpui::test]
7405    fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
7406        use std::{cell::Cell, rc::Rc};
7407        struct Panel {
7408            input: Entity<crate::input::EditorState>,
7409            observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
7410        }
7411        impl Render for Panel {
7412            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7413                self.observed.set(self.input.read(cx).cursor_layout());
7414                div().size_full().child(self.input.clone())
7415            }
7416        }
7417        struct Root(Entity<Panel>);
7418        impl Render for Root {
7419            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7420                div().size_full().child(
7421                    self.0
7422                        .clone()
7423                        .cached(gpui::StyleRefinement::default().size_full()),
7424                )
7425            }
7426        }
7427        cx.update(crate::init);
7428        let observed = Rc::new(Cell::new(None));
7429        let mut input = None;
7430        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7431            let state = cx.new(|cx| {
7432                let mut state = crate::input::EditorState::new(window, cx);
7433                state.set_value("abcdefgh", window, cx);
7434                state
7435            });
7436            input = Some(state.clone());
7437            Root(cx.new(|_| Panel {
7438                input: state,
7439                observed: observed.clone(),
7440            }))
7441        });
7442        cx.run_until_parked();
7443        let input = input.unwrap();
7444        let before = input.read_with(cx, |state, _| state.cursor_layout());
7445        // The caret geometry only exists once the input has painted, and a
7446        // notify sent from inside a draw marks the view dirty without asking
7447        // for another frame, so the consumer reads the geometry on the next
7448        // invalidation rather than during the paint that produced it.
7449        input.update(cx, |_, cx| cx.notify());
7450        cx.run_until_parked();
7451        assert_eq!(observed.get(), before);
7452        window
7453            .update(cx, |_, _, cx| {
7454                input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
7455            })
7456            .unwrap();
7457        cx.run_until_parked();
7458        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7459        let after = input.read_with(cx, |state, _| state.cursor_layout());
7460        assert_ne!(after, before, "the caret must actually move");
7461        assert_eq!(
7462            observed.get(),
7463            after,
7464            "render consumers must receive the newly painted caret geometry"
7465        );
7466    }
7467
7468    #[gpui::test]
7469    fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
7470        use std::{cell::Cell, rc::Rc};
7471
7472        cx.update(crate::init);
7473        let mut input = None;
7474        let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7475            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7476            gpui::EmptyView
7477        });
7478        let input = input.unwrap();
7479        let notifications = Rc::new(Cell::new(0));
7480        let count = notifications.clone();
7481        let _subscription =
7482            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7483
7484        input.update(cx, |state, _| {
7485            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7486            state.scroll_size = size(px(300.), px(20.));
7487        });
7488        for target in [
7489            None,
7490            Some(point(px(0.), px(0.))),
7491            Some(point(px(20.), px(50.))),
7492        ] {
7493            input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
7494            assert_eq!(
7495                notifications.get(),
7496                0,
7497                "an unchanged clamped offset must stay quiet"
7498            );
7499        }
7500        input.update(cx, |state, cx| {
7501            state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
7502            assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
7503        });
7504        assert_eq!(notifications.get(), 1, "a scroll must notify");
7505        input.update(cx, |state, cx| {
7506            state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
7507            assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
7508        });
7509        assert_eq!(notifications.get(), 2);
7510        input.update(cx, |state, cx| {
7511            state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
7512        });
7513        assert_eq!(
7514            notifications.get(),
7515            2,
7516            "clamping to the current offset must stay quiet"
7517        );
7518        input.update(cx, |state, cx| {
7519            state.scroll_size.width = px(110.);
7520            state.update_scroll_offset(None, cx);
7521            assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
7522        });
7523        assert_eq!(
7524            notifications.get(),
7525            3,
7526            "a smaller scroll range must clamp and notify"
7527        );
7528    }
7529
7530    #[gpui::test]
7531    fn test_set_line_number_notifies_only_on_change(cx: &mut TestAppContext) {
7532        use std::{cell::Cell, rc::Rc};
7533
7534        cx.update(crate::init);
7535        let mut input = None;
7536        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7537            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7538            gpui::EmptyView
7539        });
7540        let input = input.unwrap();
7541        let shown = input.read_with(cx, |state, _| state.mode.line_number());
7542        let notifications = Rc::new(Cell::new(0));
7543        let count = notifications.clone();
7544        let _subscription =
7545            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7546
7547        window
7548            .update(cx, |_, window, cx| {
7549                input.update(cx, |state, cx| state.set_line_number(shown, window, cx))
7550            })
7551            .unwrap();
7552        assert_eq!(notifications.get(), 0);
7553
7554        window
7555            .update(cx, |_, window, cx| {
7556                input.update(cx, |state, cx| state.set_line_number(!shown, window, cx))
7557            })
7558            .unwrap();
7559        assert_eq!(notifications.get(), 1);
7560        assert_eq!(
7561            input.read_with(cx, |state, _| state.mode.line_number()),
7562            !shown
7563        );
7564    }
7565
7566    #[gpui::test]
7567    fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
7568        use std::{cell::Cell, rc::Rc};
7569
7570        cx.update(crate::init);
7571        let mut input = None;
7572        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7573            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7574            gpui::EmptyView
7575        });
7576        let input = input.unwrap();
7577        cx.run_until_parked();
7578
7579        let notifications = Rc::new(Cell::new(0));
7580        let count = notifications.clone();
7581        let _subscription =
7582            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7583        cx.run_until_parked();
7584
7585        // Seeding a form is a write, so it notifies once. The input is not
7586        // focused and draws no caret, so nothing may notify after that.
7587        window
7588            .update(cx, |_, window, cx| {
7589                input.update(cx, |state, cx| state.set_value("seeded", window, cx));
7590            })
7591            .unwrap();
7592        cx.run_until_parked();
7593        let settled = notifications.get();
7594
7595        cx.executor()
7596            .advance_clock(std::time::Duration::from_secs(3));
7597        cx.run_until_parked();
7598
7599        assert_eq!(
7600            notifications.get(),
7601            settled,
7602            "an unfocused input is blinking, and every blink repaints the view it is in"
7603        );
7604    }
7605
7606    #[gpui::test]
7607    fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
7608        use std::{cell::Cell, rc::Rc};
7609
7610        struct Panel {
7611            input: Entity<crate::input::InputState>,
7612            renders: Rc<Cell<usize>>,
7613        }
7614        impl Render for Panel {
7615            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7616                self.renders.set(self.renders.get() + 1);
7617                div().size_full().child(self.input.clone())
7618            }
7619        }
7620        struct Root(Entity<Panel>);
7621        impl Render for Root {
7622            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7623                div().size_full().child(
7624                    self.0
7625                        .clone()
7626                        .cached(gpui::StyleRefinement::default().size_full()),
7627                )
7628            }
7629        }
7630
7631        cx.update(crate::init);
7632        let renders = Rc::new(Cell::new(0));
7633        let mut input = None;
7634        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7635            let state = cx.new(|cx| crate::input::InputState::new(window, cx));
7636            input = Some(state.clone());
7637            Root(cx.new(|_| Panel {
7638                input: state,
7639                renders: renders.clone(),
7640            }))
7641        });
7642        cx.run_until_parked();
7643        let before = renders.get();
7644        assert!(before > 0);
7645        for _ in 0..60 {
7646            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7647        }
7648        assert_eq!(
7649            renders.get(),
7650            before,
7651            "an idle input must not invalidate its cached parent"
7652        );
7653
7654        let input = input.unwrap();
7655        window
7656            .update(cx, |_, window, cx| {
7657                input.update(cx, |state, cx| state.set_value("changed", window, cx));
7658            })
7659            .unwrap();
7660        assert!(
7661            renders.get() > before,
7662            "text changes must invalidate the parent"
7663        );
7664        // The first paint reports the changed text extent to layout consumers.
7665        window.update(cx, |_, _, cx| cx.notify()).unwrap();
7666        let before = renders.get();
7667        for _ in 0..60 {
7668            window.update(cx, |_, _, cx| cx.notify()).unwrap();
7669        }
7670        assert_eq!(renders.get(), before, "the edited input must settle again");
7671
7672        cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
7673        cx.run_until_parked();
7674        assert!(renders.get() > before, "resizing must invalidate layout");
7675    }
7676
7677    #[gpui::test]
7678    fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
7679        cx.update(crate::init);
7680        let view = InputView::build_textarea(cx, |state| state);
7681        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7682        cx.update(|window, cx| {
7683            view.input.update(cx, |state, cx| {
7684                for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
7685                    state.set_value(original, window, cx);
7686                    let newline = original.find('\n').unwrap();
7687                    let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
7688                        newline - 1
7689                    } else {
7690                        newline
7691                    };
7692                    state.end(&MoveEnd, window, cx);
7693                    assert_eq!(state.cursor(), end);
7694                    state.right(&MoveRight, window, cx);
7695                    assert_eq!(state.cursor(), newline + 1);
7696                    state.left(&MoveLeft, window, cx);
7697                    assert_eq!(state.cursor(), end);
7698                    state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
7699                    assert_eq!(state.selected_range(), end..end);
7700                    state.move_to_end(&MoveToEnd, window, cx);
7701                    assert_eq!(state.cursor(), original.len());
7702                    state.move_to_start(&MoveToStart, window, cx);
7703                    assert_eq!(state.cursor(), 0);
7704                    assert_eq!(state.value().as_bytes(), original.as_bytes());
7705                }
7706                // A lone CR is an ordinary character; it must not skip its neighbour.
7707                state.set_value("a\rb", window, cx);
7708                state.right(&MoveRight, window, cx);
7709                assert_eq!(state.cursor(), 1);
7710                state.right(&MoveRight, window, cx);
7711                assert_eq!(state.cursor(), 2);
7712            })
7713        });
7714    }
7715
7716    #[gpui::test]
7717    fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
7718        cx.update(crate::init);
7719
7720        // A single-line input keeps its caret in view by moving its own offset;
7721        // it has no viewport to drag, so a scrollbar in a text field is a
7722        // control that does not exist.
7723        let single = InputView::build(cx, |state| state);
7724        single
7725            .input
7726            .update(cx, |state, _| assert!(!state.shows_scrollbar()));
7727
7728        let multi = InputView::build_textarea(cx, |state| state);
7729        multi
7730            .input
7731            .update(cx, |state, _| assert!(state.shows_scrollbar()));
7732    }
7733
7734    #[gpui::test]
7735    fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
7736        use std::{cell::Cell, rc::Rc};
7737        cx.update(crate::init);
7738        let input_view = InputView::new(cx);
7739        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7740        let input = input_view.input;
7741        let calls = Rc::new(Cell::new(0usize));
7742        let items = Rc::new(Cell::new(0usize));
7743        let menu_focus = cx.update(|_, cx| cx.focus_handle());
7744
7745        cx.update(|window, cx| {
7746            input.update(cx, |state, cx| {
7747                let calls2 = calls.clone();
7748                let items2 = items.clone();
7749                let menu_focus = menu_focus.clone();
7750                state.on_context_menu(Rc::new(move |menu, _, _, window, cx| {
7751                    calls2.set(calls2.get() + 1);
7752                    items2.set(menu.items.len());
7753                    menu_focus.focus(window, cx);
7754                }));
7755                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7756            })
7757        });
7758        assert_eq!(calls.get(), 1);
7759        assert_eq!(items.get(), 0);
7760        input.read_with(&cx, |state, _| {
7761            assert_eq!(
7762                state
7763                    .selection_focus
7764                    .as_ref()
7765                    .and_then(WeakFocusHandle::upgrade)
7766                    .as_ref(),
7767                Some(&menu_focus),
7768                "the menu callback must retain selection without reborrowing its input"
7769            );
7770        });
7771
7772        // A custom handler may keep using the same, already-focused menu.
7773        cx.update(|window, cx| {
7774            input.update(cx, |state, cx| {
7775                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7776            });
7777        });
7778        assert_eq!(calls.get(), 2);
7779        cx.update(|window, cx| {
7780            assert!(input.read(cx).has_selection_focus(window, cx));
7781        });
7782
7783        cx.update(|window, cx| {
7784            input.update(cx, |state, cx| {
7785                state.disabled = true;
7786                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
7787            })
7788        });
7789        assert_eq!(calls.get(), 2);
7790    }
7791
7792    #[gpui::test]
7793    fn context_menu_handler_can_read_its_input(cx: &mut TestAppContext) {
7794        use std::{cell::Cell, rc::Rc};
7795        cx.update(crate::init);
7796        let input_view = InputView::new(cx);
7797        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7798        let input = input_view.input;
7799        let cursor = Rc::new(Cell::new(None));
7800
7801        cx.update(|window, cx| {
7802            input.update(cx, |state, cx| {
7803                state.set_value("hello", window, cx);
7804                let weak = cx.weak_entity();
7805                let cursor = cursor.clone();
7806                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7807                    cursor.set(weak.upgrade().map(|input| input.read(cx).cursor()));
7808                }));
7809                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7810            })
7811        });
7812        assert_eq!(cursor.get(), Some(2));
7813    }
7814
7815    #[gpui::test]
7816    fn context_menu_handler_can_read_the_offset_under_the_pointer(cx: &mut TestAppContext) {
7817        use std::{cell::Cell, rc::Rc};
7818        cx.update(crate::init);
7819        let input_view = InputView::new(cx);
7820        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7821        let input = input_view.input;
7822        let seen = Rc::new(Cell::new(None));
7823
7824        cx.update(|window, cx| {
7825            input.update(cx, |state, cx| {
7826                state.set_value("hello world", window, cx);
7827                assert_eq!(state.context_menu_offset(), None);
7828                state.select_all(window, cx);
7829                let weak = cx.weak_entity();
7830                let seen = seen.clone();
7831                state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7832                    seen.set(weak.upgrade().map(|input| {
7833                        let input = input.read(cx);
7834                        (input.cursor(), input.context_menu_offset())
7835                    }));
7836                }));
7837                // A right-click inside the selection keeps the cursor at its end.
7838                state.handle_right_click_menu(point(px(0.), px(0.)), 2, window, cx);
7839            })
7840        });
7841        assert_eq!(seen.get(), Some((11, Some(2))));
7842    }
7843
7844    #[gpui::test]
7845    fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
7846        let input_view = InputView::new(cx);
7847        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7848        let input = input_view.input;
7849
7850        cx.update(|window, cx| {
7851            input.update(cx, |state, cx| {
7852                state.set_value("hello", window, cx);
7853                state.set_readonly(true, cx);
7854            });
7855        });
7856
7857        cx.update(|_, cx| {
7858            input.read_with(cx, |state, _| {
7859                assert!(!state.is_editable());
7860                assert!(!state.is_replaceable());
7861            });
7862        });
7863
7864        // Typing (and IME) goes through the input handler, it must be rejected.
7865        cx.update(|window, cx| {
7866            input.update(cx, |state, cx| {
7867                state.replace_text_in_range(None, " world", window, cx);
7868                state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
7869            });
7870        });
7871        cx.update(|_, cx| {
7872            input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
7873        });
7874
7875        // The programmatic APIs are not limited by the readonly mode.
7876        cx.update(|window, cx| {
7877            input.update(cx, |state, cx| {
7878                state.insert(" world", window, cx);
7879                state.set_value("changed", window, cx);
7880            });
7881        });
7882        cx.update(|_, cx| {
7883            input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
7884        });
7885
7886        // And the user can edit again after leaving the readonly mode.
7887        // The caret is at the start, because `set_value` has reset the selection.
7888        cx.update(|window, cx| {
7889            input.update(cx, |state, cx| {
7890                state.set_readonly(false, cx);
7891                state.replace_text_in_range(None, "!", window, cx);
7892            });
7893        });
7894        cx.update(|_, cx| {
7895            input.read_with(cx, |state, _| {
7896                assert!(state.is_editable());
7897                assert_eq!(state.value(), "!changed");
7898            });
7899        });
7900    }
7901
7902    /// Regression test: editing at a caret that sits far outside the viewport
7903    /// must reveal it in one frame. The cursor-follow in `layout_cursors` runs
7904    /// only on the frame the selection changes, so its old one-line step left
7905    /// the caret offscreen after typing at the end of a long paste.
7906    #[gpui::test]
7907    fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
7908        let mut input = None;
7909        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7910            cx.set_global(Theme::default());
7911            super::super::init(cx);
7912            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
7913            input = Some(state.clone());
7914            TestRoot(state)
7915        });
7916        let mut cx = VisualTestContext::from_window(window.into(), cx);
7917        let input = input.unwrap();
7918
7919        let text: String = (1..=100)
7920            .map(|i| format!("line {i}"))
7921            .collect::<Vec<_>>()
7922            .join("\n");
7923        cx.update(|window, cx| {
7924            input.update(cx, |state, cx| {
7925                state.set_value(text, window, cx);
7926                let end = state.text.len();
7927                state.set_selection(end, end);
7928            });
7929        });
7930        cx.run_until_parked();
7931
7932        // The user scrolled back to the top to read the pasted text.
7933        cx.update(|_, cx| {
7934            input.update(cx, |state, cx| {
7935                state.scroll_handle.set_offset(point(px(0.), px(0.)));
7936                cx.notify();
7937            });
7938        });
7939        cx.run_until_parked();
7940
7941        cx.update(|window, cx| {
7942            input.update(cx, |state, cx| {
7943                state.replace_text_in_range(None, "X", window, cx);
7944            });
7945        });
7946        cx.run_until_parked();
7947
7948        cx.update(|_, cx| {
7949            input.read_with(cx, |state, _| {
7950                assert!(state.value().ends_with("line 100X"));
7951                let (caret, _) = state.cursor_layout().expect("caret painted");
7952                let viewport = state.input_bounds();
7953                let scroll_y = state.scroll_handle.offset().y;
7954                let top = caret.origin.y + scroll_y - viewport.origin.y;
7955                assert!(
7956                    top >= px(0.) && top + caret.size.height <= viewport.size.height,
7957                    "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
7958                    viewport.size.height,
7959                );
7960            });
7961        });
7962    }
7963
7964    /// Regression test: changing the auto-grow limits keeps the rows fitted to
7965    /// the text. `set_auto_grow` used to start over at `min_rows`, and the rows
7966    /// were counted again only on the next edit or wrap width change.
7967    #[gpui::test]
7968    fn test_set_auto_grow_keeps_rows_fitted(cx: &mut TestAppContext) {
7969        let mut input = None;
7970        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
7971            cx.set_global(Theme::default());
7972            super::super::init(cx);
7973            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 10));
7974            input = Some(state.clone());
7975            TestRoot(state)
7976        });
7977        let mut cx = VisualTestContext::from_window(window.into(), cx);
7978        let input = input.unwrap();
7979
7980        let text: String = (1..=8)
7981            .map(|i| format!("line {i}"))
7982            .collect::<Vec<_>>()
7983            .join("\n");
7984        cx.update(|window, cx| {
7985            input.update(cx, |state, cx| state.set_value(text, window, cx));
7986        });
7987        cx.run_until_parked();
7988        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7989
7990        // A larger maximum keeps all eight rows.
7991        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 12, cx)));
7992        cx.run_until_parked();
7993        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
7994
7995        // A smaller maximum caps them.
7996        cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 4, cx)));
7997        cx.run_until_parked();
7998        cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 4)));
7999    }
8000
8001    /// Regression test: `scroll_to` at end-of-buffer must produce a deferred
8002    /// scroll target within the safe scroll range, so the painted frame
8003    /// matches what `update_scroll_offset` persists (no jitter). A small
8004    /// `cursor_surrounding_lines` override used to mismatch the hardcoded
8005    /// 3-line edge clearance in `scroll_to`, overshooting `safe_y_min`.
8006    #[gpui::test]
8007    fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
8008        let input_view = InputView::new(cx);
8009        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8010        let input = input_view.input;
8011
8012        // JetBrains-style: 1 trailing empty row + 1-line cursor surrounding.
8013        cx.update(|window, cx| {
8014            input.update(cx, |state, cx| {
8015                state.set_scroll_beyond_last_line(Some(1), window, cx);
8016                state.set_cursor_surrounding_lines(Some(1), window, cx);
8017                let text: String = (1..=50)
8018                    .map(|i| format!("line {i}"))
8019                    .collect::<Vec<_>>()
8020                    .join("\n");
8021                state.set_value(text, window, cx);
8022            });
8023        });
8024        cx.run_until_parked();
8025
8026        // Sanity: paint populated `scroll_size` and `input_bounds` — without
8027        // these, `safe_y_min` below collapses to 0 and the assertion is vacuous.
8028        cx.update(|_, cx| {
8029            input.read_with(cx, |state, _| {
8030                assert!(
8031                    state.scroll_size.height > px(0.),
8032                    "scroll_size not populated by initial paint"
8033                );
8034                assert!(
8035                    state.input_bounds.size.height > px(0.),
8036                    "input_bounds not populated by initial paint"
8037                );
8038            });
8039        });
8040
8041        // Move cursor to end with downward direction — same code path as a
8042        // `Down` keystroke at EOB. `scroll_to` runs synchronously inside
8043        // `move_to`; inspect `deferred_scroll_offset` in the same closure
8044        // before the next paint consumes and clears it.
8045        cx.update(|_, cx| {
8046            input.update(cx, |state, cx| {
8047                let end = state.text.len();
8048                state.move_to(end, Some(MoveDirection::Down), cx);
8049
8050                let deferred = state
8051                    .deferred_scroll_offset
8052                    .expect("scroll_to should populate deferred_scroll_offset");
8053                let safe_y_min =
8054                    (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
8055
8056                assert!(
8057                    deferred.y >= safe_y_min,
8058                    "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
8059                     — paint would jitter (Bug C regression)",
8060                    deferred.y,
8061                    safe_y_min,
8062                );
8063            });
8064        });
8065    }
8066
8067    #[gpui::test]
8068    fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
8069        assert_search_reveals_with_padding_after_manual_scroll(false, cx);
8070    }
8071
8072    #[gpui::test]
8073    fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
8074        cx: &mut TestAppContext,
8075    ) {
8076        assert_search_reveals_with_padding_after_manual_scroll(true, cx);
8077    }
8078
8079    fn assert_search_reveals_with_padding_after_manual_scroll(
8080        previous: bool,
8081        cx: &mut TestAppContext,
8082    ) {
8083        let input_view = InputView::new(cx);
8084        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8085        let input = input_view.input;
8086        let text = (0..160)
8087            .map(|row| {
8088                if matches!(row, 20 | 60 | 100) {
8089                    format!("match on row {row}")
8090                } else {
8091                    format!("line {row}")
8092                }
8093            })
8094            .collect::<Vec<_>>()
8095            .join("\n");
8096        let start = text.match_indices("match").nth(1).unwrap().0;
8097        let expected_match = start..start + "match".len();
8098        cx.update(|window, cx| {
8099            input.update(cx, |state, cx| {
8100                state.set_cursor_surrounding_lines(Some(3), window, cx);
8101                state.set_value(text, window, cx);
8102                state.set_search_query("match", true, cx);
8103                if previous {
8104                    state.search_session.matcher.next();
8105                    state.search_session.matcher.next();
8106                }
8107            });
8108        });
8109        cx.run_until_parked();
8110        cx.update(|_, cx| {
8111            input.update(cx, |state, cx| {
8112                let line_height = state.last_layout.as_ref().unwrap().line_height;
8113                let y = if previous { px(0.) } else { -line_height * 80. };
8114                state.set_scroll_offset(point(px(0.), y), cx);
8115            });
8116        });
8117        cx.run_until_parked();
8118        input.read_with(&cx, |state, _| {
8119            let visible = state.visible_row_range().unwrap();
8120            if previous {
8121                assert!(visible.end <= 60, "target must be below the viewport");
8122            } else {
8123                assert!(visible.start > 60, "target must be above the viewport");
8124            }
8125        });
8126        cx.update(|_, cx| {
8127            input.update(cx, |state, cx| {
8128                let range = if previous {
8129                    state.previous_search_match(cx)
8130                } else {
8131                    state.next_search_match(cx)
8132                };
8133                assert_eq!(range, Some(expected_match));
8134                assert_eq!(state.search_session.matcher.label(), "2/3");
8135            });
8136        });
8137        cx.run_until_parked();
8138        input.read_with(&cx, |state, _| {
8139            assert!(state.visible_row_range().unwrap().contains(&60));
8140            let line_height = state.last_layout.as_ref().unwrap().line_height;
8141            let target_y = line_height * 60. + state.scroll_handle.offset().y;
8142            // Three lines of edge clearance include the matched line itself.
8143            assert!(target_y >= line_height * 2. - px(0.1));
8144            assert!(
8145                target_y + line_height * 3.
8146                    <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
8147                "search must preserve the configured surrounding-line padding"
8148            );
8149        });
8150    }
8151
8152    /// A host that wants the search shortcut for its own search UI.
8153    struct SearchHost {
8154        editor: Entity<InputBaseState<EditorMode>>,
8155        search_requests: Rc<Cell<usize>>,
8156    }
8157
8158    impl Render for SearchHost {
8159        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8160            let search_requests = self.search_requests.clone();
8161            div()
8162                .size_full()
8163                .on_action(cx.listener(move |_, _: &Search, _, _| {
8164                    search_requests.set(search_requests.get() + 1);
8165                }))
8166                .child(self.editor.clone())
8167        }
8168    }
8169
8170    /// Opens an editor inside [`SearchHost`], focused, and presses the search
8171    /// shortcut once. Returns the editor and the host's request count.
8172    fn press_search_shortcut(
8173        cx: &mut TestAppContext,
8174        searchable: bool,
8175    ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
8176        let search_requests = Rc::new(Cell::new(0));
8177        let mut editor = None;
8178        let window = cx.update(|cx| {
8179            cx.open_window(Default::default(), |window, cx| {
8180                cx.set_global(Theme::default());
8181                super::super::init(cx);
8182                let state =
8183                    cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
8184                editor = Some(state.clone());
8185                cx.new(|_| SearchHost {
8186                    editor: state,
8187                    search_requests: search_requests.clone(),
8188                })
8189            })
8190            .unwrap()
8191        });
8192        let editor = editor.unwrap();
8193        let mut cx = VisualTestContext::from_window(window.into(), cx);
8194        cx.update(|window, cx| {
8195            editor.update(cx, |state, cx| state.focus(window, cx));
8196        });
8197        cx.run_until_parked();
8198        #[cfg(target_os = "macos")]
8199        cx.simulate_keystrokes("cmd-f");
8200        #[cfg(not(target_os = "macos"))]
8201        cx.simulate_keystrokes("ctrl-f");
8202        cx.run_until_parked();
8203        (editor, search_requests)
8204    }
8205
8206    #[gpui::test]
8207    fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
8208        let (editor, search_requests) = press_search_shortcut(cx, false);
8209        assert_eq!(search_requests.get(), 1);
8210        editor.read_with(cx, |state, _| {
8211            assert!(!state.search_session().open);
8212            assert!(!state.search_session().is_active());
8213        });
8214    }
8215
8216    #[gpui::test]
8217    fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
8218        let (editor, search_requests) = press_search_shortcut(cx, true);
8219        assert_eq!(search_requests.get(), 0);
8220        editor.read_with(cx, |state, _| {
8221            assert!(state.search_session().open);
8222            assert!(state.search_session().is_active());
8223        });
8224    }
8225
8226    #[gpui::test]
8227    fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
8228        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
8229        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8230        let input = input_view.input;
8231        cx.update(|window, cx| {
8232            input.update(cx, |state, cx| {
8233                state.set_value("foo bar foo", window, cx);
8234                state.set_search_query("foo", true, cx);
8235            });
8236        });
8237        cx.run_until_parked();
8238        input.read_with(&cx, |state, _| {
8239            let session = state.search_session();
8240            assert!(session.is_active());
8241            assert!(!session.open);
8242            assert_eq!(session.matcher.len(), 2);
8243        });
8244        cx.update(|_, cx| {
8245            input.update(cx, |state, cx| state.close_search(cx));
8246        });
8247        input.read_with(&cx, |state, _| {
8248            assert!(!state.search_session().is_active());
8249        });
8250    }
8251
8252    /// A closed search skips rescanning on edits, so every path that reads
8253    /// the matches again must see the edited text, not the text at close.
8254    #[gpui::test]
8255    fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
8256        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
8257        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8258        let input = input_view.input;
8259        cx.update(|window, cx| {
8260            input.update(cx, |state, cx| {
8261                state.set_value("foo bar foo", window, cx);
8262                state.set_search_query("foo", true, cx);
8263                state.close_search(cx);
8264
8265                state.set_value("bar foo", window, cx);
8266                assert_eq!(state.next_search_match(cx), Some(4..7));
8267
8268                state.set_value("foo foo foo", window, cx);
8269                state.set_search_query("foo", true, cx);
8270                assert_eq!(state.search_session().matcher.len(), 3);
8271            });
8272        });
8273    }
8274
8275    #[gpui::test]
8276    fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
8277        let input_view = InputView::new(cx);
8278        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8279        let input = input_view.input;
8280        let text = format!(
8281            "match\n{}\n{}match\n{}",
8282            "line\n".repeat(80),
8283            "wrapped text ".repeat(500),
8284            "line\n".repeat(80)
8285        );
8286        cx.update(|window, cx| {
8287            input.update(cx, |state, cx| {
8288                state.set_cursor_surrounding_lines(Some(3), window, cx);
8289                state.set_value(text, window, cx);
8290                state.set_search_query("match", true, cx);
8291            });
8292        });
8293        cx.run_until_parked();
8294        cx.update(|_, cx| {
8295            input.update(cx, |state, cx| {
8296                state.next_search_match(cx).unwrap();
8297            });
8298        });
8299        cx.run_until_parked();
8300        input.read_with(&cx, |state, _| {
8301            let range = state.search_session.matcher.matched_ranges()[1].clone();
8302            let layout = state.last_layout.as_ref().unwrap();
8303            let (_, _, position) = state.line_and_position_for_offset(range.end);
8304            let y = position.expect("wrapped match must be laid out").y;
8305            assert!(y >= layout.line_height * 2. - px(0.1));
8306            assert!(
8307                y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
8308                "wrapped match must retain surrounding display rows"
8309            );
8310        });
8311    }
8312
8313    #[gpui::test]
8314    fn test_number_step(cx: &mut TestAppContext) {
8315        let input = InputView::build(cx, |state| state).input;
8316
8317        cx.update(|cx| {
8318            input.update(cx, |_state, cx| {
8319                assert_eq!(
8320                    NumberStep::from(5.).value(123., StepAction::Increment, cx),
8321                    5.
8322                );
8323
8324                // The step can differ by direction at a boundary: at 1.0 it
8325                // is 0.1 going down and 0.5 going up.
8326                let step = NumberStep::by_value(|value, action, _cx| {
8327                    let below = match action {
8328                        StepAction::Increment => value < 1.0,
8329                        StepAction::Decrement => value <= 1.0,
8330                    };
8331                    if below { 0.1 } else { 0.5 }
8332                });
8333                assert_eq!(step.value(0.5, StepAction::Increment, cx), 0.1);
8334                assert_eq!(step.value(1.0, StepAction::Increment, cx), 0.5);
8335                assert_eq!(step.value(1.0, StepAction::Decrement, cx), 0.1);
8336                assert_eq!(step.value(2.0, StepAction::Decrement, cx), 0.5);
8337            });
8338        });
8339    }
8340
8341    #[gpui::test]
8342    fn test_number_input_normalization(cx: &mut TestAppContext) {
8343        let input_view = InputView::build(cx, |state| {
8344            state.mask_pattern(MaskPattern::Number {
8345                separator: None,
8346                fraction: None,
8347            })
8348        });
8349        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8350        let input = input_view.input;
8351
8352        // Full-width digits and the ideographic full stop are normalized,
8353        // and the cursor is at the end (in normalized bytes, not the
8354        // original 12 bytes).
8355        cx.update(|window, cx| {
8356            input.update(cx, |state, cx| {
8357                state.replace_text_in_range(None, "12。5", window, cx);
8358            });
8359        });
8360        cx.run_until_parked();
8361        cx.update(|_, cx| {
8362            input.read_with(cx, |state, _| {
8363                assert_eq!(state.value(), "12.5");
8364                let cursor: Range<usize> = state.selected_range();
8365                assert_eq!(cursor, 4..4);
8366            });
8367        });
8368
8369        // Non-numeric input is rejected.
8370        cx.update(|window, cx| {
8371            input.update(cx, |state, cx| {
8372                state.replace_text_in_range(None, "abc", window, cx);
8373            });
8374        });
8375        cx.run_until_parked();
8376        cx.update(|_, cx| {
8377            input.read_with(cx, |state, _| {
8378                assert_eq!(state.value(), "12.5");
8379            });
8380        });
8381
8382        // A bare leading dot is kept as-is (normalized from the ideographic
8383        // full stop), not completed to "0.", so it stays editable.
8384        cx.update(|window, cx| {
8385            input.update(cx, |state, cx| {
8386                let range = state.range_to_utf16(&(0..state.text.len()));
8387                state.replace_text_in_range(Some(range), "。", window, cx);
8388            });
8389        });
8390        cx.run_until_parked();
8391        cx.update(|_, cx| {
8392            input.read_with(cx, |state, _| {
8393                assert_eq!(state.value(), ".");
8394                let cursor: Range<usize> = state.selected_range();
8395                assert_eq!(cursor, 1..1);
8396            });
8397        });
8398    }
8399
8400    #[gpui::test]
8401    fn test_mask_pattern_accepts_non_ascii_text(cx: &mut TestAppContext) {
8402        let input_view = InputView::build(cx, |state| state.mask_pattern("9999年99月"));
8403        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8404        let input = input_view.input;
8405
8406        cx.update(|window, cx| {
8407            input.update(cx, |state, cx| {
8408                state.replace_text_in_range(None, "2024年12月", window, cx);
8409            });
8410        });
8411        cx.run_until_parked();
8412        cx.update(|_, cx| {
8413            input.read_with(cx, |state, _| {
8414                assert_eq!(state.value(), "2024年12月");
8415            });
8416        });
8417    }
8418
8419    #[gpui::test]
8420    fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
8421        let input_view = InputView::build(cx, |state| {
8422            state.mask_pattern(MaskPattern::Number {
8423                separator: Some(','),
8424                fraction: Some(2),
8425            })
8426        });
8427        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8428        let input = input_view.input;
8429
8430        cx.update(|window, cx| {
8431            input.update(cx, |state, cx| {
8432                state.replace_text_in_range(None, "1234", window, cx);
8433            });
8434        });
8435        cx.run_until_parked();
8436        cx.update(|_, cx| {
8437            input.read_with(cx, |state, _| {
8438                assert_eq!(state.value(), "1,234");
8439                assert_eq!(state.unmask_value(), "1234");
8440            });
8441        });
8442    }
8443
8444    #[gpui::test]
8445    fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
8446        let input_view = InputView::build(cx, |state| {
8447            state
8448                .mask_pattern(MaskPattern::Number {
8449                    separator: None,
8450                    fraction: None,
8451                })
8452                .min(10.)
8453                .max(100.)
8454        });
8455        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8456        let input = input_view.input;
8457
8458        // Out-of-range values are allowed while typing, and clamped on blur.
8459        cx.update(|window, cx| {
8460            input.update(cx, |state, cx| {
8461                state.replace_text_in_range(None, "1000", window, cx);
8462                assert_eq!(state.value(), "1000");
8463                state.clamp_number_value(window, cx);
8464                assert_eq!(state.value(), "100");
8465
8466                let range = state.range_to_utf16(&(0..state.text.len()));
8467                state.replace_text_in_range(Some(range), "1", window, cx);
8468                assert_eq!(state.value(), "1");
8469                state.clamp_number_value(window, cx);
8470                assert_eq!(state.value(), "10");
8471            });
8472        });
8473    }
8474
8475    #[gpui::test]
8476    fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
8477        let input_view = InputView::build(cx, |state| {
8478            state.mask_pattern(MaskPattern::Number {
8479                separator: Some(','),
8480                fraction: None,
8481            })
8482        });
8483        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8484        let input = input_view.input;
8485
8486        // When the mask changes the text (regrouping separators), a
8487        // whole-document change is recorded, so undo/redo can restore it.
8488        cx.update(|window, cx| {
8489            input.update(cx, |state, cx| {
8490                state.replace_text_in_range(None, "1234", window, cx);
8491                assert_eq!(state.value(), "1,234");
8492                state.replace_text_in_range(None, "5", window, cx);
8493                assert_eq!(state.value(), "12,345");
8494
8495                // Each whole-document mask rewrite is an atomic undo step.
8496                // Before the whole-document history fix, undo produced a
8497                // corrupted value like "1,2344".
8498                state.undo(&Undo, window, cx);
8499                assert_eq!(state.value(), "1,234");
8500                state.undo(&Undo, window, cx);
8501                assert_eq!(state.value(), "");
8502                state.redo(&Redo, window, cx);
8503                assert_eq!(state.value(), "1,234");
8504                state.redo(&Redo, window, cx);
8505                assert_eq!(state.value(), "12,345");
8506            });
8507        });
8508    }
8509
8510    #[gpui::test]
8511    fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
8512        let input_view = InputView::build(cx, |state| state);
8513        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8514        let input = input_view.input;
8515
8516        cx.update(|window, cx| {
8517            input.update(cx, |state, cx| {
8518                state.replace_text_in_range(None, "a", window, cx);
8519                state.replace_text_in_range(None, "b", window, cx);
8520                assert_eq!(state.value(), "ab");
8521
8522                state.undo(&Undo, window, cx);
8523                assert_eq!(state.value(), "");
8524            });
8525        });
8526    }
8527
8528    #[gpui::test]
8529    fn test_undo_manager_cursor_movement_splits_typing(cx: &mut TestAppContext) {
8530        let input_view = InputView::build(cx, |state| state);
8531        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8532        let input = input_view.input;
8533
8534        cx.update(|window, cx| {
8535            input.update(cx, |state, cx| {
8536                state.replace_text_in_range(None, "a", window, cx);
8537                state.replace_text_in_range(None, "b", window, cx);
8538                state.left(&MoveLeft, window, cx);
8539                state.replace_text_in_range(None, "x", window, cx);
8540                assert_eq!(state.value(), "axb");
8541
8542                state.undo(&Undo, window, cx);
8543                assert_eq!(state.value(), "ab");
8544                state.undo(&Undo, window, cx);
8545                assert_eq!(state.value(), "");
8546            });
8547        });
8548    }
8549
8550    #[gpui::test]
8551    fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
8552        let input_view = InputView::build(cx, |state| state);
8553        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8554        let input = input_view.input;
8555
8556        cx.update(|window, cx| {
8557            input.update(cx, |state, cx| {
8558                state.set_value("abcd", window, cx);
8559                state.set_selected_range(2..2, cx);
8560                state.backspace(&Backspace, window, cx);
8561                state.delete(&Delete, window, cx);
8562                assert_eq!(state.value(), "ad");
8563
8564                state.undo(&Undo, window, cx);
8565                assert_eq!(state.value(), "acd");
8566                state.undo(&Undo, window, cx);
8567                assert_eq!(state.value(), "abcd");
8568            });
8569        });
8570    }
8571
8572    #[gpui::test]
8573    fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
8574        let input_view = InputView::build(cx, |state| state);
8575        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8576        let input = input_view.input;
8577
8578        cx.update(|window, cx| {
8579            input.update(cx, |state, cx| {
8580                state.set_value("abcd", window, cx);
8581                state.backspace(&Backspace, window, cx);
8582                state.backspace(&Backspace, window, cx);
8583                assert_eq!(state.value(), "ab");
8584                state.undo(&Undo, window, cx);
8585                assert_eq!(state.value(), "abcd");
8586                assert_eq!(state.selected_range(), 4..4);
8587
8588                state.set_value("abcd", window, cx);
8589                state.set_selected_range(1..1, cx);
8590                state.delete(&Delete, window, cx);
8591                state.delete(&Delete, window, cx);
8592                assert_eq!(state.value(), "ad");
8593                state.undo(&Undo, window, cx);
8594                assert_eq!(state.value(), "abcd");
8595                assert_eq!(state.selected_range(), 1..1);
8596            });
8597        });
8598    }
8599
8600    #[gpui::test]
8601    fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
8602        let input_view = InputView::build(cx, |state| state);
8603        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8604        let input = input_view.input;
8605
8606        cx.update(|window, cx| {
8607            cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
8608            input.update(cx, |state, cx| {
8609                state.replace_text_in_range(None, "a", window, cx);
8610                state.paste(&Paste, window, cx);
8611                state.replace_text_in_range(None, "b", window, cx);
8612                assert_eq!(state.value(), "aPb");
8613
8614                state.undo(&Undo, window, cx);
8615                assert_eq!(state.value(), "aP");
8616                state.undo(&Undo, window, cx);
8617                assert_eq!(state.value(), "a");
8618                state.undo(&Undo, window, cx);
8619                assert_eq!(state.value(), "");
8620            });
8621        });
8622    }
8623
8624    #[gpui::test]
8625    fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
8626        let input_view = InputView::build(cx, |state| state);
8627        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8628        let input = input_view.input;
8629
8630        cx.update(|window, cx| {
8631            input.update(cx, |state, cx| {
8632                state.replace_text_in_range(None, "a", window, cx);
8633                state.insert("P", window, cx);
8634                state.replace_text_in_range(None, "b", window, cx);
8635                assert_eq!(state.value(), "aPb");
8636
8637                state.undo(&Undo, window, cx);
8638                assert_eq!(state.value(), "aP");
8639                state.undo(&Undo, window, cx);
8640                assert_eq!(state.value(), "a");
8641            });
8642        });
8643    }
8644
8645    #[gpui::test]
8646    fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
8647        let input_view = InputView::build(cx, |state| state);
8648        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8649        let input = input_view.input;
8650
8651        cx.update(|window, cx| {
8652            input.update(cx, |state, cx| {
8653                state.replace_text_in_range(None, "a", window, cx);
8654                state.replace_text_in_range(None, "b", window, cx);
8655                state.select_all(window, cx);
8656                state.unselect(window, cx);
8657                state.replace_text_in_range(None, "c", window, cx);
8658
8659                state.undo(&Undo, window, cx);
8660                assert_eq!(state.value(), "ab");
8661                state.undo(&Undo, window, cx);
8662                assert_eq!(state.value(), "");
8663            });
8664        });
8665    }
8666
8667    #[gpui::test]
8668    fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
8669        let input_view = InputView::build_textarea(cx, |state| state);
8670        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8671        let input = input_view.input;
8672
8673        cx.update(|window, cx| {
8674            input.update(cx, |state, cx| {
8675                state.replace_text_in_range(None, "a", window, cx);
8676                state.enter(
8677                    &Enter {
8678                        secondary: false,
8679                        shift: false,
8680                    },
8681                    window,
8682                    cx,
8683                );
8684                state.replace_text_in_range(None, "b", window, cx);
8685
8686                state.undo(&Undo, window, cx);
8687                assert_eq!(state.value(), "a\n");
8688                state.undo(&Undo, window, cx);
8689                assert_eq!(state.value(), "a");
8690                state.undo(&Undo, window, cx);
8691                assert_eq!(state.value(), "");
8692            });
8693        });
8694    }
8695
8696    #[gpui::test]
8697    fn test_textarea_secondary_enter_does_not_insert_newline(cx: &mut TestAppContext) {
8698        let input_view = InputView::build_textarea(cx, |state| state);
8699        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8700        let input = input_view.input;
8701
8702        cx.update(|window, cx| {
8703            input.update(cx, |state, cx| {
8704                state.replace_text_in_range(None, "hello", window, cx);
8705                state.set_selection(0, 0);
8706                state.enter(
8707                    &Enter {
8708                        secondary: true,
8709                        shift: false,
8710                    },
8711                    window,
8712                    cx,
8713                );
8714                assert_eq!(state.value(), "hello");
8715            });
8716        });
8717    }
8718
8719    #[gpui::test]
8720    fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
8721        let input_view = InputView::build(cx, |state| state);
8722        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8723        let input = input_view.input;
8724
8725        cx.update(|window, cx| {
8726            input.update(cx, |state, cx| {
8727                for part in ["a", "b", "c"] {
8728                    state.replace_text_in_range(None, part, window, cx);
8729                }
8730                state.enter(
8731                    &Enter {
8732                        secondary: false,
8733                        shift: false,
8734                    },
8735                    window,
8736                    cx,
8737                );
8738                for part in ["d", "e", "f"] {
8739                    state.replace_text_in_range(None, part, window, cx);
8740                }
8741                assert_eq!(state.value(), "abcdef");
8742
8743                state.undo(&Undo, window, cx);
8744                assert_eq!(state.value(), "abc");
8745                state.undo(&Undo, window, cx);
8746                assert_eq!(state.value(), "");
8747            });
8748        });
8749    }
8750
8751    #[gpui::test]
8752    fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
8753        let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
8754        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8755        let input = input_view.input;
8756
8757        cx.update(|window, cx| {
8758            input.update(cx, |state, cx| {
8759                state.replace_text_in_range(None, "before submit", window, cx);
8760                state.enter(
8761                    &Enter {
8762                        secondary: false,
8763                        shift: false,
8764                    },
8765                    window,
8766                    cx,
8767                );
8768                state.replace_text_in_range(None, " after submit", window, cx);
8769                assert_eq!(state.value(), "before submit after submit");
8770
8771                state.undo(&Undo, window, cx);
8772                assert_eq!(state.value(), "before submit");
8773                state.undo(&Undo, window, cx);
8774                assert_eq!(state.value(), "");
8775            });
8776        });
8777    }
8778
8779    #[gpui::test]
8780    fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
8781        let input_view = InputView::build(cx, |state| state);
8782        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8783        let input = input_view.input;
8784
8785        cx.update(|window, cx| {
8786            input.update(cx, |state, cx| {
8787                state.replace_text_in_range(None, "before blur", window, cx);
8788                state.on_blur(window, cx);
8789                state.on_focus(window, cx);
8790                state.replace_text_in_range(None, " after focus", window, cx);
8791                assert_eq!(state.value(), "before blur after focus");
8792
8793                state.undo(&Undo, window, cx);
8794                assert_eq!(state.value(), "before blur");
8795                state.undo(&Undo, window, cx);
8796                assert_eq!(state.value(), "");
8797            });
8798        });
8799    }
8800
8801    #[gpui::test]
8802    fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
8803        let input_view = InputView::build_textarea(cx, |state| state);
8804        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8805        let input = input_view.input;
8806
8807        cx.update(|window, cx| {
8808            input.update(cx, |state, cx| {
8809                let enter = Enter {
8810                    secondary: false,
8811                    shift: false,
8812                };
8813                state.replace_text_in_range(None, "a", window, cx);
8814                state.enter(&enter, window, cx);
8815                state.replace_text_in_range(None, "b", window, cx);
8816                state.enter(&enter, window, cx);
8817                state.replace_text_in_range(None, "c", window, cx);
8818                assert_eq!(state.value(), "a\nb\nc");
8819
8820                for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
8821                    state.undo(&Undo, window, cx);
8822                    assert_eq!(state.value(), expected);
8823                }
8824            });
8825        });
8826    }
8827
8828    #[gpui::test]
8829    fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
8830        let input_view = InputView::build_textarea(cx, |state| state);
8831        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8832        let input = input_view.input;
8833        let parts = [
8834            "The ",
8835            "quick ",
8836            "brown fox, ",
8837            "你好,世界 ",
8838            "🦀 jumps over 13 lazy dogs.",
8839        ];
8840        let expected = parts.concat();
8841
8842        cx.update(|window, cx| {
8843            input.update(cx, |state, cx| {
8844                for part in parts {
8845                    state.replace_text_in_range(None, part, window, cx);
8846                }
8847                assert_eq!(state.value(), expected);
8848
8849                state.undo(&Undo, window, cx);
8850                assert_eq!(state.value(), "");
8851                state.redo(&Redo, window, cx);
8852                assert_eq!(state.value(), expected);
8853            });
8854        });
8855    }
8856
8857    #[gpui::test]
8858    fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
8859        cx: &mut TestAppContext,
8860    ) {
8861        let input_view = InputView::build_textarea(cx, |state| state);
8862        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8863        let input = input_view.input;
8864        let enter = Enter {
8865            secondary: false,
8866            shift: false,
8867        };
8868
8869        cx.update(|window, cx| {
8870            input.update(cx, |state, cx| {
8871                for (index, line) in [
8872                    "first line with punctuation!",
8873                    "第二行包含 Unicode 🦀",
8874                    "third line has several words",
8875                ]
8876                .into_iter()
8877                .enumerate()
8878                {
8879                    for chunk in line.split_inclusive(' ') {
8880                        state.replace_text_in_range(None, chunk, window, cx);
8881                    }
8882                    if index < 2 {
8883                        state.enter(&enter, window, cx);
8884                    }
8885                }
8886
8887                assert_eq!(
8888                    state.value(),
8889                    "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
8890                );
8891                state.undo(&Undo, window, cx);
8892                assert_eq!(
8893                    state.value(),
8894                    "first line with punctuation!\n第二行包含 Unicode 🦀\n"
8895                );
8896                state.undo(&Undo, window, cx);
8897                assert_eq!(
8898                    state.value(),
8899                    "first line with punctuation!\n第二行包含 Unicode 🦀"
8900                );
8901                state.undo(&Undo, window, cx);
8902                assert_eq!(state.value(), "first line with punctuation!\n");
8903            });
8904        });
8905    }
8906
8907    #[gpui::test]
8908    fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
8909        let input_view = InputView::build(cx, |state| state);
8910        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8911        let input = input_view.input;
8912
8913        cx.update(|window, cx| {
8914            input.update(cx, |state, cx| {
8915                state.set_value("hunter2", window, cx);
8916                state.set_masked(true, window, cx);
8917                state.select_all(window, cx);
8918                cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
8919
8920                state.copy(&Copy, window, cx);
8921                assert_eq!(
8922                    cx.read_from_clipboard().and_then(|item| item.text()),
8923                    Some("sentinel".to_string())
8924                );
8925
8926                // Cut neither copies nor deletes.
8927                state.cut(&Cut, window, cx);
8928                assert_eq!(state.value(), "hunter2");
8929                assert_eq!(
8930                    cx.read_from_clipboard().and_then(|item| item.text()),
8931                    Some("sentinel".to_string())
8932                );
8933
8934                // Revealing the value restores both.
8935                state.set_masked(false, window, cx);
8936                state.copy(&Copy, window, cx);
8937                assert_eq!(
8938                    cx.read_from_clipboard().and_then(|item| item.text()),
8939                    Some("hunter2".to_string())
8940                );
8941            });
8942        });
8943    }
8944
8945    #[gpui::test]
8946    fn test_masked_input_redacts_ime_text(cx: &mut TestAppContext) {
8947        let input_view = InputView::build(cx, |state| state.masked(true).default_value("a🦀b"));
8948        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8949        cx.update(|window, cx| {
8950            input_view.input.update(cx, |state, cx| {
8951                let mut adjusted = None;
8952                assert_eq!(
8953                    state.text_for_range(1..5, &mut adjusted, window, cx),
8954                    Some("•••".into())
8955                );
8956                assert_eq!(adjusted, Some(1..4));
8957
8958                state.set_masked(false, window, cx);
8959                assert_eq!(
8960                    state.text_for_range(1..5, &mut adjusted, window, cx),
8961                    Some("🦀b".into())
8962                );
8963                assert_eq!(adjusted, Some(1..4));
8964            });
8965        });
8966    }
8967
8968    #[gpui::test]
8969    fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
8970        let input_view = InputView::build(cx, |state| state);
8971        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8972        let input = input_view.input;
8973
8974        cx.update(|window, cx| {
8975            input.update(cx, |state, cx| {
8976                state.set_value("aaa bbb ccc", window, cx);
8977                state.set_masked(true, window, cx);
8978                state.set_selected_range(7..7, cx);
8979
8980                // The mask hides word boundaries, so a word delete takes
8981                // everything before the caret and leaves the rest.
8982                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8983                assert_eq!(state.value(), " ccc");
8984                assert_eq!(state.selected_range(), 0..0);
8985
8986                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
8987                assert_eq!(state.value(), "");
8988
8989                // A double click takes the whole value, not one word.
8990                state.set_value("aaa bbb ccc", window, cx);
8991                state.select_word(9, window, cx);
8992                assert_eq!(state.selected_range(), 0..11);
8993
8994                // Unmasked, the same delete only takes one word.
8995                state.set_masked(false, window, cx);
8996                state.set_value("aaa bbb ccc", window, cx);
8997                state.set_selected_range(11..11, cx);
8998                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
8999                assert_eq!(state.value(), "aaa bbb ");
9000
9001                state.set_value("aaa bbb ccc", window, cx);
9002                state.select_word(9, window, cx);
9003                assert_eq!(state.selected_range(), 8..11);
9004            });
9005        });
9006    }
9007
9008    #[gpui::test]
9009    fn test_ctrl_delete_stops_at_whitespace(cx: &mut TestAppContext) {
9010        let input_view = InputView::build_textarea(cx, |state| state);
9011        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9012        let input = input_view.input;
9013
9014        cx.update(|window, cx| {
9015            input.update(cx, |state, cx| {
9016                // Indentation goes on its own, the word after it stays.
9017                state.set_value("    four leading spaces", window, cx);
9018                assert_eq!(state.next_word_delete_end_at(0, true), 4);
9019                assert_eq!(state.next_word_delete_end_at(4, true), 8);
9020                assert_eq!(state.next_word_delete_end_at(8, true), 9);
9021                // macOS Option+Delete still takes the blanks and the word.
9022                assert_eq!(state.next_word_delete_end_at(0, false), 8);
9023
9024                // At a line end only the line break goes, not the next
9025                // line's indentation or first word.
9026                state.set_value("one\n    two", window, cx);
9027                assert_eq!(state.next_word_delete_end_at(3, true), 4);
9028                state.set_value("one\r\n  two", window, cx);
9029                assert_eq!(state.next_word_delete_end_at(3, true), 5);
9030                // Trailing blanks stop at the line break.
9031                state.set_value("one  \ntwo", window, cx);
9032                assert_eq!(state.next_word_delete_end_at(3, true), 5);
9033
9034                state.set_value("    four leading spaces", window, cx);
9035                state.set_selected_range(0..0, cx);
9036                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
9037                #[cfg(not(target_os = "macos"))]
9038                assert_eq!(state.value(), "four leading spaces");
9039                #[cfg(target_os = "macos")]
9040                assert_eq!(state.value(), " leading spaces");
9041            });
9042        });
9043    }
9044
9045    #[gpui::test]
9046    fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
9047        let input_view = InputView::build(cx, |state| state);
9048        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9049        let input = input_view.input;
9050
9051        cx.update(|window, cx| {
9052            input.update(cx, |state, cx| {
9053                state.set_value("hunter2", window, cx);
9054                state.select_all(window, cx);
9055                assert!(state.context_menu_capabilities().is_copyable());
9056
9057                state.set_masked(true, window, cx);
9058                let capabilities = state.context_menu_capabilities();
9059                assert!(capabilities.is_masked());
9060                assert!(capabilities.has_selection());
9061                assert!(!capabilities.is_copyable());
9062            });
9063        });
9064    }
9065
9066    #[gpui::test]
9067    fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
9068        cx: &mut TestAppContext,
9069    ) {
9070        let input_view = InputView::build(cx, |state| state);
9071        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9072        let input = input_view.input;
9073
9074        cx.update(|window, cx| {
9075            input.update(cx, |state, cx| {
9076                state.replace_text_in_range(None, "alpha beta gamma", window, cx);
9077                state.set_selected_range(6..10, cx);
9078                state.cut(&Cut, window, cx);
9079                assert_eq!(state.value(), "alpha  gamma");
9080
9081                state.paste(&Paste, window, cx);
9082                state.paste(&Paste, window, cx);
9083                assert_eq!(state.value(), "alpha betabeta gamma");
9084
9085                state.undo(&Undo, window, cx);
9086                assert_eq!(state.value(), "alpha beta gamma");
9087                state.undo(&Undo, window, cx);
9088                assert_eq!(state.value(), "alpha  gamma");
9089                state.undo(&Undo, window, cx);
9090                assert_eq!(state.value(), "alpha beta gamma");
9091            });
9092        });
9093    }
9094
9095    #[gpui::test]
9096    fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
9097        let input_view = InputView::build_textarea(cx, |state| state);
9098        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9099        let input = input_view.input;
9100
9101        cx.update(|window, cx| {
9102            input.update(cx, |state, cx| {
9103                state.set_value("one two three\nfour five", window, cx);
9104                state.set_selected_range(13..13, cx);
9105                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
9106                assert_eq!(state.value(), "one two \nfour five");
9107                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
9108                assert_eq!(state.value(), "one two four five");
9109
9110                state.undo(&Undo, window, cx);
9111                assert_eq!(state.value(), "one two \nfour five");
9112                state.undo(&Undo, window, cx);
9113                assert_eq!(state.value(), "one two three\nfour five");
9114            });
9115        });
9116    }
9117
9118    #[gpui::test]
9119    fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
9120        let input_view = InputView::build_textarea(cx, |state| state);
9121        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9122        let input = input_view.input;
9123
9124        cx.update(|window, cx| {
9125            input.update(cx, |state, cx| {
9126                state.replace_text_in_range(None, "before", window, cx);
9127                state.set_selected_range(0..6, cx);
9128                state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
9129                assert_eq!(state.value(), "line one\nline two\n第三行");
9130
9131                state.undo(&Undo, window, cx);
9132                assert_eq!(state.value(), "before");
9133                assert_eq!(state.selected_range(), 0..6);
9134                state.redo(&Redo, window, cx);
9135                assert_eq!(state.value(), "line one\nline two\n第三行");
9136            });
9137        });
9138    }
9139
9140    #[gpui::test]
9141    fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
9142        let input_view = InputView::build(cx, |state| state);
9143        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9144        let input = input_view.input;
9145
9146        cx.update(|window, cx| {
9147            input.update(cx, |state, cx| {
9148                state.replace_text_in_range(None, "prefix ", window, cx);
9149                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
9150                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
9151                state.replace_and_mark_text_in_range(None, "你", None, window, cx);
9152                state.unmark_text(window, cx);
9153                state.replace_text_in_range(None, " suffix", window, cx);
9154                assert_eq!(state.value(), "prefix 你 suffix");
9155
9156                state.undo(&Undo, window, cx);
9157                assert_eq!(state.value(), "prefix 你");
9158                state.undo(&Undo, window, cx);
9159                assert_eq!(state.value(), "prefix ");
9160                state.undo(&Undo, window, cx);
9161                assert_eq!(state.value(), "");
9162            });
9163        });
9164    }
9165
9166    #[gpui::test]
9167    fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
9168        let input_view = InputView::build(cx, |state| state);
9169        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9170        let input = input_view.input;
9171
9172        cx.update(|window, cx| {
9173            input.update(cx, |state, cx| {
9174                state.replace_text_in_range(None, "abc", window, cx);
9175                state.set_selected_range(1..2, cx);
9176                state.replace_text_in_range(None, "X", window, cx);
9177                state.replace_text_in_range(None, "z", window, cx);
9178                assert_eq!(state.value(), "aXzc");
9179
9180                state.undo(&Undo, window, cx);
9181                assert_eq!(state.value(), "aXc");
9182                state.undo(&Undo, window, cx);
9183                assert_eq!(state.value(), "abc");
9184                state.undo(&Undo, window, cx);
9185                assert_eq!(state.value(), "");
9186            });
9187        });
9188    }
9189
9190    #[gpui::test]
9191    fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
9192        let input_view = InputView::build(cx, |state| {
9193            state.mask_pattern(MaskPattern::Number {
9194                separator: None,
9195                fraction: None,
9196            })
9197        });
9198        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9199        let input = input_view.input;
9200
9201        cx.update(|window, cx| {
9202            input.update(cx, |state, cx| {
9203                state.replace_text_in_range(None, "1.2", window, cx);
9204
9205                // Delete the integer part "1": the value keeps the leading dot
9206                // (".2"), not completed to "0.2", so the digits before the dot
9207                // stay editable.
9208                let range = state.range_to_utf16(&(0..1));
9209                state.replace_text_in_range(Some(range), "", window, cx);
9210                assert_eq!(state.value(), ".2");
9211                let cursor: Range<usize> = state.selected_range();
9212                assert_eq!(cursor, 0..0);
9213
9214                // The user can type a new integer part.
9215                state.replace_text_in_range(Some(0..0), "3", window, cx);
9216                assert_eq!(state.value(), "3.2");
9217            });
9218        });
9219    }
9220
9221    #[gpui::test]
9222    fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
9223        // A pre-existing invalid text (e.g. a `default_value` that does not
9224        // conform) must not trap the user, the edit is allowed to fix it.
9225        let input_view = InputView::build(cx, |state| {
9226            state
9227                .mask_pattern(MaskPattern::Number {
9228                    separator: None,
9229                    fraction: None,
9230                })
9231                .default_value("1,234")
9232        });
9233        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9234        let input = input_view.input;
9235
9236        cx.update(|window, cx| {
9237            input.update(cx, |state, cx| {
9238                // Delete the last char, the pending text "1,23" is still
9239                // invalid, but the edit is allowed since the old text was
9240                // already invalid.
9241                let range = state.range_to_utf16(&(4..5));
9242                state.replace_text_in_range(Some(range), "", window, cx);
9243                assert_eq!(state.value(), "1,23");
9244
9245                // Once the text becomes valid, the validation works as usual.
9246                let range = state.range_to_utf16(&(1..2));
9247                state.replace_text_in_range(Some(range), "", window, cx);
9248                assert_eq!(state.value(), "123");
9249                state.replace_text_in_range(None, "a", window, cx);
9250                assert_eq!(state.value(), "123");
9251            });
9252        });
9253    }
9254
9255    /// After `set_value` on a single-line input the caret sits at the end (like
9256    /// HTML `<input>`), yet the view is scrolled back to the start so a long
9257    /// value shows its beginning instead of its tail.
9258    #[gpui::test]
9259    fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
9260        let input_view = InputView::build(cx, |state| state);
9261        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9262        let input = input_view.input;
9263
9264        // Long enough to overflow any reasonable single-line input width.
9265        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9266        let len = value.len();
9267
9268        // Right after `set_value`, before the next paint consumes the deferred
9269        // offset: caret is at the end, and the view is forced back to the start.
9270        cx.update(|window, cx| {
9271            input.update(cx, |state, cx| {
9272                state.set_value(value.clone(), window, cx);
9273
9274                assert_eq!(
9275                    state.selected_range(),
9276                    len..len,
9277                    "single-line caret should be at the end after set_value"
9278                );
9279                assert_eq!(
9280                    state.deferred_scroll_offset,
9281                    Some(point(px(0.), px(0.))),
9282                    "the view should be forced back to the start"
9283                );
9284            });
9285        });
9286
9287        // After a paint, the steady-state view stays at the start (x == 0) even
9288        // though the caret is at the far end.
9289        cx.run_until_parked();
9290        cx.update(|_, cx| {
9291            input.read_with(cx, |state, _| {
9292                assert!(
9293                    state.scroll_size.width > state.input_bounds.size.width,
9294                    "value must overflow the input width or this test is vacuous"
9295                );
9296                assert_eq!(
9297                    state.scroll_handle.offset().x,
9298                    px(0.),
9299                    "long value should display from its start, not its tail"
9300                );
9301            });
9302        });
9303    }
9304
9305    /// `replace_all` on a single-line input replaces the text, puts the
9306    /// caret at the end, and — like `set_value` — snaps the view back to the
9307    /// start so a long value shows its beginning instead of its tail.
9308    #[gpui::test]
9309    fn test_replace_all_single_line(cx: &mut TestAppContext) {
9310        let input_view = InputView::build(cx, |state| state);
9311        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9312        let input = input_view.input;
9313
9314        // Long enough to overflow any reasonable single-line input width.
9315        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9316        let len = value.len();
9317
9318        // Right after `replace_all`, before the next paint consumes the
9319        // deferred offset: caret is at the end, and the view is forced back
9320        // to the start.
9321        cx.update(|window, cx| {
9322            input.update(cx, |state, cx| {
9323                state.set_value("hello", window, cx);
9324                state.replace_all(value.clone(), window, cx);
9325                assert_eq!(state.value(), value);
9326                assert_eq!(
9327                    state.selected_range(),
9328                    len..len,
9329                    "single-line caret should be at the end after replace_all"
9330                );
9331                assert_eq!(
9332                    state.scroll_handle.offset(),
9333                    point(px(0.), px(0.)),
9334                    "the scroll offset should be reset to the start"
9335                );
9336                assert_eq!(
9337                    state.deferred_scroll_offset,
9338                    Some(point(px(0.), px(0.))),
9339                    "single-line should set a deferred scroll offset to keep the start visible"
9340                );
9341            });
9342        });
9343
9344        // After a paint, the steady-state view stays at the start (x == 0)
9345        // even though the caret is at the far end.
9346        cx.run_until_parked();
9347        cx.update(|_, cx| {
9348            input.read_with(cx, |state, _| {
9349                assert!(
9350                    state.scroll_size.width > state.input_bounds.size.width,
9351                    "value must overflow the input width or this test is vacuous"
9352                );
9353                assert_eq!(
9354                    state.scroll_handle.offset().x,
9355                    px(0.),
9356                    "long value should display from its start, not its tail"
9357                );
9358            });
9359        });
9360    }
9361
9362    /// Pasting past the right edge of a single-line input scrolls the caret
9363    /// into view in the paint that lays the pasted text out.
9364    #[gpui::test]
9365    fn test_paste_reveals_caret_single_line(cx: &mut TestAppContext) {
9366        let input_view = InputView::build(cx, |state| state);
9367        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9368        let input = input_view.input;
9369        cx.run_until_parked();
9370
9371        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9372        cx.update(|window, cx| {
9373            cx.write_to_clipboard(ClipboardItem::new_string(value.clone()));
9374            input.update(cx, |state, cx| state.paste(&Paste, window, cx));
9375        });
9376        cx.run_until_parked();
9377
9378        cx.update(|_, cx| {
9379            input.read_with(cx, |state, _| {
9380                assert!(
9381                    state.scroll_size.width > state.input_bounds.size.width,
9382                    "value must overflow the input width or this test is vacuous"
9383                );
9384                let caret = state
9385                    .last_layout
9386                    .as_ref()
9387                    .and_then(|layout| layout.cursor_bounds)
9388                    .expect("a caret");
9389                assert!(
9390                    caret.left() >= state.input_bounds.left()
9391                        && caret.right() <= state.input_bounds.right(),
9392                    "the caret at {caret:?} should be inside {:?}",
9393                    state.input_bounds
9394                );
9395            });
9396        });
9397    }
9398
9399    #[gpui::test]
9400    fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
9401        let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
9402        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9403        let input = input_view.input;
9404
9405        cx.update(|window, cx| {
9406            input.update(cx, |state, cx| {
9407                assert_eq!(state.value(), "defaultvalue");
9408
9409                state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
9410                assert_eq!(state.value(), "firstsecondthirdfourth");
9411
9412                state.set_value("", window, cx);
9413                state.insert("a\nb", window, cx);
9414                assert_eq!(state.value(), "ab");
9415            });
9416
9417            cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
9418            input.update(cx, |state, cx| {
9419                state.set_value("", window, cx);
9420                state.paste(&Paste, window, cx);
9421                assert_eq!(state.value(), "abcd");
9422            });
9423        });
9424
9425        cx.run_until_parked();
9426    }
9427
9428    /// Tab is bound to `IndentInline`, which a single-line input propagates.
9429    /// Unhandled, the keystroke reaches the input as text, so the field
9430    /// drops the tab as it drops a newline. See issue #4069.
9431    #[gpui::test]
9432    fn test_single_line_removes_tabs(cx: &mut TestAppContext) {
9433        let input_view = InputView::build(cx, |state| state);
9434        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9435        let input = input_view.input;
9436
9437        cx.update(|window, cx| {
9438            input.update(cx, |state, cx| state.focus(window, cx));
9439        });
9440        cx.run_until_parked();
9441
9442        cx.simulate_input("a");
9443        cx.simulate_keystrokes("tab");
9444        cx.simulate_input("b");
9445        input.read_with(&cx, |state, _| assert_eq!(state.value(), "ab"));
9446
9447        cx.update(|window, cx| {
9448            input.update(cx, |state, cx| {
9449                state.set_value("c\td\ne", window, cx);
9450                assert_eq!(state.value(), "cde");
9451            });
9452        });
9453    }
9454
9455    /// `replace_all` on a multi-line (non-code-editor) input clears the
9456    /// selection to `0..0` and resets the scroll offset, but does not set a
9457    /// deferred scroll offset (single-line only).
9458    #[gpui::test]
9459    fn test_replace_all_multi_line(cx: &mut TestAppContext) {
9460        let input_view = InputView::build_textarea(cx, |state| state);
9461        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9462        let input = input_view.input;
9463
9464        cx.update(|window, cx| {
9465            input.update(cx, |state, cx| {
9466                state.set_value("foo\nbar", window, cx);
9467                state.replace_all("baz\nqux", window, cx);
9468                assert_eq!(state.value(), "baz\nqux");
9469                assert_eq!(
9470                    state.selected_range(),
9471                    0..0,
9472                    "multi-line selection should be cleared after replace_all"
9473                );
9474                assert_eq!(
9475                    state.scroll_handle.offset(),
9476                    point(px(0.), px(0.)),
9477                    "the scroll offset should be reset to the start"
9478                );
9479                assert!(
9480                    state.deferred_scroll_offset.is_none(),
9481                    "multi-line should not set a deferred scroll offset"
9482                );
9483            });
9484        });
9485    }
9486
9487    /// Unlike `set_value`, `replace_all` records the change so the user can
9488    /// undo it back to the previous text and redo to the new text.
9489    #[gpui::test]
9490    fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
9491        let input_view = InputView::build(cx, |state| state);
9492        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9493        let input = input_view.input;
9494
9495        cx.update(|window, cx| {
9496            input.update(cx, |state, cx| {
9497                // Seed with a value and clear history so the baseline is clean.
9498                state.set_value("first", window, cx);
9499                assert!(
9500                    !state.undo_manager.has_undos(),
9501                    "history should be empty after set_value"
9502                );
9503
9504                // replace_all records a single undoable change.
9505                state.replace_all("second", window, cx);
9506                assert_eq!(state.value(), "second");
9507                assert!(
9508                    state.undo_manager.has_undos(),
9509                    "replace_all should record an undo step"
9510                );
9511
9512                // Undo restores the previous text.
9513                state.undo(&Undo, window, cx);
9514                assert_eq!(state.value(), "first");
9515
9516                // Redo reapplies the replacement.
9517                state.redo(&Redo, window, cx);
9518                assert_eq!(state.value(), "second");
9519            });
9520        });
9521    }
9522
9523    /// `replace_all` on a code editor marks a pending update and resets LSP
9524    /// state, so diagnostics/completions refresh against the new text.
9525    #[gpui::test]
9526    fn test_replace_all_code_editor(cx: &mut TestAppContext) {
9527        let input_view = InputView::new(cx);
9528        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9529        let input = input_view.input;
9530
9531        cx.update(|window, cx| {
9532            input.update(cx, |state, cx| {
9533                // Plant a pending-update flag and some LSP state to verify reset.
9534                state.set_value("select 1", window, cx);
9535                state._pending_update = false;
9536
9537                state.replace_all("select 2", window, cx);
9538                assert_eq!(state.value(), "select 2");
9539                assert!(
9540                    state._pending_update,
9541                    "replace_all on a code editor should request a pending update"
9542                );
9543            });
9544        });
9545    }
9546
9547    #[gpui::test]
9548    fn test_set_selected_range(cx: &mut TestAppContext) {
9549        let input_view = InputView::build(cx, |state| state.default_value("hello world"));
9550        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9551        let input = input_view.input;
9552
9553        cx.update(|_, cx| {
9554            input.update(cx, |s, cx| {
9555                s.set_selected_range(0..5, cx);
9556                assert_eq!(s.selected_range(), 0..5);
9557                assert_eq!(s.selected_text().to_string(), "hello");
9558
9559                s.set_selected_range(6..11, cx);
9560                assert_eq!(s.selected_text().to_string(), "world");
9561
9562                // clamped + collapsed
9563                s.set_selected_range(100..100, cx);
9564                assert_eq!(s.selected_range(), 11..11);
9565            });
9566        });
9567    }
9568
9569    /// A single-edit batch round-trips through undo/redo.
9570    #[gpui::test]
9571    fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
9572        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9573        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9574        let input = input_view.input;
9575
9576        cx.update(|window, cx| {
9577            input.update(cx, |s, cx| {
9578                s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
9579                assert_eq!(s.value(), "HELLO world");
9580
9581                s.undo(&Undo, window, cx);
9582                assert_eq!(s.value(), "hello world");
9583
9584                s.redo(&Redo, window, cx);
9585                assert_eq!(s.value(), "HELLO world");
9586            });
9587        });
9588    }
9589
9590    /// A single undo restores the exact original text and a single redo
9591    /// re-applies all edits, verifying the back-to-front application ordering.
9592    #[gpui::test]
9593    fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
9594        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9595        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9596        let input = input_view.input;
9597
9598        cx.update(|window, cx| {
9599            input.update(cx, |s, cx| {
9600                // Two edits at different positions, given in pre-edit
9601                // coordinates and in arbitrary (non-sorted) order.
9602                s.replace_text_in_ranges(
9603                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9604                    window,
9605                    cx,
9606                );
9607                assert_eq!(s.value(), "X bbb Y");
9608
9609                // One collapsed cursor per edit, at the end of each inserted text.
9610                let cursors: Vec<usize> =
9611                    s.selections.iter().map(|sel| sel.cursor_offset()).collect();
9612                assert_eq!(cursors, vec![1, 7]);
9613
9614                // The whole batch is a single undo transaction.
9615                assert_eq!(s.undo_manager.undo_count(), 1);
9616
9617                // One undo restores the exact original text.
9618                s.undo(&Undo, window, cx);
9619                assert_eq!(s.value(), "aaa bbb ccc");
9620
9621                // One redo re-applies all edits.
9622                s.redo(&Redo, window, cx);
9623                assert_eq!(s.value(), "X bbb Y");
9624            });
9625        });
9626    }
9627
9628    /// A multi-edit change reaches the highlighter once, with every edit in
9629    /// application order and the text right after each, which is what the
9630    /// default `update_batch` replays through `update` one edit at a time.
9631    #[gpui::test]
9632    fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
9633        use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
9634        use gpui::HighlightStyle;
9635        use std::cell::RefCell;
9636
9637        struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
9638
9639        impl InputHighlighter for RecordingHighlighter {
9640            fn language(&self) -> SharedString {
9641                "recording".into()
9642            }
9643
9644            fn update(
9645                &mut self,
9646                _: Option<InputEdit>,
9647                text: &Rope,
9648                _: bool,
9649                _: &mut Window,
9650                _: &mut Context<EditorState>,
9651            ) {
9652                self.0.borrow_mut().push(vec![text.to_string()]);
9653            }
9654
9655            fn update_batch(
9656                &mut self,
9657                edits: &[(InputEdit, Rope)],
9658                _: bool,
9659                _: &mut Window,
9660                _: &mut Context<EditorState>,
9661            ) {
9662                let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
9663                self.0.borrow_mut().push(texts);
9664            }
9665
9666            fn styles(
9667                &self,
9668                range: &Range<usize>,
9669                _: &dyn HighlightStyleResolver,
9670            ) -> Vec<(Range<usize>, HighlightStyle)> {
9671                vec![(range.clone(), HighlightStyle::default())]
9672            }
9673
9674            fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
9675                Vec::new()
9676            }
9677        }
9678
9679        let updates = Rc::new(RefCell::new(Vec::new()));
9680        let input_view = InputView::new(cx);
9681        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9682        let input = input_view.input;
9683
9684        cx.update(|window, cx| {
9685            input.update(cx, |s, cx| {
9686                s.set_value("aaa bbb ccc", window, cx);
9687                let recorded = updates.clone();
9688                s.set_highlighter_factory(
9689                    Rc::new(move |_: &str| {
9690                        let highlighter: Box<dyn InputHighlighter> =
9691                            Box::new(RecordingHighlighter(recorded.clone()));
9692                        Some(highlighter)
9693                    }),
9694                    cx,
9695                );
9696                s.replace_text_in_ranges(
9697                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9698                    window,
9699                    cx,
9700                );
9701            });
9702        });
9703
9704        assert_eq!(
9705            *updates.borrow(),
9706            vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
9707        );
9708    }
9709
9710    /// One keypress records a single edit with the text right after it.
9711    #[gpui::test]
9712    fn test_last_input_edits_single_insert(cx: &mut TestAppContext) {
9713        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9714        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9715        let input = input_view.input;
9716
9717        cx.update(|window, cx| {
9718            input.update(cx, |state, cx| {
9719                state.replace_text_in_ranges(&[(5..5, " big".to_string())], window, cx);
9720
9721                let edits = state.last_input_edits.as_slice();
9722                assert_eq!(edits.len(), 1);
9723                let (edit, text_after) = &edits[0];
9724                assert_eq!(edit.start_byte, 5);
9725                assert_eq!(edit.old_end_byte, 5);
9726                assert_eq!(edit.new_end_byte, 9);
9727                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9728                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9729                assert_eq!(edit.new_end_position, crate::input::Point::new(0, 9));
9730                assert_eq!(text_after.to_string(), "hello big world");
9731            });
9732        });
9733    }
9734
9735    /// Deletion and a multi-line paste each describe their whole replacement.
9736    #[gpui::test]
9737    fn test_last_input_edits_delete_and_paste(cx: &mut TestAppContext) {
9738        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9739        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9740        let input = input_view.input;
9741
9742        cx.update(|window, cx| {
9743            input.update(cx, |state, cx| {
9744                state.replace_text_in_ranges(&[(5..11, String::new())], window, cx);
9745                assert_eq!(state.value(), "hello");
9746
9747                let edits = state.last_input_edits.as_slice();
9748                assert_eq!(edits.len(), 1);
9749                let (edit, text_after) = &edits[0];
9750                assert_eq!(edit.start_byte, 5);
9751                assert_eq!(edit.old_end_byte, 11);
9752                assert_eq!(edit.new_end_byte, 5);
9753                assert_eq!(text_after.to_string(), "hello");
9754
9755                state.replace_text_in_ranges(&[(5..5, "\nnext".to_string())], window, cx);
9756                assert_eq!(state.value(), "hello\nnext");
9757
9758                let edits = state.last_input_edits.as_slice();
9759                assert_eq!(edits.len(), 1);
9760                let (edit, text_after) = &edits[0];
9761                assert_eq!(edit.start_byte, 5);
9762                assert_eq!(edit.old_end_byte, 5);
9763                assert_eq!(edit.new_end_byte, 10);
9764                assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9765                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9766                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 4));
9767                assert_eq!(text_after.to_string(), "hello\nnext");
9768            });
9769        });
9770    }
9771
9772    /// A grouped change records every applied edit in application order.
9773    #[gpui::test]
9774    fn test_last_input_edits_grouped_change(cx: &mut TestAppContext) {
9775        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9776        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9777        let input = input_view.input;
9778
9779        cx.update(|window, cx| {
9780            input.update(cx, |state, cx| {
9781                state.replace_text_in_ranges(
9782                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9783                    window,
9784                    cx,
9785                );
9786                assert_eq!(state.value(), "X bbb Y");
9787
9788                let edits = state.last_input_edits.as_slice();
9789                assert_eq!(edits.len(), 2);
9790                // The higher offset is applied first, before the lower one.
9791                assert_eq!(edits[0].0.start_byte, 8);
9792                assert_eq!(edits[0].0.old_end_byte, 11);
9793                assert_eq!(edits[0].0.new_end_byte, 9);
9794                assert_eq!(edits[0].0.start_position, crate::input::Point::new(0, 8));
9795                assert_eq!(edits[0].0.old_end_position, crate::input::Point::new(0, 11));
9796                assert_eq!(edits[0].0.new_end_position, crate::input::Point::new(0, 9));
9797                assert_eq!(edits[0].1.to_string(), "aaa bbb Y");
9798
9799                assert_eq!(edits[1].0.start_byte, 0);
9800                assert_eq!(edits[1].0.old_end_byte, 3);
9801                assert_eq!(edits[1].0.new_end_byte, 1);
9802                assert_eq!(edits[1].0.start_position, crate::input::Point::new(0, 0));
9803                assert_eq!(edits[1].0.old_end_position, crate::input::Point::new(0, 3));
9804                assert_eq!(edits[1].0.new_end_position, crate::input::Point::new(0, 1));
9805                assert_eq!(edits[1].1.to_string(), "X bbb Y");
9806            });
9807        });
9808    }
9809
9810    /// Edits are recorded even when no highlighter can be installed.
9811    #[gpui::test]
9812    fn test_last_input_edits_without_a_highlighter(cx: &mut TestAppContext) {
9813        let input_view = InputView::new(cx);
9814        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9815        let input = input_view.input;
9816
9817        cx.update(|window, cx| {
9818            input.update(cx, |state, cx| {
9819                state.set_value("fn main() {}", window, cx);
9820                let no_highlighter: InputHighlighterFactory = Rc::new(|_: &str| None);
9821                state.set_highlighter_factory(no_highlighter, cx);
9822                assert!(state.last_input_edits.as_slice().is_empty());
9823
9824                state.replace_text_in_ranges(&[(12..12, "\n".to_string())], window, cx);
9825                assert_eq!(state.value(), "fn main() {}\n");
9826
9827                let edits = state.last_input_edits.as_slice();
9828                assert_eq!(edits.len(), 1);
9829                let (edit, text_after) = &edits[0];
9830                assert_eq!(edit.start_byte, 12);
9831                assert_eq!(edit.old_end_byte, 12);
9832                assert_eq!(edit.new_end_byte, 13);
9833                assert_eq!(edit.start_position, crate::input::Point::new(0, 12));
9834                assert_eq!(edit.old_end_position, crate::input::Point::new(0, 12));
9835                assert_eq!(edit.new_end_position, crate::input::Point::new(1, 0));
9836                assert_eq!(text_after.to_string(), "fn main() {}\n");
9837            });
9838        });
9839    }
9840
9841    /// `set_value` is silent and leaves no edits behind for the next change.
9842    #[gpui::test]
9843    fn test_last_input_edits_cleared_by_set_value(cx: &mut TestAppContext) {
9844        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9845        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9846        let input = input_view.input;
9847
9848        cx.update(|window, cx| {
9849            input.update(cx, |state, cx| {
9850                state.replace_text_in_ranges(&[(5..5, "!".to_string())], window, cx);
9851                assert_eq!(state.last_input_edits.as_slice().len(), 1);
9852
9853                state.set_value("replaced", window, cx);
9854                assert!(state.last_input_edits.as_slice().is_empty());
9855
9856                state.replace_text_in_ranges(&[(8..8, "?".to_string())], window, cx);
9857                let edits = state.last_input_edits.as_slice();
9858                assert_eq!(edits.len(), 1);
9859                assert_eq!(edits[0].1.to_string(), "replaced?");
9860            });
9861        });
9862    }
9863
9864    /// Apply an emitted batch as an incremental consumer would and verify every snapshot.
9865    fn replay_input_edits(text: &mut String, event: &InputEditsEvent) {
9866        for (edit, after) in event.edits() {
9867            let replacement = after.slice(edit.start_byte..edit.new_end_byte).to_string();
9868            text.replace_range(edit.start_byte..edit.old_end_byte, &replacement);
9869            assert_eq!(*text, after.to_string());
9870        }
9871    }
9872
9873    #[gpui::test]
9874    fn input_edits_events_preserve_queued_changes_and_undo(cx: &mut TestAppContext) {
9875        let view = InputView::build_textarea(cx, |state| state.default_value("hello"));
9876        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9877        let input = view.input;
9878        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9879        let seen = observed.clone();
9880        let _subscription = cx.update(|_, cx| {
9881            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9882                seen.borrow_mut().push(event.clone());
9883            })
9884        });
9885        cx.update(|window, cx| {
9886            input.update(cx, |state, cx| {
9887                state.replace_text_in_ranges(&[(5..5, "!".into())], window, cx);
9888                state.replace_text_in_ranges(&[(6..6, "?".into())], window, cx);
9889                state.undo(&Undo, window, cx);
9890            });
9891        });
9892        let events = observed.borrow();
9893        assert!(events.len() >= 3);
9894        let mut text = "hello".to_string();
9895        for event in events.iter() {
9896            replay_input_edits(&mut text, event);
9897        }
9898        assert_eq!(
9899            text,
9900            input.read_with(&cx, |state, _| state.value().to_string())
9901        );
9902        assert_eq!(events[0].edits()[0].1.to_string(), "hello!");
9903        assert_eq!(events[1].edits()[0].1.to_string(), "hello!?");
9904    }
9905
9906    #[gpui::test]
9907    fn input_edits_event_replays_ime_commit(cx: &mut TestAppContext) {
9908        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9909        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9910        let input = view.input;
9911        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9912        let seen = observed.clone();
9913        let _subscription = cx.update(|_, cx| {
9914            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9915                seen.borrow_mut().push(event.clone());
9916            })
9917        });
9918        cx.update(|window, cx| {
9919            input.update(cx, |state, cx| {
9920                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9921                state.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
9922                state.replace_text_in_range(None, "你", window, cx);
9923            });
9924        });
9925        let events = observed.borrow();
9926        assert_eq!(events.len(), 1);
9927        let mut text = String::new();
9928        replay_input_edits(&mut text, &events[0]);
9929        assert_eq!(text, "你");
9930    }
9931
9932    #[gpui::test]
9933    fn input_edits_event_replays_after_cancelled_composition(cx: &mut TestAppContext) {
9934        let view = InputView::build_textarea(cx, |state| state.default_value(""));
9935        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9936        let input = view.input;
9937        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9938        let seen = observed.clone();
9939        let _subscription = cx.update(|_, cx| {
9940            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9941                seen.borrow_mut().push(event.clone());
9942            })
9943        });
9944        cx.update(|window, cx| {
9945            input.update(cx, |state, cx| {
9946                state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
9947                state.replace_and_mark_text_in_range(None, "", None, window, cx);
9948                state.replace_text_in_range(None, "x", window, cx);
9949            });
9950        });
9951        let events = observed.borrow();
9952        assert_eq!(events.len(), 1);
9953        let mut text = String::new();
9954        replay_input_edits(&mut text, &events[0]);
9955        assert_eq!(text, "x");
9956    }
9957
9958    #[gpui::test]
9959    fn input_edits_event_replays_mask_rewrite(cx: &mut TestAppContext) {
9960        let view = InputView::build(cx, |state| {
9961            state
9962                .mask_pattern(MaskPattern::Number {
9963                    separator: Some(','),
9964                    fraction: None,
9965                })
9966                .default_value("999")
9967        });
9968        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9969        let input = view.input;
9970        let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
9971        let seen = observed.clone();
9972        let _subscription = cx.update(|_, cx| {
9973            cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
9974                seen.borrow_mut().push(event.clone());
9975            })
9976        });
9977        cx.update(|window, cx| {
9978            input.update(cx, |state, cx| {
9979                state.set_cursor_to(3);
9980                state.replace_text_in_range(None, "9", window, cx)
9981            });
9982        });
9983        let events = observed.borrow();
9984        assert_eq!(events.len(), 1);
9985        let mut text = "999".to_string();
9986        replay_input_edits(&mut text, &events[0]);
9987        assert_eq!(text, "9,999");
9988    }
9989
9990    /// An IME composition (marking then commit) undoes as a single unit.
9991    #[gpui::test]
9992    fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
9993        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
9994        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9995        let input = input_view.input;
9996
9997        cx.update(|window, cx| {
9998            input.update(cx, |s, cx| {
9999                // Simulate an IME composition: mark, refine, then commit.
10000                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10001                s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
10002                s.replace_text_in_range(None, "你", window, cx);
10003                assert_eq!(s.value(), "你");
10004
10005                // The entire composition is one undo transaction.
10006                assert_eq!(s.undo_manager.undo_count(), 1);
10007
10008                s.undo(&Undo, window, cx);
10009                assert_eq!(s.value(), "");
10010
10011                s.redo(&Redo, window, cx);
10012                assert_eq!(s.value(), "你");
10013            });
10014        });
10015    }
10016
10017    /// A keystroke right after a committed composition must be its own undo
10018    /// entry, not merged into the (finalized) composition transaction.
10019    #[gpui::test]
10020    fn test_edit_after_composition_is_separate_undo(cx: &mut TestAppContext) {
10021        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
10022        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10023        let input = input_view.input;
10024
10025        cx.update(|window, cx| {
10026            input.update(cx, |s, cx| {
10027                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10028                s.replace_text_in_range(None, "你", window, cx);
10029                assert_eq!(s.value(), "你");
10030                assert_eq!(s.undo_manager.undo_count(), 1);
10031
10032                // Typing after the commit is a distinct transaction.
10033                s.replace_text_in_range(None, "x", window, cx);
10034                assert_eq!(s.value(), "你x");
10035                assert_eq!(s.undo_manager.undo_count(), 2);
10036
10037                s.undo(&Undo, window, cx);
10038                assert_eq!(s.value(), "你");
10039                s.undo(&Undo, window, cx);
10040                assert_eq!(s.value(), "");
10041            });
10042        });
10043    }
10044
10045    /// Canceling a composition via `unmark_text` closes its transaction so it
10046    /// does not leak and swallow a later edit.
10047    #[gpui::test]
10048    fn test_composition_cancel_via_unmark_does_not_leak(cx: &mut TestAppContext) {
10049        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
10050        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10051        let input = input_view.input;
10052
10053        cx.update(|window, cx| {
10054            input.update(cx, |s, cx| {
10055                // Start a composition, then cancel it via unmark.
10056                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10057                s.unmark_text(window, cx);
10058                let after_cancel = s.undo_manager.undo_count();
10059
10060                // A later edit is recorded independently.
10061                s.replace_text_in_range(None, "x", window, cx);
10062                assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
10063            });
10064        });
10065    }
10066
10067    #[gpui::test]
10068    fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
10069        let input_view = InputView::build(cx, |state| state.default_value("éx"));
10070        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10071        let input = input_view.input;
10072
10073        cx.update(|window, cx| {
10074            input.update(cx, |state, cx| {
10075                state.set_selected_range(0..1, cx);
10076                assert_eq!(state.selected_range(), 0..2);
10077                state.copy(&Copy, window, cx);
10078
10079                state.set_selected_range(1..1, cx);
10080                assert_eq!(state.selected_range(), 0..0);
10081            });
10082        });
10083    }
10084
10085    #[gpui::test]
10086    fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
10087        let input_view = InputView::build(cx, |state| state.default_value("你好 "));
10088        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10089        let input = input_view.input;
10090
10091        cx.update(|window, cx| {
10092            input.update(cx, |state, cx| {
10093                state.set_selected_range(7..7, cx);
10094                state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
10095                state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
10096
10097                assert_eq!(state.value(), "你好 sh");
10098                assert_eq!(state.selected_range(), 9..9);
10099                assert_eq!(state.ime_marked_range, Some((7..9).into()));
10100            });
10101        });
10102    }
10103
10104    #[gpui::test]
10105    fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
10106        let input_view = InputView::build(cx, |state| state);
10107        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10108        let input = input_view.input;
10109
10110        cx.update(|window, cx| {
10111            input.update(cx, |state, cx| {
10112                state.set_value("a", window, cx);
10113                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
10114                state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
10115                state.replace_text_in_range(None, "是", window, cx);
10116                assert_eq!(state.value(), "a是");
10117
10118                state.undo(&Undo, window, cx);
10119                assert_eq!(state.value(), "a");
10120                state.redo(&Redo, window, cx);
10121                assert_eq!(state.value(), "a是");
10122            });
10123        });
10124    }
10125
10126    #[gpui::test]
10127    fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
10128        let input_view = InputView::build(cx, |state| state);
10129        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10130        let input = input_view.input;
10131
10132        cx.update(|window, cx| {
10133            input.update(cx, |state, cx| {
10134                // First composition: "jin" -> "今天"
10135                state.replace_and_mark_text_in_range(None, "j", None, window, cx);
10136                state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
10137                state.replace_text_in_range(None, "今天", window, cx);
10138                // Second composition: "wo" -> "我们"
10139                state.replace_and_mark_text_in_range(None, "w", None, window, cx);
10140                state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
10141                state.replace_text_in_range(None, "我们", window, cx);
10142                assert_eq!(state.value(), "今天我们");
10143                assert_eq!(state.selected_range(), 12..12);
10144
10145                state.undo(&Undo, window, cx);
10146                assert_eq!(state.value(), "今天");
10147                assert_eq!(state.selected_range(), 6..6);
10148
10149                state.undo(&Undo, window, cx);
10150                assert_eq!(state.value(), "");
10151                assert_eq!(state.selected_range(), 0..0);
10152
10153                state.redo(&Redo, window, cx);
10154                assert_eq!(state.value(), "今天");
10155                assert_eq!(state.selected_range(), 6..6);
10156
10157                state.redo(&Redo, window, cx);
10158                assert_eq!(state.value(), "今天我们");
10159                assert_eq!(state.selected_range(), 12..12);
10160            });
10161        });
10162    }
10163
10164    #[gpui::test]
10165    fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
10166        let input_view = InputView::build(cx, |state| state);
10167        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10168        let input = input_view.input;
10169
10170        cx.update(|window, cx| {
10171            input.update(cx, |state, cx| {
10172                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
10173                state.replace_text_in_range(None, "你", window, cx);
10174                state.undo_manager.set_pending_intent(EditIntent::Typing);
10175                state.replace_text_in_range(None, "a", window, cx);
10176                state.undo_manager.set_pending_intent(EditIntent::Typing);
10177                state.replace_text_in_range(None, "b", window, cx);
10178                assert_eq!(state.value(), "你ab");
10179
10180                state.undo(&Undo, window, cx);
10181                assert_eq!(state.value(), "你");
10182
10183                state.undo(&Undo, window, cx);
10184                assert_eq!(state.value(), "");
10185            });
10186        });
10187    }
10188
10189    #[gpui::test]
10190    fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
10191        let input_view = InputView::build(cx, |state| state);
10192        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10193        let input = input_view.input;
10194
10195        cx.update(|window, cx| {
10196            input.update(cx, |state, cx| {
10197                state.set_value("a", window, cx);
10198                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
10199                state.replace_and_mark_text_in_range(None, "", None, window, cx);
10200
10201                assert_eq!(state.value(), "a");
10202                assert!(!state.undo_manager.has_undos());
10203            });
10204        });
10205    }
10206
10207    /// The macOS Korean IME rewrites the character it just inserted.
10208    #[gpui::test]
10209    fn test_undo_manager_ime_rewrites_of_typed_char_are_one_group(cx: &mut TestAppContext) {
10210        let input_view = InputView::build(cx, |state| state);
10211        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10212        let input = input_view.input;
10213
10214        cx.update(|window, cx| {
10215            input.update(cx, |state, cx| {
10216                state.set_value("é ", window, cx);
10217                state.set_selected_range(3..3, cx);
10218                // g k s r m f: "ㅎ" -> "하" -> "한", then "ㄱ" -> "그" -> "글"
10219                state.replace_text_in_range(None, "ㅎ", window, cx);
10220                state.replace_text_in_range(Some(2..3), "하", window, cx);
10221                state.replace_text_in_range(Some(2..3), "한", window, cx);
10222                state.replace_text_in_range(None, "ㄱ", window, cx);
10223                state.replace_text_in_range(Some(3..4), "그", window, cx);
10224                state.replace_text_in_range(Some(3..4), "글", window, cx);
10225                assert_eq!(state.value(), "é 한글");
10226                assert_eq!(state.undo_manager.undo_count(), 1);
10227
10228                state.undo(&Undo, window, cx);
10229                assert_eq!(state.value(), "é ");
10230                assert_eq!(state.selected_range(), 3..3);
10231
10232                state.redo(&Redo, window, cx);
10233                assert_eq!(state.value(), "é 한글");
10234                assert_eq!(state.selected_range(), 9..9);
10235            });
10236        });
10237    }
10238
10239    #[gpui::test]
10240    fn test_undo_manager_rewrite_after_cursor_movement_is_separate(cx: &mut TestAppContext) {
10241        let input_view = InputView::build(cx, |state| state);
10242        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10243        let input = input_view.input;
10244
10245        cx.update(|window, cx| {
10246            input.update(cx, |state, cx| {
10247                state.replace_text_in_range(None, "c", window, cx);
10248                state.replace_text_in_range(None, "e", window, cx);
10249                state.left(&MoveLeft, window, cx);
10250                state.right(&MoveRight, window, cx);
10251                state.replace_text_in_range(Some(1..2), "é", window, cx);
10252                assert_eq!(state.value(), "cé");
10253
10254                state.undo(&Undo, window, cx);
10255                assert_eq!(state.value(), "ce");
10256                state.undo(&Undo, window, cx);
10257                assert_eq!(state.value(), "");
10258            });
10259        });
10260    }
10261
10262    #[gpui::test]
10263    fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
10264        let input_view = InputView::build(cx, |state| state);
10265        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10266        let input = input_view.input;
10267
10268        cx.update(|window, cx| {
10269            input.update(cx, |state, cx| {
10270                state.set_value("abc", window, cx);
10271                state.set_selected_range(1..2, cx);
10272                state.replace_text_in_range(None, "X", window, cx);
10273
10274                state.undo(&Undo, window, cx);
10275                assert_eq!(state.value(), "abc");
10276                assert_eq!(state.selected_range(), 1..2);
10277
10278                state.redo(&Redo, window, cx);
10279                assert_eq!(state.value(), "aXc");
10280                assert_eq!(state.selected_range(), 2..2);
10281            });
10282        });
10283    }
10284
10285    #[gpui::test]
10286    fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
10287        let input_view = InputView::build(cx, |state| state);
10288        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10289        let input = input_view.input;
10290
10291        cx.update(|window, cx| {
10292            input.update(cx, |state, cx| {
10293                state.set_value("abc", window, cx);
10294                state.set_selected_range(1..1, cx);
10295                state.delete(&Delete, window, cx);
10296
10297                state.undo(&Undo, window, cx);
10298                assert_eq!(state.value(), "abc");
10299                assert_eq!(state.selected_range(), 1..1);
10300            });
10301        });
10302    }
10303
10304    #[gpui::test]
10305    fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
10306        let input_view = InputView::build(cx, |state| state);
10307        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10308        let input = input_view.input;
10309
10310        cx.update(|window, cx| {
10311            input.update(cx, |state, cx| {
10312                state.replace_text_in_range(None, "ab", window, cx);
10313                state.undo(&Undo, window, cx);
10314                state.set_selected_range(0..0, cx);
10315                state.redo(&Redo, window, cx);
10316                assert_eq!(state.value(), "ab");
10317
10318                state.undo(&Undo, window, cx);
10319                state.replace_text_in_range(None, "x", window, cx);
10320                state.redo(&Redo, window, cx);
10321                assert_eq!(state.value(), "x");
10322            });
10323        });
10324    }
10325
10326    #[gpui::test]
10327    fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
10328        let input_view = InputView::build(cx, |state| state);
10329        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10330        let input = input_view.input;
10331
10332        cx.update(|window, cx| {
10333            input.update(cx, |state, cx| {
10334                state.replace_text_in_range(None, "a", window, cx);
10335                state.move_to(0, None, cx);
10336                state.replace_text_in_range(None, "", window, cx);
10337                state.undo(&Undo, window, cx);
10338                assert_eq!(state.value(), "");
10339                state.redo(&Redo, window, cx);
10340                assert_eq!(state.value(), "a");
10341                assert_eq!(state.cursor(), 1);
10342            });
10343        });
10344    }
10345
10346    #[gpui::test]
10347    fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
10348        let input_view = InputView::build(cx, |state| state);
10349        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10350        let input = input_view.input;
10351
10352        cx.update(|window, cx| {
10353            input.update(cx, |state, cx| {
10354                state.replace_text_in_range(None, "a", window, cx);
10355                state.left(&MoveLeft, window, cx);
10356                state.right(&MoveRight, window, cx);
10357                state.replace_text_in_range(None, "b", window, cx);
10358
10359                state.undo(&Undo, window, cx);
10360                assert_eq!(state.value(), "a");
10361                state.undo(&Undo, window, cx);
10362                assert_eq!(state.value(), "");
10363            });
10364        });
10365    }
10366
10367    #[gpui::test]
10368    fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
10369        cx: &mut TestAppContext,
10370    ) {
10371        let input_view = InputView::build(cx, |state| state);
10372        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10373        let input = input_view.input;
10374
10375        cx.update(|window, cx| {
10376            input.update(cx, |state, cx| {
10377                state.replace_text_in_range(None, "alpha", window, cx);
10378                state.replace_text_in_range(None, "", window, cx);
10379                state.replace_text_in_range(None, "beta", window, cx);
10380                assert_eq!(state.value(), "alphabeta");
10381
10382                state.undo(&Undo, window, cx);
10383                assert_eq!(state.value(), "alpha");
10384                state.undo(&Undo, window, cx);
10385                assert_eq!(state.value(), "");
10386            });
10387        });
10388    }
10389
10390    #[gpui::test]
10391    fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
10392        let input_view = InputView::build(cx, |state| {
10393            state.mask_pattern(MaskPattern::Number {
10394                separator: Some(','),
10395                fraction: None,
10396            })
10397        });
10398        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10399        let input = input_view.input;
10400
10401        cx.update(|window, cx| {
10402            input.update(cx, |state, cx| {
10403                state.set_value("12345", window, cx);
10404                state.set_selected_range(2..2, cx);
10405                state.replace_text_in_range(None, "9", window, cx);
10406                let selection_after_edit = state.selected_range();
10407                assert_ne!(selection_after_edit.end, state.value().len());
10408
10409                state.undo(&Undo, window, cx);
10410                state.redo(&Redo, window, cx);
10411                assert_eq!(state.selected_range(), selection_after_edit);
10412            });
10413        });
10414    }
10415
10416    /// fold_all, fold_at_level and unfold_all change only the folded set; the
10417    /// candidates stay. A level counts the candidates that contain a range.
10418    #[gpui::test]
10419    fn test_fold_all_and_fold_at_level(cx: &mut TestAppContext) {
10420        use crate::input::FoldRange;
10421
10422        let view = InputView::<EditorMode>::new(cx);
10423        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10424        let input = view.input;
10425
10426        // Level 1: 0..=9; level 2: 1..=4 and 5..=8; level 3: 2..=3.
10427        cx.update(|window, cx| {
10428            input.update(cx, |state, cx| {
10429                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj", window, cx);
10430                state.apply_highlighter_fold_candidates(
10431                    vec![
10432                        FoldRange::new(0, 9),
10433                        FoldRange::new(1, 4),
10434                        FoldRange::new(2, 3),
10435                        FoldRange::new(5, 8),
10436                    ],
10437                    cx,
10438                );
10439            });
10440        });
10441        let folded = |cx: &mut VisualTestContext| {
10442            cx.update(|_, cx| {
10443                input.read_with(cx, |state, _| {
10444                    state
10445                        .display_map
10446                        .folded_ranges()
10447                        .iter()
10448                        .map(|f| f.start_line)
10449                        .collect::<Vec<_>>()
10450                })
10451            })
10452        };
10453
10454        cx.update(|_, cx| input.update(cx, |state, cx| state.fold_all(cx)));
10455        assert_eq!(folded(&mut cx), vec![0, 1, 2, 5]);
10456
10457        cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(2, cx)));
10458        assert_eq!(folded(&mut cx), vec![1, 5]);
10459
10460        cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(1, cx)));
10461        assert_eq!(folded(&mut cx), vec![0]);
10462
10463        cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(3, cx)));
10464        assert_eq!(folded(&mut cx), vec![2]);
10465
10466        cx.update(|_, cx| input.update(cx, |state, cx| state.unfold_all(cx)));
10467        assert!(folded(&mut cx).is_empty());
10468        cx.update(|_, cx| {
10469            input.read_with(cx, |state, _| assert_eq!(state.fold_candidates().len(), 4));
10470        });
10471
10472        cx.update(|_, cx| {
10473            input.update(cx, |state, cx| {
10474                assert!(state.set_folded(5, true, cx));
10475                assert!(!state.set_folded(6, true, cx));
10476            })
10477        });
10478        assert_eq!(folded(&mut cx), vec![5]);
10479    }
10480
10481    /// Unfolding at a position opens exactly the folds hiding it.
10482    ///
10483    /// A fold keeps its own first and last line visible, so a position on
10484    /// either of them opens nothing. Nested folds all open at once, sibling
10485    /// folds stay closed, and the opened ranges stay fold candidates.
10486    #[gpui::test]
10487    fn test_unfold_at(cx: &mut TestAppContext) {
10488        use crate::input::{FoldRange, Position};
10489
10490        let view = InputView::<EditorMode>::new(cx);
10491        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10492        let input = view.input;
10493
10494        // An outer fold over lines 0..=5, a fold nested inside it, and a
10495        // sibling fold that must never be touched.
10496        cx.update(|window, cx| {
10497            input.update(cx, |state, cx| {
10498                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
10499                state.apply_highlighter_fold_candidates(
10500                    vec![
10501                        FoldRange::new(0, 5),
10502                        FoldRange::new(2, 4),
10503                        FoldRange::new(7, 10),
10504                    ],
10505                    cx,
10506                );
10507                state.display_map.set_folded(0, true);
10508                state.display_map.set_folded(2, true);
10509                state.display_map.set_folded(7, true);
10510            });
10511        });
10512
10513        // The outer fold's own first and last line stay visible, so neither
10514        // position opens anything.
10515        for line in [0, 5] {
10516            cx.update(|_, cx| {
10517                input.update(cx, |state, cx| {
10518                    assert!(!state.display_map.is_buffer_line_hidden(line));
10519                    assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
10520                });
10521                input.read_with(cx, |state, _| {
10522                    assert!(state.display_map.is_folded_at(0));
10523                    assert!(state.display_map.is_folded_at(2));
10524                    assert!(state.display_map.is_folded_at(7));
10525                });
10526            });
10527        }
10528
10529        // Line 3 is hidden by both the outer and the nested fold, so both
10530        // open; the sibling fold does not.
10531        cx.update(|_, cx| {
10532            input.update(cx, |state, cx| {
10533                assert!(state.unfold_at(Position::new(3, 0), cx));
10534            });
10535            input.read_with(cx, |state, _| {
10536                assert!(!state.display_map.is_buffer_line_hidden(3));
10537                assert!(!state.display_map.is_folded_at(0));
10538                assert!(!state.display_map.is_folded_at(2));
10539                assert!(state.display_map.is_folded_at(7));
10540                // The opened ranges are still candidates for refolding.
10541                assert!(state.display_map.is_fold_candidate(0));
10542                assert!(state.display_map.is_fold_candidate(2));
10543            });
10544        });
10545
10546        // Nothing is hidden there any more, so a second call is a no-op.
10547        cx.update(|_, cx| {
10548            input.update(cx, |state, cx| {
10549                assert!(!state.unfold_at(Position::new(3, 0), cx));
10550            });
10551        });
10552    }
10553
10554    /// Losing focus hides the hover popover but keeps the decorations.
10555    ///
10556    /// Both used to be dropped by one call, so clicking away threw away
10557    /// decorations the application had installed and never asked to remove.
10558    #[gpui::test]
10559    fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
10560        let view = InputView::<EditorMode>::new(cx);
10561        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10562        let input = view.input;
10563
10564        cx.update(|window, cx| {
10565            input.update(cx, |state, cx| {
10566                state.set_value("select 1", window, cx);
10567                let _collection = state.create_decorations_collection(
10568                    vec![crate::input::TextDecoration::new(
10569                        0..6,
10570                        gpui::HighlightStyle {
10571                            font_weight: Some(gpui::FontWeight::BOLD),
10572                            ..Default::default()
10573                        },
10574                    )],
10575                    cx,
10576                );
10577                state.present_hover(
10578                    0..6,
10579                    lsp_types::Hover {
10580                        contents: lsp_types::HoverContents::Scalar(
10581                            lsp_types::MarkedString::String("docs".into()),
10582                        ),
10583                        range: None,
10584                    },
10585                    cx,
10586                );
10587                assert!(state.hover_popover().is_some());
10588
10589                state.on_blur(window, cx);
10590
10591                assert!(
10592                    state.hover_popover().is_none(),
10593                    "blur should hide the hover popover"
10594                );
10595                let decorations = state.extras.decoration_layers();
10596                assert!(
10597                    decorations.iter().any(|layer| !layer.is_empty()),
10598                    "blur must not discard decorations"
10599                );
10600            });
10601        });
10602    }
10603
10604    /// The mode marker is the only source of truth for the kind of input.
10605    ///
10606    /// An auto-growing textarea capped at one row used to report itself as
10607    /// single-line, because the answer was derived from the row counts.
10608    #[gpui::test]
10609    fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
10610        let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
10611        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10612        view.input.read_with(&mut cx, |state, _| {
10613            assert!(state.is_multi_line());
10614            assert!(!state.is_single_line());
10615            assert!(!state.is_code_editor());
10616        });
10617    }
10618
10619    #[gpui::test]
10620    fn test_textarea_prewrap_prepares_content_rows_before_layout(cx: &mut TestAppContext) {
10621        cx.update(crate::init);
10622        for (value, expected_rows) in [("", 1), ("one\ntwo", 2)] {
10623            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10624                let font = window.text_style().font();
10625                cx.new(|cx| {
10626                    let mut state = crate::input::TextareaState::new(window, cx)
10627                        .rows(12)
10628                        .default_value(value);
10629                    assert_eq!(state.display_map().wrap_row_count(), 0);
10630                    state.prewrap(font, px(14.), px(120.), cx);
10631                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10632                    assert_eq!(state.value(), value);
10633                    state
10634                });
10635                gpui::EmptyView
10636            });
10637        }
10638    }
10639
10640    #[gpui::test]
10641    fn test_textarea_prewrap_respects_soft_wrap_before_layout(cx: &mut TestAppContext) {
10642        cx.update(crate::init);
10643        let value = "select id, name, email, phone from users where active\nlimit 10";
10644        for soft_wrap in [true, false] {
10645            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10646                let font = window.text_style().font();
10647                cx.new(|cx| {
10648                    let mut state = crate::input::TextareaState::new(window, cx)
10649                        .rows(1)
10650                        .soft_wrap(soft_wrap)
10651                        .default_value(value);
10652                    state.prewrap(font, px(14.), px(120.), cx);
10653                    let rows = state.display_map().wrap_row_count();
10654                    if soft_wrap {
10655                        assert!(rows > 2, "the first logical line must wrap");
10656                    } else {
10657                        assert_eq!(rows, 2);
10658                    }
10659                    assert_eq!(state.value(), value);
10660                    state
10661                });
10662                gpui::EmptyView
10663            });
10664        }
10665    }
10666
10667    #[gpui::test]
10668    fn test_prewrap_counts_wrapped_rows_before_the_first_paint(cx: &mut TestAppContext) {
10669        cx.update(crate::init);
10670        let text = "select id, name, email, phone from users where active\nlimit 10";
10671        for (soft_wrap, wraps) in [(true, true), (false, false)] {
10672            let mut input = None;
10673            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10674                let font = window.text_style().font();
10675                let editor = cx.new(|cx| {
10676                    let mut state = crate::input::EditorState::new(window, cx)
10677                        .soft_wrap(soft_wrap)
10678                        .default_value(text);
10679                    state.prewrap(font, px(14.), px(120.), cx);
10680                    state
10681                });
10682                input = Some(editor);
10683                gpui::EmptyView
10684            });
10685            let rows = input
10686                .unwrap()
10687                .read_with(cx, |state, _| state.display_map().wrap_row_count());
10688            // Two lines; at 120px the first wraps unless soft wrap is off.
10689            assert_eq!(rows > 2, wraps, "soft_wrap({soft_wrap}): {rows} rows");
10690            if !wraps {
10691                assert_eq!(rows, 2);
10692            }
10693        }
10694    }
10695
10696    #[gpui::test]
10697    fn test_prewrap_uses_the_configured_tab_stops(cx: &mut TestAppContext) {
10698        cx.update(crate::init);
10699        cx.open_window(size(px(400.), px(100.)), |window, cx| {
10700            let font = window.text_style().font();
10701            let font_size = px(14.);
10702            let font_id = window.text_system().resolve_font(&font);
10703            let space_width = window.text_system().layout_width(font_id, font_size, ' ');
10704            cx.new(|cx| {
10705                let mut state = crate::input::EditorState::new(window, cx)
10706                    .tab_size(TabSize {
10707                        tab_size: 4,
10708                        hard_tabs: true,
10709                    })
10710                    .default_value("\t\t");
10711                for (tab_size, expected_rows) in [(4, 2), (2, 1), (8, 2)] {
10712                    state.set_tab_size(
10713                        TabSize {
10714                            tab_size,
10715                            hard_tabs: true,
10716                        },
10717                        cx,
10718                    );
10719                    state.prewrap(font.clone(), font_size, space_width * 5. + RIGHT_MARGIN, cx);
10720                    assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10721                }
10722                state
10723            });
10724            gpui::EmptyView
10725        });
10726    }
10727
10728    /// Prewrap counts with the state's wrapping indent, as the first layout
10729    /// does: continuation rows indented as deep as their line take more rows.
10730    #[gpui::test]
10731    fn test_prewrap_wraps_with_the_wrapping_indent(cx: &mut TestAppContext) {
10732        cx.update(crate::init);
10733        let text = "            select id, name, email, phone from users where active";
10734        let mut rows = Vec::new();
10735        for indent in [WrappingIndent::Same, WrappingIndent::None] {
10736            let mut input = None;
10737            cx.open_window(size(px(400.), px(100.)), |window, cx| {
10738                let font = window.text_style().font();
10739                input = Some(cx.new(|cx| {
10740                    let mut state = crate::input::EditorState::new(window, cx)
10741                        .wrapping_indent(indent)
10742                        .default_value(text);
10743                    state.prewrap(font, px(14.), px(200.), cx);
10744                    state
10745                }));
10746                gpui::EmptyView
10747            });
10748            rows.push(
10749                input
10750                    .unwrap()
10751                    .read_with(cx, |state, _| state.display_map().wrap_row_count()),
10752            );
10753        }
10754        assert!(rows[0] > rows[1], "rows with Same, None: {rows:?}");
10755    }
10756
10757    /// Once the editor is laid out, layout owns the wrap and prewrap leaves it.
10758    #[gpui::test]
10759    fn test_prewrap_does_nothing_once_laid_out(cx: &mut TestAppContext) {
10760        struct Frame(Entity<crate::input::EditorState>);
10761        impl Render for Frame {
10762            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10763                crate::input::InputBase::new("frame")
10764                    .h(px(100.))
10765                    .child(crate::input::Editor::new(&self.0))
10766            }
10767        }
10768
10769        cx.update(crate::init);
10770        let text = "select id, name, email, phone from users where active\nlimit 10";
10771        let mut input = None;
10772        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
10773            let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
10774            input = Some(state.clone());
10775            Frame(state)
10776        });
10777        let input = input.unwrap();
10778        let mut cx = VisualTestContext::from_window(window.into(), cx);
10779        cx.update(|window, cx| window.draw(cx).clear(cx));
10780
10781        let laid_out = input.read_with(&cx, |state, _| state.display_map().wrap_row_count());
10782        assert!(laid_out >= 2, "laid out to {laid_out} rows");
10783        let font = cx.update(|window, _| window.text_style().font());
10784        input.update(&mut cx, |state, cx| {
10785            state.prewrap(font, px(14.), px(60.), cx)
10786        });
10787        assert_eq!(
10788            input.read_with(&cx, |state, _| state.display_map().wrap_row_count()),
10789            laid_out
10790        );
10791    }
10792
10793    /// Soft wrap is on by default, for every mode that can wrap.
10794    ///
10795    /// The default lives in the shared constructor, where a mode-specific
10796    /// `new` can silently fail to restore it; this pins it down.
10797    #[gpui::test]
10798    fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
10799        let textarea = InputView::build_textarea(cx, |state| state);
10800        let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
10801        textarea
10802            .input
10803            .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
10804
10805        let editor = InputView::<EditorMode>::new(cx);
10806        let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
10807        editor
10808            .input
10809            .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
10810    }
10811
10812    /// Parse a cursor spec into `(text, cursor_offsets)`. Non-empty lines are
10813    /// joined with `\n` plus a trailing `\n`. `|` marks a cursor. Leading
10814    /// whitespace is kept, so a spec can express indentation.
10815    fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
10816        let mut full_text = String::new();
10817        let mut cursor_offsets = Vec::new();
10818        let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
10819
10820        for (line_idx, line) in non_empty_lines.iter().enumerate() {
10821            let mut positions = Vec::new();
10822            let mut text = String::new();
10823            for ch in line.chars() {
10824                if ch == '|' {
10825                    positions.push(text.len());
10826                } else {
10827                    text.push(ch);
10828                }
10829            }
10830
10831            if line_idx > 0 {
10832                full_text.push('\n');
10833            }
10834            let line_start = full_text.len();
10835            for pos in positions {
10836                cursor_offsets.push(line_start + pos);
10837            }
10838            full_text.push_str(&text);
10839        }
10840        full_text.push('\n');
10841
10842        (full_text, cursor_offsets)
10843    }
10844
10845    /// Build a multi-line input for multi-cursor tests.
10846    fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
10847        InputView::build_textarea(cx, |state| state)
10848    }
10849
10850    /// Set the text and cursor positions from a spec (see [`parse_cursor_spec`]).
10851    fn setup_cursors<M: InputModeKind>(
10852        cx: &mut VisualTestContext,
10853        input: &Entity<InputBaseState<M>>,
10854        spec: &str,
10855    ) {
10856        let (full_text, offsets) = parse_cursor_spec(spec);
10857        cx.update(|window, cx| {
10858            input.update(cx, |state, cx| {
10859                state.set_value(&full_text, window, cx);
10860                let selections = offsets
10861                    .into_iter()
10862                    .map(|offset| {
10863                        CursorSelection::new(state.selections.generate_id(), offset, offset)
10864                    })
10865                    .collect();
10866                state.selections.replace_all(selections);
10867                cx.notify();
10868            });
10869        });
10870    }
10871
10872    /// Assert the text and cursor positions match a spec.
10873    #[track_caller]
10874    fn assert_cursors<M: InputModeKind>(
10875        cx: &mut VisualTestContext,
10876        input: &Entity<InputBaseState<M>>,
10877        spec: &str,
10878    ) {
10879        let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
10880        expected_cursors.sort();
10881
10882        let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
10883            (
10884                state.text.to_string(),
10885                state
10886                    .selections
10887                    .iter()
10888                    .map(|s| s.cursor_offset())
10889                    .collect::<Vec<_>>(),
10890            )
10891        });
10892        actual_cursors.sort();
10893
10894        assert_eq!(
10895            actual_text, expected_text,
10896            "Text mismatch:\nExpected: {expected_text:?}\nActual:   {actual_text:?}"
10897        );
10898        assert_eq!(
10899            actual_cursors, expected_cursors,
10900            "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual:   {actual_cursors:?}"
10901        );
10902    }
10903
10904    #[gpui::test]
10905    fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
10906        cx.update(crate::init);
10907        let view = InputView::<EditorMode>::new(cx);
10908        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10909        for modifiers in [
10910            gpui::Modifiers {
10911                alt: true,
10912                ..Default::default()
10913            },
10914            gpui::Modifiers {
10915                alt: true,
10916                shift: true,
10917                ..Default::default()
10918            },
10919            #[cfg(target_os = "linux")]
10920            gpui::Modifiers {
10921                alt: true,
10922                control: true,
10923                ..Default::default()
10924            },
10925        ] {
10926            setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
10927            cx.update(|window, cx| {
10928                view.input.update(cx, |state, cx| state.focus(window, cx));
10929            });
10930            let (start, end) = view.input.read_with(&cx, |state, _| {
10931                let layout = state.last_layout.as_ref().unwrap();
10932                let origin = state.last_bounds.unwrap().origin;
10933                let position = |row: usize, col| {
10934                    let local = layout.lines[row]
10935                        .position_for_index(col, layout, false)
10936                        .unwrap();
10937                    origin
10938                        + point(
10939                            layout.line_number_width + local.x,
10940                            layout.line_height * (row as f32 + 0.5),
10941                        )
10942                };
10943                (position(0, 1), position(2, 3))
10944            });
10945            // Land inside the third column instead of exactly on its trailing
10946            // glyph boundary, where pixel rounding can select the next column.
10947            let end = point(end.x - px(0.5), end.y);
10948            // A cached Ctrl-hover definition must not steal a column gesture.
10949            cx.update(|_, cx| {
10950                view.input.update(cx, |state, _| {
10951                    state.extras.hover_definition.update(
10952                        0..4,
10953                        vec![lsp_types::LocationLink {
10954                            origin_selection_range: None,
10955                            target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
10956                            target_range: Default::default(),
10957                            target_selection_range: Default::default(),
10958                        }],
10959                    );
10960                });
10961            });
10962            cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
10963            cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
10964            cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
10965            view.input.read_with(&cx, |state, _| {
10966                let ranges: Vec<_> = state
10967                    .selections
10968                    .iter()
10969                    .map(|sel| sel.start..sel.end)
10970                    .collect();
10971                assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
10972            });
10973            // Moving after release must leave the block intact.
10974            cx.simulate_mouse_move(start, None, modifiers);
10975            cx.simulate_keystrokes("x");
10976            assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
10977        }
10978    }
10979
10980    #[gpui::test]
10981    fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
10982        cx.update(crate::init);
10983        let view = InputView::<EditorMode>::new(cx);
10984        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10985        setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
10986        cx.update(|window, cx| {
10987            view.input.update(cx, |state, cx| state.focus(window, cx));
10988        });
10989        let (start, end) = view.input.read_with(&cx, |state, _| {
10990            let layout = state.last_layout.as_ref().unwrap();
10991            let origin = state.last_bounds.unwrap().origin;
10992            let local = layout.lines[0]
10993                .position_for_index(1, layout, false)
10994                .unwrap();
10995            let x = layout.line_number_width + local.x;
10996            (
10997                origin + point(x, layout.line_height * 2.5),
10998                origin + point(x, layout.line_height * 0.5),
10999            )
11000        });
11001        let modifiers = gpui::Modifiers {
11002            alt: true,
11003            ..Default::default()
11004        };
11005        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
11006        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
11007        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
11008        assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
11009    }
11010
11011    #[gpui::test]
11012    fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
11013        cx.update(crate::init);
11014        let view = InputView::<EditorMode>::new(cx);
11015        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11016        setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
11017        cx.update(|window, cx| {
11018            view.input.update(cx, |state, cx| state.focus(window, cx));
11019        });
11020        // Drag from row 0 column 1 down to row 1, at the x of row 0's column 5. Row 1
11021        // only has two characters, so the pointer ends past its end.
11022        let (start, end) = view.input.read_with(&cx, |state, _| {
11023            let layout = state.last_layout.as_ref().unwrap();
11024            let origin = state.last_bounds.unwrap().origin;
11025            let x_of = |index| {
11026                layout.line_number_width
11027                    + layout.lines[0]
11028                        .position_for_index(index, layout, false)
11029                        .unwrap()
11030                        .x
11031            };
11032            (
11033                origin + point(x_of(1), layout.line_height * 0.5),
11034                origin + point(x_of(5), layout.line_height * 1.5),
11035            )
11036        });
11037        let modifiers = gpui::Modifiers {
11038            alt: true,
11039            shift: true,
11040            ..Default::default()
11041        };
11042        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
11043        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
11044        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
11045
11046        // The short row is clipped to its own end; the long row keeps the full span.
11047        view.input.read_with(&cx, |state, _| {
11048            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
11049            assert_eq!(ranges, vec![(1, 5), (8, 9)]);
11050        });
11051    }
11052
11053    #[gpui::test]
11054    fn test_lost_mouse_release_ends_selection_on_plain_motion(cx: &mut TestAppContext) {
11055        cx.update(crate::init);
11056        let view = InputView::<EditorMode>::new(cx);
11057        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11058        setup_cursors(&mut cx, &view.input, "|alpha bravo charlie delta");
11059        let (start, end, beyond) = view.input.read_with(&cx, |state, _| {
11060            (
11061                state.range_to_bounds(&(0..1)).unwrap().center(),
11062                state.range_to_bounds(&(6..7)).unwrap().center(),
11063                state.range_to_bounds(&(18..19)).unwrap().center(),
11064            )
11065        });
11066        cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
11067        cx.simulate_mouse_move(end, MouseButton::Left, gpui::Modifiers::default());
11068        let selected = view.input.read_with(&cx, |state, _| {
11069            assert!(state.selecting);
11070            let text = state.selected_value();
11071            assert!(!text.is_empty());
11072            text
11073        });
11074        cx.simulate_mouse_move(beyond, None, gpui::Modifiers::default());
11075        view.input.read_with(&cx, |state, _| {
11076            assert!(!state.selecting);
11077            assert_eq!(state.selected_value(), selected);
11078        });
11079    }
11080
11081    #[gpui::test]
11082    fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
11083        cx.update(crate::init);
11084        let view = InputView::<EditorMode>::new(cx);
11085        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11086        setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
11087        let position = view.input.read_with(&cx, |state, _| {
11088            let layout = state.last_layout.as_ref().unwrap();
11089            state.last_bounds.unwrap().origin
11090                + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
11091        });
11092        let modifiers = gpui::Modifiers {
11093            alt: true,
11094            ..Default::default()
11095        };
11096        cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
11097        cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
11098        view.input.read_with(&cx, |state, _| {
11099            assert!(!state.selecting);
11100            assert!(state.column_select_start.is_none());
11101        });
11102    }
11103
11104    #[gpui::test]
11105    fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
11106        let view = InputView::<EditorMode>::new(cx);
11107        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11108        setup_cursors(&mut cx, &view.input, "a|b");
11109        cx.update(|window, cx| {
11110            view.input.update(cx, |state, cx| {
11111                state.focus(window, cx);
11112                state.pause_blink_cursor(cx);
11113            });
11114        });
11115        cx.run_until_parked();
11116        cx.executor()
11117            .advance_clock(std::time::Duration::from_millis(300));
11118        cx.run_until_parked();
11119        view.input.read_with(&cx, |state, cx| {
11120            assert!(!state.blink_cursor.read(cx).visible());
11121        });
11122        // Copy consumes its shortcut without editing text or moving selections.
11123        for _ in 0..5 {
11124            #[cfg(target_os = "macos")]
11125            cx.simulate_keystrokes("cmd-c");
11126            #[cfg(not(target_os = "macos"))]
11127            cx.simulate_keystrokes("ctrl-c");
11128            cx.run_until_parked();
11129            cx.executor()
11130                .advance_clock(std::time::Duration::from_millis(200));
11131            cx.run_until_parked();
11132            view.input.read_with(&cx, |state, cx| {
11133                assert!(state.blink_cursor.read(cx).visible());
11134            });
11135        }
11136    }
11137
11138    #[gpui::test]
11139    fn test_mouse_down_shows_cursor_like_a_cursor_move(cx: &mut TestAppContext) {
11140        cx.update(crate::init);
11141        let view = InputView::<EditorMode>::new(cx);
11142        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11143        setup_cursors(&mut cx, &view.input, "abcd|efgh");
11144        let position = |offset: Pixels, cx: &mut VisualTestContext| {
11145            view.input.read_with(cx, |state, _| {
11146                let layout = state.last_layout.as_ref().unwrap();
11147                state.last_bounds.unwrap().origin
11148                    + point(layout.line_number_width + offset, layout.line_height * 0.5)
11149            })
11150        };
11151        let visible = |cx: &mut VisualTestContext| {
11152            view.input
11153                .read_with(cx, |state, cx| state.blink_cursor.read(cx).visible())
11154        };
11155
11156        // The press itself shows the caret, without waiting for the focus
11157        // observer, and the idle delay holds it there like a cursor move.
11158        let first = position(px(2.), &mut cx);
11159        cx.simulate_mouse_down(first, MouseButton::Left, Default::default());
11160        assert!(visible(&mut cx));
11161        cx.simulate_mouse_up(first, MouseButton::Left, Default::default());
11162        cx.run_until_parked();
11163
11164        // Pressing elsewhere in the focused input, in the hidden phase of the
11165        // blink, shows the caret again at the press.
11166        cx.executor()
11167            .advance_clock(std::time::Duration::from_millis(400));
11168        cx.run_until_parked();
11169        assert!(!visible(&mut cx));
11170        let second = position(px(30.), &mut cx);
11171        cx.simulate_mouse_down(second, MouseButton::Left, Default::default());
11172        assert!(visible(&mut cx));
11173        cx.executor()
11174            .advance_clock(std::time::Duration::from_millis(250));
11175        cx.run_until_parked();
11176        assert!(visible(&mut cx));
11177        cx.simulate_mouse_up(second, MouseButton::Left, Default::default());
11178    }
11179
11180    #[gpui::test]
11181    fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
11182        let view = InputView::<EditorMode>::new(cx);
11183        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11184        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
11185        // Start each action in the hidden phase without depending on a
11186        // key-down listener: actions and text input also arrive directly.
11187        for action in 0..6 {
11188            cx.update(|_, cx| {
11189                view.input.update(cx, |state, cx| {
11190                    state.blink_cursor = cx.new(BlinkCursor::new);
11191                    state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
11192                });
11193            });
11194            cx.run_until_parked();
11195            cx.executor()
11196                .advance_clock(std::time::Duration::from_millis(500));
11197            cx.run_until_parked();
11198            view.input.read_with(&cx, |state, cx| {
11199                assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
11200            });
11201
11202            cx.update(|window, cx| {
11203                view.input.update(cx, |state, cx| {
11204                    match action {
11205                        0 => state.add_cursor_above(&AddCursorAbove, window, cx),
11206                        1 => state.add_cursor_below(&AddCursorBelow, window, cx),
11207                        2 => state.select_up(&SelectUp, window, cx),
11208                        3 => state.select_down(&SelectDown, window, cx),
11209                        4 => state.replace_text_in_range(None, "x", window, cx),
11210                        _ => state.backspace(&Backspace, window, cx),
11211                    }
11212                    assert!(state.blink_cursor.read(cx).visible(), "action {action}");
11213                });
11214            });
11215        }
11216    }
11217
11218    #[gpui::test]
11219    fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
11220        let view = InputView::<EditorMode>::new(cx);
11221        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11222        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
11223        cx.update(|window, cx| {
11224            view.input.update(cx, |state, cx| state.focus(window, cx));
11225        });
11226        #[cfg(target_os = "macos")]
11227        cx.simulate_keystrokes("cmd-alt-up");
11228        #[cfg(target_os = "windows")]
11229        cx.simulate_keystrokes("ctrl-alt-up");
11230        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
11231        cx.simulate_keystrokes("alt-shift-up");
11232        view.input
11233            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
11234        #[cfg(target_os = "macos")]
11235        cx.simulate_keystrokes("cmd-alt-down");
11236        #[cfg(target_os = "windows")]
11237        cx.simulate_keystrokes("ctrl-alt-down");
11238        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
11239        cx.simulate_keystrokes("alt-shift-down");
11240        view.input
11241            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
11242        cx.simulate_keystrokes("x");
11243        assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
11244    }
11245
11246    #[gpui::test]
11247    fn test_multi_cursor_platform_word_selection_dispatch(cx: &mut TestAppContext) {
11248        let view = InputView::<EditorMode>::new(cx);
11249        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11250        setup_cursors(&mut cx, &view.input, "one |two\none |two");
11251        cx.update(|window, cx| {
11252            view.input.update(cx, |state, cx| state.focus(window, cx));
11253        });
11254        #[cfg(any(target_os = "macos", target_os = "linux"))]
11255        cx.simulate_keystrokes("alt-shift-right");
11256        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
11257        cx.simulate_keystrokes("ctrl-shift-right");
11258        cx.simulate_keystrokes("x");
11259        assert_cursors(&mut cx, &view.input, "one x|\none x|");
11260        setup_cursors(&mut cx, &view.input, "one two|\none two|");
11261        #[cfg(any(target_os = "macos", target_os = "linux"))]
11262        cx.simulate_keystrokes("alt-shift-left");
11263        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
11264        cx.simulate_keystrokes("ctrl-shift-left");
11265        cx.simulate_keystrokes("x");
11266        assert_cursors(&mut cx, &view.input, "one x|\none x|");
11267    }
11268
11269    #[cfg(not(target_os = "macos"))]
11270    #[gpui::test]
11271    fn test_multi_cursor_horizontal_selection_dispatch(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, "ab\na|b");
11275        cx.update(|window, cx| {
11276            view.input.update(cx, |state, cx| state.focus(window, cx));
11277        });
11278        #[cfg(target_os = "windows")]
11279        cx.simulate_keystrokes("ctrl-alt-up");
11280        #[cfg(not(target_os = "windows"))]
11281        cx.simulate_keystrokes("alt-shift-up");
11282        #[cfg(target_os = "linux")]
11283        cx.simulate_keystrokes("shift-right");
11284        #[cfg(not(target_os = "linux"))]
11285        cx.simulate_keystrokes("alt-shift-right");
11286        view.input.read_with(&cx, |state, _| {
11287            assert_eq!(
11288                state
11289                    .selections
11290                    .iter()
11291                    .map(|s| s.start..s.end)
11292                    .collect::<Vec<_>>(),
11293                vec![4..5, 1..2]
11294            );
11295        });
11296        #[cfg(target_os = "linux")]
11297        cx.simulate_keystrokes("shift-left shift-left");
11298        #[cfg(not(target_os = "linux"))]
11299        cx.simulate_keystrokes("alt-shift-left alt-shift-left");
11300        view.input.read_with(&cx, |state, _| {
11301            assert_eq!(
11302                state
11303                    .selections
11304                    .iter()
11305                    .map(|s| s.start..s.end)
11306                    .collect::<Vec<_>>(),
11307                vec![3..4, 0..1]
11308            );
11309        });
11310        cx.simulate_keystrokes("x");
11311        assert_cursors(&mut cx, &view.input, "x|b\nx|b");
11312    }
11313
11314    #[gpui::test]
11315    fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
11316        cx.update(crate::init);
11317        let view = InputView::<EditorMode>::new(cx);
11318        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11319        setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
11320        cx.update(|window, cx| {
11321            view.input.update(cx, |state, cx| state.focus(window, cx));
11322        });
11323        let position = view.input.read_with(&cx, |state, _| {
11324            let bounds = state.last_bounds.unwrap();
11325            let layout = state.last_layout.as_ref().unwrap();
11326            bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
11327        });
11328        cx.simulate_click(
11329            position,
11330            gpui::Modifiers {
11331                alt: true,
11332                ..Default::default()
11333            },
11334        );
11335        view.input
11336            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
11337    }
11338
11339    #[gpui::test]
11340    fn test_add_selection(cx: &mut TestAppContext) {
11341        let view = InputView::<EditorMode>::new(cx);
11342        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11343        cx.update(|window, cx| {
11344            view.input.update(cx, |state, cx| {
11345                state.focus(window, cx);
11346                state.set_value("foo bar foo", window, cx);
11347                state.set_selected_range(0..3, cx);
11348                // The programmatic second cursor: the next occurrence.
11349                state.add_selection(8..11, cx);
11350                // Adding a range that is already selected changes nothing.
11351                state.add_selection(0..3, cx);
11352            });
11353        });
11354        view.input.read_with(&cx, |state, _| {
11355            let mut ranges: Vec<Range<usize>> =
11356                state.selections.iter().map(|s| s.start..s.end).collect();
11357            ranges.sort_by_key(|r| r.start);
11358            assert_eq!(ranges, vec![0..3, 8..11]);
11359        });
11360        // Typing replaces every selection at once.
11361        cx.simulate_keystrokes("x");
11362        view.input.read_with(&cx, |state, _| {
11363            assert_eq!(state.text.to_string(), "x bar x")
11364        });
11365    }
11366
11367    #[gpui::test]
11368    fn test_add_selection_preserves_crlf_boundaries(cx: &mut TestAppContext) {
11369        let view = InputView::build_textarea(cx, |state| state.default_value("a\r\nb"));
11370        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11371        cx.update(|window, cx| {
11372            view.input.update(cx, |state, cx| {
11373                state.focus(window, cx);
11374                state.set_selected_range(4..4, cx);
11375                state.add_selection(2..2, cx);
11376                let ranges: Vec<_> = state.selections.iter().map(|s| s.start..s.end).collect();
11377                assert_eq!(ranges, vec![4..4, 1..1]);
11378            });
11379        });
11380        cx.simulate_keystrokes("x");
11381        view.input.read_with(&cx, |state, _| {
11382            assert_eq!(state.value(), "ax\r\nbx");
11383        });
11384        cx.update(|window, cx| {
11385            view.input.update(cx, |state, cx| {
11386                state.set_value("a\r\nb", window, cx);
11387                state.set_selected_range(4..4, cx);
11388                state.add_selection(2..3, cx);
11389                state.cut(&Cut, window, cx);
11390                assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "\r\n");
11391                assert_eq!(state.value(), "ab");
11392            });
11393        });
11394    }
11395
11396    #[gpui::test]
11397    fn test_add_selection_merges_overlaps_before_copy_and_cut(cx: &mut TestAppContext) {
11398        let view = InputView::<EditorMode>::new(cx);
11399        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11400        cx.update(|window, cx| {
11401            view.input.update(cx, |state, cx| {
11402                // Cover partial overlaps, a containing range, and a bridge
11403                // between two previously disjoint selections.
11404                for additions in [vec![2..5], vec![0..5], vec![4..5, 2..4]] {
11405                    state.set_value("abcdef", window, cx);
11406                    state.set_selected_range(0..3, cx);
11407                    let active_id = state.active_selection().id;
11408                    for range in additions {
11409                        state.add_selection(range, cx);
11410                    }
11411                    assert_eq!(state.active_selection().id, active_id);
11412                    assert_eq!(state.selected_range(), 0..5);
11413                    assert_eq!(state.selections.len(), 1);
11414                    state.copy(&Copy, window, cx);
11415                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11416                    state.cut(&Cut, window, cx);
11417                    assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11418                    assert_eq!(state.value(), "f");
11419                    state.undo(&Undo, window, cx);
11420                    assert_eq!(state.value(), "abcdef");
11421                    assert_eq!(state.selected_range(), 0..5);
11422                }
11423            });
11424        });
11425    }
11426
11427    #[gpui::test]
11428    fn test_add_selection_clears_inline_completion(cx: &mut TestAppContext) {
11429        use crate::input::CompletionProvider;
11430        use gpui::Task;
11431        use lsp_types::{
11432            CompletionContext, CompletionResponse, InlineCompletionContext, InlineCompletionItem,
11433            InlineCompletionResponse,
11434        };
11435        use std::time::Duration;
11436
11437        struct Provider(Rc<Cell<usize>>);
11438
11439        impl CompletionProvider for Provider {
11440            fn is_completion_trigger(&self, _: usize, _: &str, _: &mut App) -> bool {
11441                false
11442            }
11443
11444            fn completions(
11445                &self,
11446                _: &Rope,
11447                _: usize,
11448                _: CompletionContext,
11449                _: &mut Window,
11450                _: &mut App,
11451            ) -> Task<anyhow::Result<CompletionResponse>> {
11452                Task::ready(Ok(CompletionResponse::Array(vec![])))
11453            }
11454
11455            fn inline_completion(
11456                &self,
11457                _: &Rope,
11458                _: usize,
11459                _: InlineCompletionContext,
11460                _: &mut Window,
11461                _: &mut App,
11462            ) -> Task<anyhow::Result<InlineCompletionResponse>> {
11463                self.0.set(self.0.get() + 1);
11464                Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
11465            }
11466        }
11467
11468        let view = InputView::<EditorMode>::new(cx);
11469        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11470        let calls = Rc::new(Cell::new(0));
11471        cx.update(|window, cx| {
11472            view.input.update(cx, |state, cx| {
11473                state.focus(window, cx);
11474                state.set_value("aa\naa", window, cx);
11475                state.set_selected_range(2..2, cx);
11476                state.extras.inline_completion.item = Some(InlineCompletionItem {
11477                    insert_text: "suggestion".into(),
11478                    filter_text: None,
11479                    range: None,
11480                    command: None,
11481                    insert_text_format: None,
11482                });
11483                state.add_selection(5..5, cx);
11484                assert!(!state.has_inline_completion());
11485                state.indent_inline(&IndentInline, window, cx);
11486                assert_eq!(state.value(), "aa  \naa  ");
11487                assert_eq!(state.selections.len(), 2);
11488
11489                // The active cursor stays put, so only canceling the task
11490                // prevents this pending request from fetching a suggestion.
11491                state.set_value("aa\naa", window, cx);
11492                state.set_selected_range(2..2, cx);
11493                state.extras.lsp.completion_provider = Some(Rc::new(Provider(calls.clone())));
11494                state.schedule_inline_completion(window, cx);
11495            });
11496        });
11497        cx.run_until_parked();
11498        cx.update(|_, cx| {
11499            view.input
11500                .update(cx, |state, cx| state.add_selection(5..5, cx));
11501        });
11502        cx.executor().advance_clock(Duration::from_secs(1));
11503        cx.run_until_parked();
11504        assert_eq!(calls.get(), 0);
11505        view.input.read_with(&cx, |state, _| {
11506            assert!(!state.has_inline_completion());
11507            assert_eq!(state.selections.len(), 2);
11508            assert_eq!(state.value(), "aa\naa");
11509        });
11510    }
11511
11512    #[gpui::test]
11513    fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
11514        let view = multi_line(cx);
11515        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11516        setup_cursors(&mut cx, &view.input, "hello|");
11517        cx.update(|window, cx| {
11518            view.input.update(cx, |state, cx| {
11519                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
11520                state.undo(&Undo, window, cx);
11521                assert_eq!(state.selected_range(), 5..5);
11522            });
11523        });
11524    }
11525
11526    #[gpui::test]
11527    fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
11528        let view = multi_line(cx);
11529        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11530        setup_cursors(&mut cx, &view.input, "a|b|c");
11531        cx.update(|window, cx| {
11532            view.input.update(cx, |state, cx| {
11533                state.backspace(&Backspace, window, cx);
11534                state.undo(&Undo, window, cx);
11535            });
11536        });
11537        assert_cursors(&mut cx, &view.input, "a|b|c");
11538    }
11539
11540    #[gpui::test]
11541    fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
11542        let view = InputView::<EditorMode>::new(cx);
11543        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11544        cx.update(|window, cx| {
11545            view.input.update(cx, |state, cx| {
11546                state.set_value("abcdef ".repeat(30), window, cx);
11547                state.display_map.on_layout_changed(Some(px(60.)), cx);
11548                let line = state.display_map.line(0).unwrap();
11549                assert!(line.wrapped_lines.len() > 1);
11550                let boundary = line.wrapped_lines[0].end;
11551                state.move_to_with_affinity(boundary, None, true, cx);
11552                state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
11553                assert_eq!(state.selected_range(), boundary..state.text.len());
11554            });
11555        });
11556    }
11557
11558    #[gpui::test]
11559    fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
11560        let view = multi_line(cx);
11561        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11562        setup_cursors(&mut cx, &view.input, "|你好\n|世界");
11563        cx.update(|window, cx| {
11564            view.input.update(cx, |state, cx| {
11565                state.outdent(false, window, cx);
11566                state.outdent(true, window, cx);
11567            });
11568        });
11569        assert_cursors(&mut cx, &view.input, "|你好\n|世界");
11570    }
11571
11572    #[gpui::test]
11573    fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
11574        let view = multi_line(cx);
11575        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11576        setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
11577        cx.update(|window, cx| {
11578            view.input.update(cx, |state, cx| {
11579                state.build_columnar_selection(
11580                    ColumnarPoint::new(1, 0),
11581                    ColumnarPoint::new(11, 0),
11582                    cx,
11583                );
11584                let text = state.value();
11585                for sel in state.selections.iter() {
11586                    assert!(text.is_char_boundary(sel.start));
11587                    assert!(text.is_char_boundary(sel.end));
11588                }
11589                state.replace_text_in_range(None, "X", window, cx);
11590            });
11591        });
11592    }
11593
11594    #[gpui::test]
11595    fn test_cursor_moves_and_deletes_whole_graphemes(cx: &mut TestAppContext) {
11596        let input_view = InputView::build(cx, |state| state);
11597        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
11598        let input = input_view.input;
11599
11600        let graphemes = ["a", "\u{267B}\u{FE0F}", "👍🏽", "👨‍👩‍👧", "🇸🇪", "e\u{301}", "b"];
11601        let text = graphemes.concat();
11602        let ends: Vec<usize> = graphemes
11603            .iter()
11604            .scan(0, |end, g| {
11605                *end += g.len();
11606                Some(*end)
11607            })
11608            .collect();
11609
11610        cx.update(|window, cx| {
11611            input.update(cx, |state, cx| {
11612                state.set_value(text.clone(), window, cx);
11613                state.set_selected_range(0..0, cx);
11614                for &end in &ends {
11615                    state.right(&MoveRight, window, cx);
11616                    assert_eq!(state.cursor(), end);
11617                }
11618                for &end in ends.iter().rev().skip(1).chain([&0]) {
11619                    state.left(&MoveLeft, window, cx);
11620                    assert_eq!(state.cursor(), end);
11621                }
11622
11623                state.set_selected_range(ends[3]..ends[3], cx);
11624                state.backspace(&Backspace, window, cx);
11625                assert_eq!(
11626                    state.value(),
11627                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[4..].concat()
11628                );
11629                state.delete(&Delete, window, cx);
11630                assert_eq!(
11631                    state.value(),
11632                    ["a", graphemes[1], graphemes[2]].concat() + &graphemes[5..].concat()
11633                );
11634            });
11635        });
11636    }
11637
11638    #[gpui::test]
11639    fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
11640        let view = InputView::<EditorMode>::new(cx);
11641        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11642        cx.update(|window, cx| {
11643            view.input.update(cx, |state, cx| {
11644                state.set_value("abc def", window, cx);
11645                state.create_decorations_collection(
11646                    vec![crate::input::TextDecoration::new(
11647                        4..7,
11648                        gpui::HighlightStyle::default(),
11649                    )],
11650                    cx,
11651                );
11652                state.set_selected_range(0..0, cx);
11653                state.replace_text_in_range(None, "X", window, cx);
11654                let layers = state.extras.decoration_layers();
11655                assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
11656            });
11657        });
11658    }
11659
11660    #[gpui::test]
11661    fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
11662        let view = InputView::<EditorMode>::new(cx);
11663        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11664        setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
11665        cx.update(|window, cx| {
11666            view.input.update(cx, |state, cx| {
11667                set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
11668                state.backspace(&Backspace, window, cx);
11669            });
11670        });
11671        assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
11672    }
11673
11674    #[gpui::test]
11675    fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
11676        struct UnexpectedQuery;
11677        impl crate::input::SyntaxContextProvider for UnexpectedQuery {
11678            fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
11679                panic!("ordinary typing must not query syntax");
11680            }
11681        }
11682        let view = InputView::<EditorMode>::new(cx);
11683        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11684        setup_cursors(&mut cx, &view.input, "|");
11685        cx.update(|window, cx| {
11686            view.input.update(cx, |state, cx| {
11687                set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
11688                for c in ["a", "b", "c"] {
11689                    state.replace_text_in_range(None, c, window, cx);
11690                }
11691            });
11692        });
11693        assert_cursors(&mut cx, &view.input, "abc|");
11694    }
11695
11696    #[gpui::test]
11697    fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
11698        let view = InputView::<EditorMode>::new(cx);
11699        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11700        setup_cursors(&mut cx, &view.input, "|");
11701        cx.update(|window, cx| {
11702            view.input.update(cx, |state, cx| {
11703                for _ in 0..999 {
11704                    state.replace_text_in_range(None, "a", window, cx);
11705                }
11706                state.replace_text_in_range(None, "(", window, cx);
11707                state.undo(&Undo, window, cx);
11708                assert!(!state.text.to_string().contains('('));
11709                assert!(!state.text.to_string().contains(')'));
11710                state.redo(&Redo, window, cx);
11711            });
11712        });
11713        assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
11714    }
11715
11716    #[gpui::test]
11717    fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
11718        let view = InputView::<EditorMode>::new(cx);
11719        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11720        setup_cursors(&mut cx, &view.input, "// (|)");
11721        cx.update(|window, cx| {
11722            view.input.update(cx, |state, cx| {
11723                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
11724                state.replace_text_in_range(None, ")", window, cx);
11725            });
11726        });
11727        assert_cursors(&mut cx, &view.input, "// ()|)");
11728    }
11729
11730    #[gpui::test]
11731    fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
11732        let view = InputView::<EditorMode>::new(cx);
11733        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11734        setup_cursors(&mut cx, &view.input, "(a|)");
11735        let before = view.input.read_with(&cx, |state, _| state.text.to_string());
11736        cx.update(|window, cx| {
11737            view.input.update(cx, |state, cx| {
11738                state.replace_text_in_range(Some(2..2), ")", window, cx);
11739            });
11740        });
11741        assert_cursors(&mut cx, &view.input, "(a)|");
11742        cx.update(|window, cx| {
11743            view.input
11744                .update(cx, |state, cx| state.undo(&Undo, window, cx));
11745        });
11746        view.input.read_with(&cx, |state, _| {
11747            assert_eq!(
11748                state.text.to_string(),
11749                before,
11750                "skip must not remove an existing closer on undo"
11751            );
11752        });
11753    }
11754
11755    #[gpui::test]
11756    fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11757        let view = InputView::<EditorMode>::new(cx);
11758        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11759        setup_cursors(&mut cx, &view.input, "|");
11760        cx.update(|window, cx| {
11761            view.input.update(cx, |state, cx| {
11762                state.replace_text_in_range(None, "(", window, cx);
11763            });
11764        });
11765        assert_cursors(&mut cx, &view.input, "(|)");
11766        cx.update(|window, cx| {
11767            view.input.update(cx, |state, cx| {
11768                state.undo(&Undo, window, cx);
11769                state.redo(&Redo, window, cx);
11770            });
11771        });
11772        assert_cursors(&mut cx, &view.input, "(|)");
11773    }
11774
11775    #[gpui::test]
11776    fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
11777        let view = InputView::<EditorMode>::new(cx);
11778        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11779        setup_cursors(&mut cx, &view.input, "{|}");
11780        cx.update(|window, cx| {
11781            view.input.update(cx, |state, cx| {
11782                state.enter(
11783                    &Enter {
11784                        secondary: false,
11785                        shift: false,
11786                    },
11787                    window,
11788                    cx,
11789                );
11790            });
11791        });
11792        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11793        cx.update(|window, cx| {
11794            view.input.update(cx, |state, cx| {
11795                state.undo(&Undo, window, cx);
11796            });
11797        });
11798        assert_cursors(&mut cx, &view.input, "{|}");
11799        cx.update(|window, cx| {
11800            view.input
11801                .update(cx, |state, cx| state.redo(&Redo, window, cx));
11802        });
11803        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11804    }
11805
11806    #[gpui::test]
11807    fn test_auto_close_parens(cx: &mut TestAppContext) {
11808        let view = InputView::<EditorMode>::new(cx);
11809        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11810        setup_cursors(&mut cx, &view.input, "|");
11811        cx.update(|window, cx| {
11812            view.input.update(cx, |state, cx| {
11813                state.replace_text_in_range(None, "(", window, cx);
11814            });
11815        });
11816        assert_cursors(&mut cx, &view.input, "(|)");
11817        // Selection must be collapsed: typing next must insert, not replace.
11818        cx.update(|window, cx| {
11819            view.input.update(cx, |state, cx| {
11820                state.replace_text_in_range(None, "x", window, cx);
11821            });
11822        });
11823        assert_cursors(&mut cx, &view.input, "(x|)");
11824    }
11825
11826    #[gpui::test]
11827    fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
11828        let view = InputView::<EditorMode>::new(cx);
11829        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11830        setup_cursors(&mut cx, &view.input, "(|)");
11831        cx.update(|window, cx| {
11832            view.input.update(cx, |state, cx| {
11833                state.replace_text_in_range(None, ")", window, cx);
11834            });
11835        });
11836        // No duplicate closer, cursor moves past the existing one.
11837        assert_cursors(&mut cx, &view.input, "()|");
11838        // Selection must be collapsed, not covering blank space.
11839        view.input.read_with(&cx, |state, _| {
11840            assert!(state.active_selection().is_empty());
11841        });
11842    }
11843
11844    #[gpui::test]
11845    fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
11846        let view = InputView::<EditorMode>::new(cx);
11847        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11848        setup_cursors(&mut cx, &view.input, "don|");
11849        cx.update(|window, cx| {
11850            view.input.update(cx, |state, cx| {
11851                state.replace_text_in_range(None, "'", window, cx);
11852            });
11853        });
11854        // Contraction: no auto-close.
11855        assert_cursors(&mut cx, &view.input, "don'|");
11856    }
11857
11858    #[gpui::test]
11859    fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
11860        let view = InputView::<EditorMode>::new(cx);
11861        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11862        // Unicode-safe previous-char lookup: must not panic on multi-byte prefix.
11863        // CJK counts as word-like, so no pairing — single quote inserted.
11864        setup_cursors(&mut cx, &view.input, "中|");
11865        cx.update(|window, cx| {
11866            view.input.update(cx, |state, 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_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
11875        let view = InputView::<EditorMode>::new(cx);
11876        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11877        // Cursor before existing closing quote: typing `"` skips past it.
11878        setup_cursors(&mut cx, &view.input, "\"hello|\"");
11879        cx.update(|window, cx| {
11880            view.input.update(cx, |state, cx| {
11881                state.replace_text_in_range(None, "\"", window, cx);
11882            });
11883        });
11884        assert_cursors(&mut cx, &view.input, "\"hello\"|");
11885        view.input.read_with(&cx, |state, _| {
11886            assert!(state.active_selection().is_empty());
11887        });
11888    }
11889
11890    #[gpui::test]
11891    fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
11892        let view = InputView::<EditorMode>::new(cx);
11893        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11894        // UTF-16 conversion: deleting `()` after CJK must not touch neighbors.
11895        setup_cursors(&mut cx, &view.input, "中(|)abc");
11896        cx.update(|window, cx| {
11897            view.input
11898                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
11899        });
11900        assert_cursors(&mut cx, &view.input, "中|abc");
11901    }
11902
11903    #[gpui::test]
11904    fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
11905        let view = InputView::<EditorMode>::new(cx);
11906        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11907        setup_cursors(&mut cx, &view.input, "{|}");
11908        cx.update(|window, cx| {
11909            view.input.update(cx, |state, cx| {
11910                state.set_smart_indent(false, window, cx);
11911                state.enter(
11912                    &Enter {
11913                        secondary: false,
11914                        shift: false,
11915                    },
11916                    window,
11917                    cx,
11918                );
11919            });
11920        });
11921        // Smart indent controls both structural splitting and extra indentation.
11922        assert_cursors(&mut cx, &view.input, "{\n|}");
11923    }
11924
11925    #[gpui::test]
11926    fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
11927        let view = InputView::<EditorMode>::new(cx);
11928        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11929        setup_cursors(&mut cx, &view.input, "{|}");
11930        cx.update(|window, cx| {
11931            view.input.update(cx, |state, cx| {
11932                state.set_auto_close(false, window, cx);
11933                state.enter(
11934                    &Enter {
11935                        secondary: false,
11936                        shift: false,
11937                    },
11938                    window,
11939                    cx,
11940                );
11941            });
11942        });
11943        // Disabling automatic insertion does not disable structural indentation.
11944        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
11945    }
11946
11947    #[gpui::test]
11948    fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
11949        use crate::input::{AutoClosingPair, set_language_config};
11950        let view = InputView::<EditorMode>::new(cx);
11951        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11952        cx.update(|window, cx| {
11953            set_language_config(
11954                "alpha",
11955                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
11956                cx,
11957            );
11958            set_language_config(
11959                "beta",
11960                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
11961                cx,
11962            );
11963            let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
11964            let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
11965            first.update(cx, |state, cx| {
11966                state.replace_text_in_range(None, "«", window, cx);
11967                assert_eq!(state.text().to_string(), "«»");
11968                state.set_value("", window, cx);
11969                state.set_smart_indent(false, window, cx);
11970                state.set_highlighter("beta", cx);
11971                assert!(!state.mode.is_smart_indent());
11972                state.replace_text_in_range(None, "‹", window, cx);
11973                assert_eq!(state.text().to_string(), "‹›");
11974                state.set_value("", window, cx);
11975                state.set_highlighter("unknown", cx);
11976                state.replace_text_in_range(None, "(", window, cx);
11977                assert_eq!(state.text().to_string(), "()");
11978            });
11979            second.update(cx, |state, cx| {
11980                state.replace_text_in_range(None, "‹", window, cx);
11981                assert_eq!(state.text().to_string(), "‹›");
11982            });
11983        });
11984    }
11985
11986    #[gpui::test]
11987    fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
11988        use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
11989        struct StringLanguages(Rc<Cell<usize>>);
11990        impl LanguageProvider for StringLanguages {
11991            fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
11992                self.0.set(self.0.get() + 1);
11993                Some(Rc::new(StringAllProvider))
11994            }
11995        }
11996        struct CodeLanguages;
11997        impl LanguageProvider for CodeLanguages {}
11998        let view = InputView::<EditorMode>::new(cx);
11999        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12000        cx.update(|window, cx| {
12001            let creations = Rc::new(Cell::new(0));
12002            set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
12003            view.input.update(cx, |state, cx| {
12004                state.replace_text_in_range(None, "(", window, cx);
12005                state.replace_text_in_range(None, "[", window, cx);
12006                assert_eq!(state.text().to_string(), "([");
12007                assert_eq!(
12008                    creations.get(),
12009                    1,
12010                    "retain the document provider between edits"
12011                );
12012            });
12013            set_language_provider(Rc::new(CodeLanguages), cx);
12014            view.input.update(cx, |state, cx| {
12015                state.replace_text_in_range(None, "{", window, cx);
12016                assert_eq!(state.text().to_string(), "([{}");
12017            });
12018        });
12019    }
12020
12021    #[gpui::test]
12022    fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
12023        use crate::input::{AutoClosingPair, set_language_config};
12024        let view = InputView::<EditorMode>::new(cx);
12025        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12026        setup_cursors(&mut cx, &view.input, "|");
12027        cx.update(|window, cx| {
12028            view.input.update(cx, |state, cx| {
12029                state.set_highlighter("CUSTOM", cx);
12030                state.set_auto_close(false, window, cx);
12031                state.set_smart_indent(false, window, cx);
12032            });
12033            set_language_config(
12034                "custom",
12035                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
12036                cx,
12037            );
12038            // Batched registrations must update every affected language.
12039            set_language_config("other", LanguageConfig::default(), cx);
12040            view.input.update(cx, |state, cx| {
12041                assert!(!state.mode.is_auto_close());
12042                assert!(!state.mode.is_smart_indent());
12043                state.set_auto_close(true, window, cx);
12044                state.replace_text_in_range(None, "«", window, cx);
12045            });
12046        });
12047        assert_cursors(&mut cx, &view.input, "«|»");
12048    }
12049
12050    #[gpui::test]
12051    fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
12052        let view = InputView::<EditorMode>::new(cx);
12053        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12054        setup_cursors(&mut cx, &view.input, "|word");
12055        cx.update(|window, cx| {
12056            view.input.update(cx, |state, cx| {
12057                state.replace_text_in_range(None, "(", window, cx)
12058            });
12059        });
12060        assert_cursors(&mut cx, &view.input, "(|word");
12061        setup_cursors(&mut cx, &view.input, "|word");
12062        cx.update(|window, cx| {
12063            view.input.update(cx, |state, cx| {
12064                crate::input::set_language_config(
12065                    state.language_name(),
12066                    LanguageConfig::default().auto_close_before("w"),
12067                    cx,
12068                );
12069                state.replace_text_in_range(None, "(", window, cx);
12070            });
12071        });
12072        assert_cursors(&mut cx, &view.input, "(|)word");
12073    }
12074
12075    #[gpui::test]
12076    fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
12077        use crate::input::{AutoClosingPair, SyntaxContext};
12078        let view = InputView::<EditorMode>::new(cx);
12079        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12080        setup_cursors(&mut cx, &view.input, "|");
12081        cx.update(|window, cx| {
12082            view.input.update(cx, |state, cx| {
12083                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12084                crate::input::set_language_config(
12085                    state.language_name(),
12086                    LanguageConfig::default().auto_closing_pairs([
12087                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
12088                        AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
12089                    ]),
12090                    cx,
12091                );
12092                state.replace_text_in_range(None, "(", window, cx);
12093                state.replace_text_in_range(None, "[", window, cx);
12094            });
12095        });
12096        assert_cursors(&mut cx, &view.input, "([|)");
12097    }
12098
12099    #[gpui::test]
12100    fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
12101        use crate::input::{AutoClosingPair, SyntaxContext};
12102        struct BlockComment;
12103        impl crate::input::SyntaxContextProvider for BlockComment {
12104            fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
12105                if text.to_string().contains("/*") {
12106                    SyntaxContext::Comment
12107                } else {
12108                    SyntaxContext::Code
12109                }
12110            }
12111        }
12112        let view = InputView::<EditorMode>::new(cx);
12113        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12114        setup_cursors(&mut cx, &view.input, "|");
12115        cx.update(|window, cx| {
12116            view.input.update(cx, |state, cx| {
12117                set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
12118                crate::input::set_language_config(
12119                    state.language_name(),
12120                    LanguageConfig::default()
12121                        .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
12122                            .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
12123                    cx,
12124                );
12125                state.replace_text_in_range(None, "/", window, cx);
12126                state.replace_text_in_range(None, "*", window, cx);
12127            });
12128        });
12129        assert_cursors(&mut cx, &view.input, "/*|*/");
12130        cx.update(|window, cx| {
12131            view.input
12132                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12133        });
12134        assert_cursors(&mut cx, &view.input, "|");
12135        cx.update(|window, cx| {
12136            view.input.update(cx, |state, cx| {
12137                state.undo(&Undo, window, cx);
12138                state.replace_text_in_range(None, "*", window, cx);
12139                state.replace_text_in_range(None, "/", window, cx);
12140            });
12141        });
12142        assert_cursors(&mut cx, &view.input, "/**/|");
12143    }
12144
12145    #[gpui::test]
12146    fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
12147        use crate::input::BracketPair;
12148        let view = InputView::<EditorMode>::new(cx);
12149        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12150        setup_cursors(&mut cx, &view.input, "|");
12151        cx.update(|window, cx| {
12152            view.input.update(cx, |state, cx| {
12153                let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
12154                rules.auto_closing_pairs = None;
12155                crate::input::set_language_config(state.language_name(), rules.clone(), cx);
12156                state.replace_text_in_range(None, "«", window, cx);
12157                crate::input::set_language_config(
12158                    state.language_name(),
12159                    rules.auto_closing_pairs([]),
12160                    cx,
12161                );
12162                state.replace_text_in_range(None, "«", window, cx);
12163            });
12164        });
12165        assert_cursors(&mut cx, &view.input, "««|»");
12166    }
12167
12168    #[gpui::test]
12169    fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
12170        use crate::input::{AutoClosingPair, SyntaxContext};
12171        let view = InputView::<EditorMode>::new(cx);
12172        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12173        setup_cursors(&mut cx, &view.input, "|");
12174        cx.update(|window, cx| {
12175            view.input.update(cx, |state, cx| {
12176                crate::input::set_language_config(
12177                    state.language_name(),
12178                    LanguageConfig::default()
12179                        .auto_closing_pairs([
12180                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12181                        ]),
12182                    cx,
12183                );
12184                state.replace_text_in_range(None, "/", window, cx);
12185                state.replace_text_in_range(None, "*", window, cx);
12186                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12187                state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
12188                state.undo(&Undo, window, cx);
12189                state.replace_text_in_range(None, "*", window, cx);
12190                state.replace_text_in_range(None, "/", window, cx);
12191            });
12192        });
12193        assert_cursors(&mut cx, &view.input, "/**/|");
12194    }
12195
12196    #[gpui::test]
12197    fn test_undo_does_not_promote_literal_comment_delimiters(cx: &mut TestAppContext) {
12198        use crate::input::{AutoClosingPair, SyntaxContext};
12199        let view = InputView::<EditorMode>::new(cx);
12200        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12201        setup_cursors(&mut cx, &view.input, "/*|*/");
12202        cx.update(|window, cx| {
12203            view.input.update(cx, |state, cx| {
12204                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12205                crate::input::set_language_config(
12206                    state.language_name(),
12207                    LanguageConfig::default()
12208                        .auto_closing_pairs([
12209                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12210                        ]),
12211                    cx,
12212                );
12213                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
12214                state.undo(&Undo, window, cx);
12215                state.backspace(&Backspace, window, cx);
12216            });
12217        });
12218        assert_cursors(&mut cx, &view.input, "/|*/");
12219    }
12220
12221    #[gpui::test]
12222    fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
12223        use crate::input::{AutoClosingPair, SyntaxContext};
12224        struct CommentScope;
12225        impl crate::input::SyntaxContextProvider for CommentScope {
12226            fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
12227                if text
12228                    .to_string()
12229                    .find("*/")
12230                    .is_some_and(|end| offset < end + 2)
12231                {
12232                    SyntaxContext::Comment
12233                } else {
12234                    SyntaxContext::Code
12235                }
12236            }
12237        }
12238        let view = InputView::<EditorMode>::new(cx);
12239        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12240        setup_cursors(&mut cx, &view.input, "|");
12241        cx.update(|window, cx| {
12242            view.input.update(cx, |state, cx| {
12243                set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
12244                crate::input::set_language_config(
12245                    state.language_name(),
12246                    LanguageConfig::default().auto_closing_pairs([
12247                        AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
12248                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
12249                    ]),
12250                    cx,
12251                );
12252                state.replace_text_in_range(None, "/", window, cx);
12253                state.replace_text_in_range(None, "*", window, cx);
12254                state.set_selected_range(4..4, cx);
12255                state.replace_text_in_range(None, "(", window, cx);
12256                state.set_selected_range(2..2, cx);
12257                state.replace_text_in_range(None, "*", window, cx);
12258                state.replace_text_in_range(None, "/", window, cx);
12259            });
12260        });
12261        assert_cursors(&mut cx, &view.input, "/**/|()");
12262        cx.update(|window, cx| {
12263            view.input.update(cx, |state, cx| {
12264                state.set_selected_range(2..2, cx);
12265                state.backspace(&Backspace, window, cx);
12266                state.undo(&Undo, window, cx);
12267                state.redo(&Redo, window, cx);
12268            });
12269        });
12270        assert_cursors(&mut cx, &view.input, "|()");
12271    }
12272
12273    #[gpui::test]
12274    fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
12275        use crate::input::{AutoClosingPair, SyntaxContext};
12276        let view = InputView::<EditorMode>::new(cx);
12277        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12278        setup_cursors(&mut cx, &view.input, "|");
12279        cx.update(|window, cx| {
12280            view.input.update(cx, |state, cx| {
12281                crate::input::set_language_config(
12282                    state.language_name(),
12283                    LanguageConfig::default()
12284                        .auto_closing_pairs([
12285                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12286                        ]),
12287                    cx,
12288                );
12289                state.replace_text_in_range(None, "/", window, cx);
12290                state.replace_text_in_range(None, "*", window, cx);
12291                state.replace_text_in_range(Some(0..2), "//", window, cx);
12292                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12293                state.replace_text_in_range(None, "*", window, cx);
12294            });
12295        });
12296        assert_cursors(&mut cx, &view.input, "//*|*/");
12297    }
12298
12299    #[gpui::test]
12300    fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
12301        use crate::input::IndentationRules;
12302        let view = InputView::<EditorMode>::new(cx);
12303        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12304        setup_cursors(&mut cx, &view.input, "BEGIN|");
12305        cx.update(|window, cx| {
12306            view.input.update(cx, |state, cx| {
12307                let rules = |insensitive| {
12308                    LanguageConfig::default().indentation_rules(IndentationRules::new(
12309                        regex::RegexBuilder::new("begin$")
12310                            .case_insensitive(insensitive)
12311                            .build()
12312                            .unwrap(),
12313                        regex::Regex::new("^end").unwrap(),
12314                    ))
12315                };
12316                crate::input::set_language_config(state.language_name(), rules(false), cx);
12317                crate::input::set_language_config(state.language_name(), rules(true), cx);
12318                state.enter(
12319                    &Enter {
12320                        secondary: false,
12321                        shift: false,
12322                    },
12323                    window,
12324                    cx,
12325                );
12326            });
12327        });
12328        assert_cursors(&mut cx, &view.input, "BEGIN\n  |");
12329    }
12330
12331    #[gpui::test]
12332    fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
12333        use crate::input::IndentationRules;
12334        let view = InputView::<EditorMode>::new(cx);
12335        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12336        let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
12337            regex::Regex::new(r"\bbegin\s*$").unwrap(),
12338            regex::Regex::new(r"^\s*end\b").unwrap(),
12339        ));
12340        for (before, expected) in [("begin|", "begin\n  |"), ("  |end", "  \n|end")] {
12341            setup_cursors(&mut cx, &view.input, before);
12342            cx.update(|window, cx| {
12343                view.input.update(cx, |state, cx| {
12344                    crate::input::set_language_config(state.language_name(), rules.clone(), cx);
12345                    state.enter(
12346                        &Enter {
12347                            secondary: false,
12348                            shift: false,
12349                        },
12350                        window,
12351                        cx,
12352                    );
12353                });
12354            });
12355            assert_cursors(&mut cx, &view.input, expected);
12356        }
12357    }
12358
12359    #[gpui::test]
12360    fn test_custom_language_config(cx: &mut TestAppContext) {
12361        let view = InputView::<EditorMode>::new(cx);
12362        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12363        cx.update(|_window, cx| {
12364            view.input.update(cx, |state, cx| {
12365                crate::input::set_language_config(
12366                    state.language_name(),
12367                    crate::input::language_config::LanguageConfig::default()
12368                        .brackets([crate::input::BracketPair::new("«", "»")])
12369                        .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
12370                    cx,
12371                );
12372            });
12373        });
12374        // Custom pair closes.
12375        setup_cursors(&mut cx, &view.input, "|");
12376        cx.update(|window, cx| {
12377            view.input.update(cx, |state, cx| {
12378                state.replace_text_in_range(None, "«", window, cx);
12379            });
12380        });
12381        assert_cursors(&mut cx, &view.input, "«|»");
12382        // Default `(` no longer pairs under custom rules.
12383        cx.update(|window, cx| {
12384            view.input.update(cx, |state, cx| {
12385                state.set_value("\n", window, cx);
12386                state.set_selected_range(0..0, cx);
12387                state.replace_text_in_range(None, "(", window, cx);
12388            });
12389        });
12390        assert_cursors(&mut cx, &view.input, "(|");
12391    }
12392
12393    #[gpui::test]
12394    fn test_skip_records_no_history(cx: &mut TestAppContext) {
12395        let view = InputView::<EditorMode>::new(cx);
12396        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12397        setup_cursors(&mut cx, &view.input, "(a|)");
12398        cx.update(|window, cx| {
12399            view.input.update(cx, |state, cx| {
12400                // Type a normal char (recorded), then skip over `)`.
12401                state.replace_text_in_range(None, "b", window, cx);
12402            });
12403        });
12404        assert_cursors(&mut cx, &view.input, "(ab|)");
12405        cx.update(|window, cx| {
12406            view.input.update(cx, |state, cx| {
12407                state.replace_text_in_range(None, ")", window, cx);
12408            });
12409        });
12410        // Skip is a pure cursor move: no history entry of its own.
12411        assert_cursors(&mut cx, &view.input, "(ab)|");
12412        // Undo removes `b`, never exposing a transient `())`.
12413        cx.update(|window, cx| {
12414            view.input
12415                .update(cx, |state, cx| state.undo(&Undo, window, cx));
12416        });
12417        assert_cursors(&mut cx, &view.input, "(a|)");
12418    }
12419
12420    #[gpui::test]
12421    fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
12422        let view = InputView::<EditorMode>::new(cx);
12423        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12424        setup_cursors(&mut cx, &view.input, "|");
12425        cx.update(|window, cx| {
12426            view.input.update(cx, |state, cx| {
12427                state.replace_text_in_range(None, "(", window, cx);
12428            });
12429        });
12430        assert_cursors(&mut cx, &view.input, "(|)");
12431        // One undo removes the whole pair (typing coalescing).
12432        cx.update(|window, cx| {
12433            view.input
12434                .update(cx, |state, cx| state.undo(&Undo, window, cx));
12435        });
12436        assert_cursors(&mut cx, &view.input, "|");
12437    }
12438
12439    #[gpui::test]
12440    fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
12441        let view = InputView::<EditorMode>::new(cx);
12442        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12443        // Odd backslashes: the typed quote is escaped, insert literally.
12444        setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
12445        cx.update(|window, cx| {
12446            view.input.update(cx, |state, cx| {
12447                state.replace_text_in_range(None, "\"", window, cx);
12448            });
12449        });
12450        assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
12451    }
12452
12453    #[gpui::test]
12454    fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
12455        let view = InputView::<EditorMode>::new(cx);
12456        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12457        // Even backslashes: quote is not escaped, skip over the terminator.
12458        setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
12459        cx.update(|window, cx| {
12460            view.input.update(cx, |state, cx| {
12461                state.replace_text_in_range(None, "\"", window, cx);
12462            });
12463        });
12464        assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
12465    }
12466
12467    #[gpui::test]
12468    fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
12469        use crate::input::{BracketPair, LanguageConfig};
12470
12471        let view = InputView::<EditorMode>::new(cx);
12472        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12473        cx.update(|window, cx| {
12474            view.input.update(cx, |state, cx| {
12475                // Language changes update rules without changing editor preferences.
12476                state.set_smart_indent(false, window, cx);
12477                crate::input::set_language_config(
12478                    state.language_name(),
12479                    LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
12480                    cx,
12481                );
12482            });
12483        });
12484        view.input.read_with(&cx, |state, _| {
12485            assert!(!state.mode.is_smart_indent(), "editor option preserved");
12486            assert!(state.mode.is_auto_close());
12487            let pairs = &state.mode.language_config().unwrap().brackets;
12488            assert_eq!(pairs.len(), 1, "pairs follow configuration");
12489            assert_eq!(pairs[0].open.as_ref(), "«");
12490        });
12491    }
12492
12493    struct CommentAllProvider;
12494    impl crate::input::SyntaxContextProvider for CommentAllProvider {
12495        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12496            crate::input::SyntaxContext::Comment
12497        }
12498    }
12499
12500    struct StringAllProvider;
12501    impl crate::input::SyntaxContextProvider for StringAllProvider {
12502        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12503            crate::input::SyntaxContext::String
12504        }
12505    }
12506
12507    #[gpui::test]
12508    fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
12509        use std::rc::Rc;
12510
12511        let view = InputView::<EditorMode>::new(cx);
12512        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12513        cx.update(|_window, cx| {
12514            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12515        });
12516        // Trigger `{` inside a string: no extra level, base indent only.
12517        setup_cursors(&mut cx, &view.input, "  x = {|");
12518        cx.update(|window, cx| {
12519            view.input.update(cx, |state, cx| {
12520                state.enter(
12521                    &Enter {
12522                        secondary: false,
12523                        shift: false,
12524                    },
12525                    window,
12526                    cx,
12527                );
12528            });
12529        });
12530        assert_cursors(&mut cx, &view.input, "  x = {\n  |");
12531    }
12532
12533    #[gpui::test]
12534    fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
12535        use std::rc::Rc;
12536
12537        let view = InputView::<EditorMode>::new(cx);
12538        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12539        cx.update(|_window, cx| {
12540            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12541        });
12542        // No three-way split inside strings: plain newline instead.
12543        setup_cursors(&mut cx, &view.input, "{|}");
12544        cx.update(|window, cx| {
12545            view.input.update(cx, |state, cx| {
12546                state.enter(
12547                    &Enter {
12548                        secondary: false,
12549                        shift: false,
12550                    },
12551                    window,
12552                    cx,
12553                );
12554            });
12555        });
12556        assert_cursors(&mut cx, &view.input, "{\n|}");
12557    }
12558
12559    #[gpui::test]
12560    fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
12561        use std::rc::Rc;
12562
12563        let view = InputView::<EditorMode>::new(cx);
12564        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12565        cx.update(|_window, cx| {
12566            set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
12567        });
12568        setup_cursors(&mut cx, &view.input, "|");
12569        cx.update(|window, cx| {
12570            view.input.update(cx, |state, cx| {
12571                state.replace_text_in_range(None, "(", window, cx);
12572            });
12573        });
12574        // In comments every character is literal.
12575        assert_cursors(&mut cx, &view.input, "(|");
12576    }
12577
12578    #[gpui::test]
12579    fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
12580        let view = InputView::<EditorMode>::new(cx);
12581        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12582        setup_cursors(&mut cx, &view.input, "{|}");
12583        cx.update(|window, cx| {
12584            view.input
12585                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12586        });
12587        assert_cursors(&mut cx, &view.input, "|");
12588    }
12589
12590    #[gpui::test]
12591    fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
12592        let view = InputView::<EditorMode>::new(cx);
12593        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12594        setup_cursors(&mut cx, &view.input, "{d|}");
12595        cx.update(|window, cx| {
12596            view.input
12597                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12598        });
12599        // Only `d` is deleted, the closing brace stays.
12600        assert_cursors(&mut cx, &view.input, "{|}");
12601    }
12602
12603    #[gpui::test]
12604    fn test_enter_splits_brackets(cx: &mut TestAppContext) {
12605        let view = InputView::<EditorMode>::new(cx);
12606        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12607        setup_cursors(&mut cx, &view.input, "{|}");
12608        cx.update(|window, cx| {
12609            view.input.update(cx, |state, cx| {
12610                state.enter(
12611                    &Enter {
12612                        secondary: false,
12613                        shift: false,
12614                    },
12615                    window,
12616                    cx,
12617                );
12618            });
12619        });
12620        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
12621        // Selection must be collapsed: typing next must insert, not replace.
12622        view.input.read_with(&cx, |state, _| {
12623            assert!(state.active_selection().is_empty());
12624        });
12625        cx.update(|window, cx| {
12626            view.input.update(cx, |state, cx| {
12627                state.replace_text_in_range(None, "x", window, cx);
12628            });
12629        });
12630        assert_cursors(&mut cx, &view.input, "{\n  x|\n}");
12631    }
12632
12633    #[gpui::test]
12634    fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
12635        let view = InputView::<EditorMode>::new(cx);
12636        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12637        setup_cursors(&mut cx, &view.input, "fn main() {|");
12638        cx.update(|window, cx| {
12639            view.input.update(cx, |state, cx| {
12640                state.enter(
12641                    &Enter {
12642                        secondary: false,
12643                        shift: false,
12644                    },
12645                    window,
12646                    cx,
12647                );
12648            });
12649        });
12650        assert_cursors(&mut cx, &view.input, "fn main() {\n  |");
12651    }
12652
12653    #[gpui::test]
12654    fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
12655        let view = multi_line(cx);
12656        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12657        setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12658        cx.update(|window, cx| {
12659            view.input
12660                .update(cx, |state, cx| state.indent(true, window, cx));
12661        });
12662        assert_cursors(&mut cx, &view.input, "  |ab\n  |cd\n  |ef");
12663        cx.update(|window, cx| {
12664            view.input
12665                .update(cx, |state, cx| state.outdent(true, window, cx));
12666        });
12667        assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12668    }
12669
12670    #[gpui::test]
12671    fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
12672        let view = multi_line(cx);
12673        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12674        setup_cursors(&mut cx, &view.input, "ab\n | cd");
12675        cx.update(|window, cx| {
12676            view.input
12677                .update(cx, |state, cx| state.outdent(true, window, cx));
12678        });
12679        assert_cursors(&mut cx, &view.input, "ab\n|cd");
12680    }
12681
12682    #[gpui::test]
12683    fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
12684        let view = InputView::build(cx, |state| state);
12685        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12686        cx.update(|window, cx| {
12687            view.input.update(cx, |state, cx| {
12688                state.set_value("abc", window, cx);
12689                state.set_selected_range(1..2, cx);
12690                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
12691                state.replace_text_in_range(None, "你", window, cx);
12692                state.undo(&Undo, window, cx);
12693                assert_eq!(state.value(), "abc");
12694                assert_eq!(state.selected_range(), 1..2);
12695                state.redo(&Redo, window, cx);
12696                assert_eq!(state.selected_range(), 4..4);
12697            });
12698        });
12699    }
12700
12701    #[gpui::test]
12702    fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
12703        let view = multi_line(cx);
12704        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12705        cx.update(|window, cx| {
12706            view.input.update(cx, |state, cx| {
12707                state.set_value("abc", window, cx);
12708                state.set_selected_range(1..1, cx);
12709                state.replace_text_in_range(None, "X", window, cx);
12710                state.set_selected_range(0..0, cx);
12711                state.replace_text_in_range(None, "", window, cx);
12712                state.undo(&Undo, window, cx);
12713                state.redo(&Redo, window, cx);
12714                assert_eq!(state.value(), "aXbc");
12715                assert_eq!(state.selected_range(), 2..2);
12716            });
12717        });
12718    }
12719
12720    #[gpui::test]
12721    fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
12722        let view = multi_line(cx);
12723        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12724        let input = view.input;
12725
12726        setup_cursors(&mut cx, &input, "|hello |world|");
12727        cx.update(|window, cx| {
12728            input.update(cx, |state, cx| {
12729                state.replace_text_in_range(None, ">>>", window, cx);
12730            });
12731        });
12732        assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
12733    }
12734
12735    #[gpui::test]
12736    fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
12737        let view = multi_line(cx);
12738        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12739        let input = view.input;
12740
12741        setup_cursors(&mut cx, &input, "|islands| cars|");
12742        cx.update(|window, cx| {
12743            input.update(cx, |state, cx| {
12744                state.backspace(&Backspace, window, cx);
12745            });
12746        });
12747        // The first cursor has nothing to delete. The others delete an `s`.
12748        assert_cursors(&mut cx, &input, "|island| car|");
12749    }
12750
12751    #[gpui::test]
12752    fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
12753        let view = multi_line(cx);
12754        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12755        let input = view.input;
12756
12757        setup_cursors(&mut cx, &input, "hello| |world");
12758        cx.update(|window, cx| {
12759            input.update(cx, |state, cx| {
12760                state.delete(&Delete, window, cx);
12761            });
12762        });
12763        // Adjacent deletions merge into a single cursor.
12764        assert_cursors(&mut cx, &input, "hello|orld");
12765    }
12766
12767    #[gpui::test]
12768    fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
12769        let view = multi_line(cx);
12770        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12771        let input = view.input;
12772
12773        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12774        cx.update(|window, cx| {
12775            input.update(cx, |state, cx| {
12776                state.replace_text_in_range(None, "a", window, cx);
12777            });
12778        });
12779        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12780
12781        // The whole multi-edit insert is a single undo transaction.
12782        input.read_with(&cx, |state, _| {
12783            assert_eq!(state.undo_manager.undo_count(), 1);
12784        });
12785
12786        cx.update(|window, cx| {
12787            input.update(cx, |state, cx| {
12788                state.backspace(&Backspace, window, cx);
12789            });
12790        });
12791        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12792    }
12793
12794    #[gpui::test]
12795    fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
12796        let view = multi_line(cx);
12797        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12798        let input = view.input;
12799
12800        setup_cursors(&mut cx, &input, "ab|cd\nabcd");
12801        cx.update(|window, cx| {
12802            input.update(cx, |state, cx| {
12803                state.add_cursor_below(&AddCursorBelow, window, cx);
12804            });
12805        });
12806        assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
12807    }
12808
12809    #[gpui::test]
12810    fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
12811        let view = multi_line(cx);
12812        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12813        let input = view.input;
12814
12815        setup_cursors(&mut cx, &input, "he|llo");
12816        cx.update(|_, cx| {
12817            input.update(cx, |state, cx| {
12818                // Duplicate of the existing cursor is rejected.
12819                state.add_cursor_at(2, cx);
12820                assert_eq!(state.selections.len(), 1);
12821                // A distinct offset adds a cursor.
12822                state.add_cursor_at(4, cx);
12823                assert_eq!(state.selections.len(), 2);
12824            });
12825        });
12826    }
12827
12828    #[gpui::test]
12829    fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
12830        let view = multi_line(cx);
12831        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12832        let input = view.input;
12833
12834        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12835        cx.update(|window, cx| {
12836            input.update(cx, |state, cx| {
12837                state.replace_text_in_range(None, "a", window, cx);
12838            });
12839        });
12840        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12841
12842        cx.update(|window, cx| {
12843            input.update(cx, |state, cx| {
12844                state.undo(&Undo, window, cx);
12845            });
12846        });
12847        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12848
12849        cx.update(|window, cx| {
12850            input.update(cx, |state, cx| {
12851                state.redo(&Redo, window, cx);
12852            });
12853        });
12854        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
12855    }
12856
12857    #[gpui::test]
12858    fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
12859        let view = multi_line(cx);
12860        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12861        let input = view.input;
12862
12863        setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12864        cx.update(|window, cx| {
12865            input.update(cx, |state, cx| {
12866                state.replace_text_in_range(None, "a", window, cx);
12867            });
12868        });
12869        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12870
12871        cx.update(|window, cx| {
12872            input.update(cx, |state, cx| {
12873                state.undo(&Undo, window, cx);
12874            });
12875        });
12876        assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
12877
12878        cx.update(|window, cx| {
12879            input.update(cx, |state, cx| {
12880                state.redo(&Redo, window, cx);
12881            });
12882        });
12883        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
12884    }
12885
12886    #[gpui::test]
12887    fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
12888        let view = multi_line(cx);
12889        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12890        let input = view.input;
12891
12892        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12893        for ch in ['a', 'b', 'c'] {
12894            cx.update(|window, cx| {
12895                input.update(cx, |state, cx| {
12896                    state.replace_text_in_range(None, &ch.to_string(), window, cx);
12897                });
12898            });
12899        }
12900        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12901
12902        // The repeated keystrokes form one typing gesture.
12903        cx.update(|window, cx| {
12904            input.update(cx, |state, cx| {
12905                assert_eq!(state.undo_manager.undo_count(), 1);
12906                state.undo(&Undo, window, cx);
12907            });
12908        });
12909        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12910
12911        cx.update(|window, cx| {
12912            input.update(cx, |state, cx| {
12913                state.redo(&Redo, window, cx);
12914            });
12915        });
12916        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12917    }
12918
12919    #[gpui::test]
12920    fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
12921        let view = multi_line(cx);
12922        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12923        let input = view.input;
12924
12925        setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12926        for _ in 0..3 {
12927            cx.update(|window, cx| {
12928                input.update(cx, |state, cx| {
12929                    state.backspace(&Backspace, window, cx);
12930                });
12931            });
12932        }
12933        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12934
12935        cx.update(|window, cx| {
12936            input.update(cx, |state, cx| {
12937                assert_eq!(state.undo_manager.undo_count(), 1);
12938                state.undo(&Undo, window, cx);
12939            });
12940        });
12941        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
12942    }
12943
12944    #[gpui::test]
12945    fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
12946        let view = multi_line(cx);
12947        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12948        let input = view.input;
12949
12950        setup_cursors(&mut cx, &input, "|1\n2\n3");
12951        cx.update(|window, cx| {
12952            input.update(cx, |state, cx| {
12953                state.replace_text_in_range(None, "a", window, cx);
12954                state.add_cursor_below(&AddCursorBelow, window, cx);
12955                state.replace_text_in_range(None, "b", window, cx);
12956            });
12957        });
12958        assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
12959
12960        // The keystroke after the cursor was added is its own undo entry.
12961        cx.update(|window, cx| {
12962            input.update(cx, |state, cx| {
12963                state.undo(&Undo, window, cx);
12964            });
12965        });
12966        assert_cursors(&mut cx, &input, "a|1\n2|\n3");
12967    }
12968
12969    #[gpui::test]
12970    fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
12971        let view = multi_line(cx);
12972        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12973        let input = view.input;
12974
12975        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12976        cx.update(|window, cx| {
12977            input.update(cx, |state, cx| {
12978                state.indent_inline(&IndentInline, window, cx);
12979                assert_eq!(state.undo_manager.undo_count(), 1);
12980                state.undo(&Undo, window, cx);
12981            });
12982        });
12983        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
12984    }
12985
12986    #[gpui::test]
12987    fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
12988        let view = multi_line(cx);
12989        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12990        let input = view.input;
12991
12992        // Cursors at line starts.
12993        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
12994        cx.update(|window, cx| {
12995            input.update(cx, |state, cx| {
12996                state.indent(false, window, cx);
12997            });
12998        });
12999        assert_cursors(&mut cx, &input, "  |1\n  |2\n  |3");
13000
13001        cx.update(|window, cx| {
13002            input.update(cx, |state, cx| {
13003                state.outdent(false, window, cx);
13004            });
13005        });
13006        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13007    }
13008
13009    #[gpui::test]
13010    fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
13011        let view = multi_line(cx);
13012        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13013        let input = view.input;
13014
13015        // A mid-line indent lands at the cursor, and the outdent does not
13016        // take it back: it only ever removes leading line indentation.
13017        setup_cursors(&mut cx, &input, "1|2\n1|2");
13018        cx.update(|window, cx| {
13019            input.update(cx, |state, cx| {
13020                state.indent(false, window, cx);
13021            });
13022        });
13023        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
13024
13025        cx.update(|window, cx| {
13026            input.update(cx, |state, cx| {
13027                state.outdent(false, window, cx);
13028            });
13029        });
13030        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
13031
13032        // A line with leading indentation loses that, wherever the cursor is.
13033        setup_cursors(&mut cx, &input, "  1|2\n  1|2");
13034        cx.update(|window, cx| {
13035            input.update(cx, |state, cx| {
13036                state.outdent(false, window, cx);
13037            });
13038        });
13039        assert_cursors(&mut cx, &input, "1|2\n1|2");
13040    }
13041
13042    #[gpui::test]
13043    fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
13044        let view = multi_line(cx);
13045        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13046        let input = view.input;
13047
13048        setup_cursors(&mut cx, &input, "a|b\nc|d");
13049        cx.update(|window, cx| {
13050            input.update(cx, |state, cx| {
13051                let before: Vec<_> = state.selections.iter().copied().collect();
13052                state.set_readonly(true, cx);
13053                state.backspace(&Backspace, window, cx);
13054                state.indent_inline(&IndentInline, window, cx);
13055
13056                assert_eq!(state.value(), "ab\ncd\n");
13057                assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
13058            });
13059        });
13060    }
13061
13062    #[gpui::test]
13063    fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
13064        let view = multi_line(cx);
13065        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13066        let input = view.input;
13067
13068        setup_cursors(&mut cx, &input, "x|\n|y");
13069        cx.update(|window, cx| {
13070            input.update(cx, |state, cx| {
13071                let mut selections: Vec<_> = state.selections.iter().copied().collect();
13072                selections.swap(0, 1);
13073                state.selections.replace_all(selections);
13074                let active_id = state.active_selection().id;
13075                state.replace_text_in_range(None, "!", window, cx);
13076                assert_eq!(state.active_selection().id, active_id);
13077            });
13078        });
13079    }
13080
13081    #[gpui::test]
13082    fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
13083        let view = multi_line(cx);
13084        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13085        let input = view.input;
13086
13087        cx.update(|window, cx| {
13088            input.update(cx, |state, cx| {
13089                state.set_value("line1\nline2\nline3", window, cx);
13090                let id = state.selections.generate_id();
13091                state
13092                    .selections
13093                    .replace_all(vec![CursorSelection::new(id, 0, 17)]);
13094                cx.notify();
13095            });
13096        });
13097
13098        cx.update(|window, cx| {
13099            input.update(cx, |state, cx| {
13100                state.indent(true, window, cx);
13101            });
13102        });
13103        input.read_with(&cx, |state, _| {
13104            assert_eq!(state.text.to_string(), "  line1\n  line2\n  line3");
13105        });
13106
13107        cx.update(|window, cx| {
13108            input.update(cx, |state, cx| {
13109                state.outdent(true, window, cx);
13110            });
13111        });
13112        input.read_with(&cx, |state, _| {
13113            assert_eq!(state.text.to_string(), "line1\nline2\nline3");
13114        });
13115    }
13116
13117    #[gpui::test]
13118    fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
13119        let view = multi_line(cx);
13120        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13121        let input = view.input;
13122
13123        setup_cursors(
13124            &mut cx,
13125            &input,
13126            "on|e two three\none t|wo three\non|e two three",
13127        );
13128
13129        cx.update(|window, cx| {
13130            input.update(cx, |state, cx| {
13131                state.move_to_next_word(&MoveToNextWord, window, cx);
13132            });
13133        });
13134        assert_cursors(
13135            &mut cx,
13136            &input,
13137            "one| two three\none two| three\none| two three",
13138        );
13139
13140        cx.update(|window, cx| {
13141            input.update(cx, |state, cx| {
13142                state.move_to_previous_word(&MoveToPreviousWord, window, cx);
13143            });
13144        });
13145        assert_cursors(
13146            &mut cx,
13147            &input,
13148            "|one two three\none |two three\n|one two three",
13149        );
13150
13151        // Move to end/start of document collapses to a single cursor.
13152        cx.update(|window, cx| {
13153            input.update(cx, |state, cx| {
13154                state.move_to_end(&MoveToEnd, window, cx);
13155            });
13156        });
13157        input.read_with(&cx, |state, _| {
13158            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13159            assert_eq!(cursors, vec![state.text.len()]);
13160        });
13161
13162        cx.update(|window, cx| {
13163            input.update(cx, |state, cx| {
13164                state.move_to_start(&MoveToStart, window, cx);
13165            });
13166        });
13167        input.read_with(&cx, |state, _| {
13168            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13169            assert_eq!(cursors, vec![0]);
13170        });
13171    }
13172
13173    #[gpui::test]
13174    fn test_rtl_arrow_keys_move_visually(cx: &mut TestAppContext) {
13175        let view = multi_line(cx);
13176        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13177        let input = view.input;
13178        // Each Arabic letter is two bytes.
13179        let text = "مرحبا عالم";
13180        let place = |cx: &mut VisualTestContext, offset: usize| {
13181            cx.update(|window, cx| {
13182                input.update(cx, |state, cx| {
13183                    state.set_value(text, window, cx);
13184                    let id = state.selections.generate_id();
13185                    state
13186                        .selections
13187                        .replace_all(vec![CursorSelection::new(id, offset, offset)]);
13188                });
13189            });
13190        };
13191        let selection = |cx: &mut VisualTestContext| {
13192            input.read_with(cx, |state, _| {
13193                let sel = state.active_selection();
13194                (sel.start, sel.end, sel.cursor_offset())
13195            })
13196        };
13197
13198        cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
13199
13200        // Right moves toward the start of a right-to-left paragraph.
13201        place(&mut cx, 4);
13202        cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
13203        assert_eq!(selection(&mut cx).2, 2);
13204        cx.update(|window, cx| input.update(cx, |s, cx| s.left(&MoveLeft, window, cx)));
13205        assert_eq!(selection(&mut cx).2, 4);
13206
13207        // Shift-arrows extend the selection the same way.
13208        cx.update(|window, cx| input.update(cx, |s, cx| s.select_right(&SelectRight, window, cx)));
13209        assert_eq!(selection(&mut cx), (2, 4, 2));
13210        place(&mut cx, 4);
13211        cx.update(|window, cx| input.update(cx, |s, cx| s.select_left(&SelectLeft, window, cx)));
13212        assert_eq!(selection(&mut cx), (4, 6, 6));
13213
13214        // Word movement: Right goes to the previous word start.
13215        let second_word = text.find('ع').unwrap();
13216        place(&mut cx, text.len());
13217        cx.update(|window, cx| {
13218            input.update(cx, |s, cx| s.move_to_next_word(&MoveToNextWord, window, cx))
13219        });
13220        assert_eq!(selection(&mut cx).2, second_word);
13221        place(&mut cx, 0);
13222        cx.update(|window, cx| {
13223            input.update(cx, |s, cx| {
13224                s.move_to_previous_word(&MoveToPreviousWord, window, cx)
13225            })
13226        });
13227        assert_eq!(selection(&mut cx).2, text.find(' ').unwrap());
13228
13229        // Left to right keeps the logical meaning.
13230        cx.update(|_, cx| crate::LayoutDirection::Ltr.set_global(cx));
13231        place(&mut cx, 4);
13232        cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
13233        assert_eq!(selection(&mut cx).2, 6);
13234    }
13235
13236    #[gpui::test]
13237    fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
13238        let view = multi_line(cx);
13239        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13240        let input = view.input;
13241
13242        setup_cursors(
13243            &mut cx,
13244            &input,
13245            "on|e two three\none t|wo three\non|e two three",
13246        );
13247        cx.update(|window, cx| {
13248            input.update(cx, |state, cx| {
13249                state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
13250            });
13251        });
13252        assert_cursors(
13253            &mut cx,
13254            &input,
13255            "|one two three\n|one two three\n|one two three",
13256        );
13257
13258        // Select to document start collapses to the active cursor only.
13259        setup_cursors(
13260            &mut cx,
13261            &input,
13262            "on|e two three\none t|wo three\non|e two three",
13263        );
13264        cx.update(|window, cx| {
13265            input.update(cx, |state, cx| {
13266                state.select_to_start(&SelectToStart, window, cx);
13267            });
13268        });
13269        input.read_with(&cx, |state, _| {
13270            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13271            assert_eq!(cursors, vec![0]);
13272        });
13273    }
13274
13275    #[gpui::test]
13276    fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
13277        let view = multi_line(cx);
13278        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13279        let input = view.input;
13280
13281        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
13282        cx.update(|window, cx| {
13283            input.update(cx, |state, cx| {
13284                state.select_right(&SelectRight, window, cx);
13285            });
13286        });
13287        input.read_with(&cx, |state, _| {
13288            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13289            assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
13290        });
13291
13292        cx.update(|window, cx| {
13293            input.update(cx, |state, cx| {
13294                state.replace_text_in_range(None, "x", window, cx);
13295            });
13296        });
13297        assert_cursors(&mut cx, &input, "x|\nx|\nx|");
13298    }
13299
13300    #[gpui::test]
13301    fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
13302        let view = multi_line(cx);
13303        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13304        let input = view.input;
13305
13306        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
13307        cx.update(|window, cx| {
13308            input.update(cx, |state, cx| {
13309                state.escape(&Escape, window, cx);
13310            });
13311        });
13312        input.read_with(&cx, |state, _| {
13313            assert_eq!(state.selections.len(), 1);
13314        });
13315    }
13316
13317    #[gpui::test]
13318    fn test_build_columnar_selection(cx: &mut TestAppContext) {
13319        let view = multi_line(cx);
13320        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13321        let input = view.input;
13322
13323        setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
13324        cx.update(|_, cx| {
13325            input.update(cx, |state, cx| {
13326                // From row 0 col 1 to row 2 col 3.
13327                state.build_columnar_selection(
13328                    ColumnarPoint::new(1, 0),
13329                    ColumnarPoint::new(13, 0),
13330                    cx,
13331                );
13332                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13333                assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
13334            });
13335        });
13336    }
13337
13338    #[gpui::test]
13339    fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
13340        let view = multi_line(cx);
13341        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13342        let input = view.input;
13343
13344        setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
13345        cx.update(|_, cx| {
13346            input.update(cx, |state, cx| {
13347                // Ends on the short row, 3 columns past its end: the block still spans
13348                // columns 1..5, and only that row is clipped to what it has.
13349                state.build_columnar_selection(
13350                    ColumnarPoint::new(1, 0),
13351                    ColumnarPoint::new(9, 3),
13352                    cx,
13353                );
13354                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13355                assert_eq!(ranges, vec![(1, 5), (8, 9)]);
13356            });
13357        });
13358    }
13359
13360    #[gpui::test]
13361    fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
13362        let view = multi_line(cx);
13363        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13364        let input = view.input;
13365
13366        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13367        cx.update(|_, cx| {
13368            cx.write_to_clipboard(ClipboardItem::new_string("x\ny\nz".to_string()));
13369        });
13370        cx.update(|window, cx| {
13371            input.update(cx, |state, cx| {
13372                state.paste(&Paste, window, cx);
13373            });
13374        });
13375        // One clipboard line per cursor.
13376        assert_cursors(&mut cx, &input, "x|1\ny|2\nz|3");
13377    }
13378
13379    #[gpui::test]
13380    fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
13381        use gpui::{ClipboardEntry, Image, ImageFormat};
13382
13383        let input_view = InputView::build(cx, |state| state);
13384        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13385        let input = input_view.input;
13386
13387        cx.update(|window, cx| {
13388            input.update(cx, |state, cx| {
13389                state.set_value("hello world", window, cx);
13390                state.select_all(window, cx);
13391                cx.write_to_clipboard(ClipboardItem {
13392                    entries: vec![ClipboardEntry::Image(Image::from_bytes(
13393                        ImageFormat::Png,
13394                        vec![0x89, b'P', b'N', b'G'],
13395                    ))],
13396                });
13397
13398                // An image-only clipboard must not replace the selection
13399                // with nothing.
13400                state.paste(&Paste, window, cx);
13401                assert_eq!(state.value(), "hello world");
13402                assert_eq!(state.selected_range(), 0..11);
13403            });
13404        });
13405    }
13406
13407    #[gpui::test]
13408    fn test_paste_target_tracks_edits_and_selections(cx: &mut TestAppContext) {
13409        let view = multi_line(cx);
13410        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13411        let input = view.input;
13412
13413        setup_cursors(&mut cx, &input, "ab|c");
13414        let target = input.read_with(&cx, |state, _| state.paste_target());
13415        // Nothing happened: a paste asked for then still applies.
13416        assert_eq!(
13417            input.read_with(&cx, |state, _| state.paste_target()),
13418            target
13419        );
13420
13421        // Moving the caret changes where the paste would go.
13422        cx.update(|_, cx| {
13423            input.update(cx, |state, cx| {
13424                let id = state.selections.generate_id();
13425                state
13426                    .selections
13427                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13428                cx.notify();
13429            });
13430        });
13431        let moved = input.read_with(&cx, |state, _| state.paste_target());
13432        assert_ne!(moved, target);
13433
13434        // Editing the text changes it too, even with the caret put back.
13435        cx.update(|window, cx| {
13436            input.update(cx, |state, cx| {
13437                state.replace_text_in_range_silent(None, "x", window, cx);
13438                let id = state.selections.generate_id();
13439                state
13440                    .selections
13441                    .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13442            });
13443        });
13444        assert_ne!(input.read_with(&cx, |state, _| state.paste_target()), moved);
13445    }
13446
13447    #[gpui::test]
13448    fn character_index_for_point_finds_each_letter_where_it_is_drawn(cx: &mut TestAppContext) {
13449        // With a gutter and without, on the first line and on the lines after it.
13450        for line_number in [true, false] {
13451            let input_view = InputView::build_editor(cx, move |state| {
13452                state
13453                    .line_number(line_number)
13454                    .default_value("Teh quick\nbrown fox\njumps")
13455            });
13456            let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13457            visual.update(|window, cx| window.draw(cx).clear(cx));
13458
13459            visual.update(|window, cx| {
13460                input_view.input.update(cx, |state, cx| {
13461                    let bounds = state.text_bounds().unwrap();
13462                    for index in [0, 5, 8, 10, 14, 18, 20, 24] {
13463                        let middle = state
13464                            .bounds_for_range(index..index + 1, bounds, window, cx)
13465                            .unwrap()
13466                            .center();
13467                        assert_eq!(
13468                            state.character_index_for_point(middle, window, cx),
13469                            Some(index),
13470                            "line numbers: {line_number}"
13471                        );
13472                    }
13473                });
13474            });
13475        }
13476    }
13477
13478    #[gpui::test]
13479    fn test_ime_candidate_bounds_fallback_before_repaint(cx: &mut TestAppContext) {
13480        let input_view = InputView::build_textarea(cx, |state| {
13481            state.default_value("这是一段已经输入的中文文字")
13482        });
13483        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13484        visual.update(|window, cx| window.draw(cx).clear(cx));
13485
13486        visual.update(|window, cx| {
13487            input_view.input.update(cx, |state, cx| {
13488                state.focus(window, cx);
13489                let len = state.text.len();
13490                state.set_cursor_to(len);
13491            });
13492        });
13493        visual.update(|window, cx| window.draw(cx).clear(cx));
13494
13495        visual.update(|window, cx| {
13496            input_view.input.update(cx, |state, cx| {
13497                let bounds = state.text_bounds().unwrap_or_default();
13498                let before = state.selected_text_range(false, window, cx).unwrap().range;
13499                let previous = state
13500                    .bounds_for_range(before.end..before.end, bounds, window, cx)
13501                    .unwrap();
13502
13503                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
13504
13505                let after = state.selected_text_range(false, window, cx).unwrap().range;
13506                let pending = state
13507                    .bounds_for_range(after.end..after.end, bounds, window, cx)
13508                    .unwrap();
13509
13510                assert!(
13511                    (pending.origin.x - previous.origin.x).abs() < px(40.0),
13512                    "pending origin.x {:?} must remain close to previous origin.x {:?}",
13513                    pending.origin.x,
13514                    previous.origin.x
13515                );
13516
13517                let range_bounds = state
13518                    .bounds_for_range(before.end..after.end, bounds, window, cx)
13519                    .unwrap();
13520                assert!(
13521                    (range_bounds.origin.x - previous.origin.x).abs() < px(40.0),
13522                    "range_bounds origin.x {:?} must remain close to previous origin.x {:?}",
13523                    range_bounds.origin.x,
13524                    previous.origin.x
13525                );
13526                assert!(range_bounds.size.width >= px(0.0));
13527            });
13528        });
13529    }
13530
13531    #[gpui::test]
13532    fn test_ime_candidate_bounds_multiline_line_end(cx: &mut TestAppContext) {
13533        let input_view =
13534            InputView::build_textarea(cx, |state| state.default_value("First line\nSecond line"));
13535        let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13536        visual.update(|window, cx| window.draw(cx).clear(cx));
13537
13538        visual.update(|window, cx| {
13539            input_view.input.update(cx, |state, cx| {
13540                state.focus(window, cx);
13541                // Position at end of first line ("First line".len() == 10)
13542                state.set_cursor_to(10);
13543            });
13544        });
13545        visual.update(|window, cx| window.draw(cx).clear(cx));
13546
13547        visual.update(|window, cx| {
13548            input_view.input.update(cx, |state, cx| {
13549                let bounds = state.text_bounds().unwrap_or_default();
13550                let candidate_bounds = state.bounds_for_range(10..10, bounds, window, cx).unwrap();
13551
13552                // Candidate bounds for end of line 0 must be positioned at the end of line 0,
13553                // and must not jump to the start of the next line (column 0).
13554                let line_number_width = state
13555                    .last_layout
13556                    .as_ref()
13557                    .map(|l| l.line_number_width)
13558                    .unwrap_or_default();
13559                assert!(
13560                    candidate_bounds.origin.x > bounds.origin.x + line_number_width,
13561                    "candidate bounds at line end must be past the line start, got {:?}",
13562                    candidate_bounds.origin.x
13563                );
13564
13565                let (line_idx, sub_line, pos) = state.line_and_position_for_offset(10);
13566                assert_eq!(line_idx, 0);
13567                assert_eq!(sub_line, 0);
13568                assert!(pos.is_some());
13569                assert!(pos.unwrap().x > line_number_width);
13570            });
13571        });
13572    }
13573}
13574
13575/// Methods that only a single-line input offers.
13576impl InputBaseState<crate::input::InputMode> {
13577    /// Create a single-line text input state.
13578    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13579        Self::new_in_mode(window, cx)
13580    }
13581
13582    /// Set a custom step function of the [`super::NumberInput`].
13583    ///
13584    /// The `f` receives the current value and the [`StepAction`], and returns
13585    /// the step to apply, so the step can vary with the value.
13586    ///
13587    /// # Example
13588    ///
13589    /// ```ignore
13590    /// // At the boundary 1.0 the step is 0.1 going down and 0.5 going up.
13591    /// InputState::new(window, cx).step_by(|value, action, _cx| match action {
13592    ///     StepAction::Increment => if value < 1.0 { 0.1 } else { 0.5 },
13593    ///     StepAction::Decrement => if value <= 1.0 { 0.1 } else { 0.5 },
13594    /// })
13595    /// ```
13596    pub fn step_by(mut self, f: impl Fn(f64, StepAction, &mut App) -> f64 + 'static) -> Self {
13597        self.number_step = Some(NumberStep::by_value(f));
13598        self
13599    }
13600
13601    /// Set with password masked state.
13602    pub fn masked(mut self, masked: bool) -> Self {
13603        self.masked = masked;
13604        self
13605    }
13606
13607    /// Set the password masked state of the input field.
13608    pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
13609        self.masked = masked;
13610        cx.notify();
13611    }
13612
13613    /// Set the regular expression pattern of the input field.
13614    pub fn pattern(mut self, pattern: regex::Regex) -> Self {
13615        self.pattern = Some(pattern);
13616        self
13617    }
13618
13619    /// Set the regular expression pattern of the input field with reference.
13620    pub fn set_pattern(
13621        &mut self,
13622        pattern: regex::Regex,
13623        _window: &mut Window,
13624        _cx: &mut Context<Self>,
13625    ) {
13626        self.pattern = Some(pattern);
13627    }
13628
13629    /// Set the validation function of the input field.
13630    pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
13631        self.validate = Some(Box::new(f));
13632        self
13633    }
13634
13635    pub fn set_validator(
13636        &mut self,
13637        validate: impl Fn(&str, &mut App) -> bool + 'static,
13638        _cx: &mut Context<Self>,
13639    ) {
13640        self.validate = Some(Box::new(validate));
13641    }
13642
13643    /// Set the step value of the [`super::NumberInput`] for increment/decrement.
13644    ///
13645    /// If any of `step`, `min`, `max` is set, the [`super::NumberInput`] will
13646    /// update the value internally (step by `step`, default 1, clamp to the
13647    /// `min`/`max` range and emit [`InputEvent::Change`]) instead of emitting
13648    /// [`super::NumberInputEvent::Step`].
13649    ///
13650    /// See also [`Self::step_by`] to calculate the step value
13651    /// based on the current value.
13652    pub fn step(mut self, step: impl Into<NumberStep>) -> Self {
13653        self.number_step = Some(step.into());
13654        self
13655    }
13656
13657    /// Set the minimum value of the [`super::NumberInput`].
13658    ///
13659    /// The value will be clamped to the minimum value on stepping and on
13660    /// blur (only if the clamped value passes the `pattern`/`validate` check).
13661    /// See also [`Self::step`].
13662    pub fn min(mut self, min: f64) -> Self {
13663        self.number_min = Some(min);
13664        self
13665    }
13666
13667    /// Set the maximum value of the [`super::NumberInput`].
13668    ///
13669    /// The value will be clamped to the maximum value on stepping and on
13670    /// blur (only if the clamped value passes the `pattern`/`validate` check).
13671    /// See also [`Self::step`].
13672    pub fn max(mut self, max: f64) -> Self {
13673        self.number_max = Some(max);
13674        self
13675    }
13676
13677    /// Update the step value after construction, `None` to fall back to
13678    /// emitting [`super::NumberInputEvent::Step`] (if `min`, `max` are unset).
13679    ///
13680    /// See [`Self::step`] and [`Self::step_by`].
13681    pub fn set_step(
13682        &mut self,
13683        step: impl Into<Option<NumberStep>>,
13684        _: &mut Window,
13685        _: &mut Context<Self>,
13686    ) {
13687        self.number_step = step.into();
13688    }
13689
13690    /// Update the minimum value after construction. See [`Self::min`].
13691    pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13692        self.number_min = min;
13693    }
13694
13695    /// Update the maximum value after construction. See [`Self::max`].
13696    pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13697        self.number_max = max;
13698    }
13699
13700    /// Set true to show spinner at the input right.
13701    pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
13702        self.loading = loading;
13703        cx.notify();
13704    }
13705}
13706
13707/// Methods shared by the two multi-line modes, and reachable on neither a
13708/// single-line input nor anything else.
13709impl<M: crate::input::MultiLineMode> InputBaseState<M> {
13710    /// Set whether text taller than the input stretches past its top and
13711    /// bottom and springs back when precise trackpad or Magic Mouse scrolling
13712    /// or its momentum runs into an end. Ordinary line-wheel scrolling does
13713    /// not bounce. The default follows
13714    /// [`crate::ScrollBounce::enabled_by_default`]: on on iOS, Android and
13715    /// macOS, off elsewhere. Under reduced motion the text stops at its ends
13716    /// without stretching.
13717    pub fn scroll_bounce(mut self, scroll_bounce: bool) -> Self {
13718        self.scroll_bounce = scroll_bounce;
13719        self
13720    }
13721
13722    /// Update whether the text stretches past its ends, see
13723    /// [`InputBaseState::scroll_bounce`]. Turning it off drops a stretch in
13724    /// progress.
13725    pub fn set_scroll_bounce(&mut self, scroll_bounce: bool, cx: &mut Context<Self>) {
13726        if self.scroll_bounce != scroll_bounce {
13727            self.scroll_bounce = scroll_bounce;
13728            self.overscroll.reset();
13729            cx.notify();
13730        }
13731    }
13732
13733    /// Whether the built-in search panel and its shortcut are enabled. Off by
13734    /// default, on for the code editor.
13735    ///
13736    /// This only concerns the panel. An input that is not searchable still
13737    /// answers [`InputBaseState::set_search_query`] and the other search
13738    /// methods, and lets `Ctrl-F` / `Cmd-F` bubble up to its ancestors, so an
13739    /// application can put its own search UI on top of the same engine.
13740    pub fn searchable(mut self, searchable: bool) -> Self {
13741        self.searchable = searchable;
13742        self
13743    }
13744
13745    /// See [`InputBaseState::searchable`].
13746    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
13747        self.searchable = searchable;
13748        cx.notify();
13749    }
13750
13751    /// The placement of the scrollbars, default is [`ScrollbarPlacement::BottomRight`].
13752    ///
13753    /// On the left, the vertical scrollbar sits on the input's left edge, over
13754    /// the line numbers. At the top, the horizontal scrollbar overlays the
13755    /// first line, as at the bottom it overlays the last.
13756    pub fn scrollbar_placement(mut self, placement: ScrollbarPlacement) -> Self {
13757        self.scrollbar_placement = placement;
13758        self
13759    }
13760
13761    /// See [`InputBaseState::scrollbar_placement`].
13762    pub fn set_scrollbar_placement(
13763        &mut self,
13764        placement: ScrollbarPlacement,
13765        cx: &mut Context<Self>,
13766    ) {
13767        self.scrollbar_placement = placement;
13768        cx.notify();
13769    }
13770
13771    /// Set the soft wrap mode, default is true.
13772    #[doc(hidden)]
13773    pub fn soft_wrap(mut self, wrap: bool) -> Self {
13774        self.soft_wrap = wrap;
13775        self
13776    }
13777
13778    /// Update the soft wrap mode, default is true.
13779    pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
13780        self.soft_wrap = wrap;
13781        if wrap {
13782            let wrap_width = self
13783                .last_layout
13784                .as_ref()
13785                .and_then(|b| b.wrap_width)
13786                .unwrap_or(self.input_bounds.size.width);
13787
13788            self.display_map.on_layout_changed(Some(wrap_width), cx);
13789
13790            // Reset scroll to left 0
13791            let mut offset = self.scroll_handle.offset();
13792            offset.x = px(0.);
13793            self.scroll_handle.set_offset(offset);
13794        } else {
13795            self.display_map.on_layout_changed(None, cx);
13796        }
13797        cx.notify();
13798    }
13799
13800    /// Set how soft-wrapped continuation lines are indented, default is [`WrappingIndent::Same`]
13801    #[doc(hidden)]
13802    pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
13803        self.wrapping_indent = wrapping_indent;
13804        self
13805    }
13806
13807    /// Update how soft-wrapped continuation lines are indented.
13808    pub fn set_wrapping_indent(
13809        &mut self,
13810        wrapping_indent: WrappingIndent,
13811        _: &mut Window,
13812        cx: &mut Context<Self>,
13813    ) {
13814        self.wrapping_indent = wrapping_indent;
13815        self.display_map.set_wrapping_indent(wrapping_indent, cx);
13816        cx.notify();
13817    }
13818}
13819
13820/// Methods that only ordinary multi-line text offers.
13821impl InputBaseState<crate::input::TextareaMode> {
13822    /// Create a multi-line text state.
13823    ///
13824    /// Being multi-line is carried by the mode, not by the layout, so the
13825    /// default plain-text layout needs no adjustment here.
13826    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13827        Self::new_in_mode(window, cx)
13828    }
13829
13830    pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
13831        self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
13832        self.mode.update_auto_grow(&self.display_map);
13833        cx.notify();
13834    }
13835
13836    /// Set the number of rows for the multi-line Textarea.
13837    ///
13838    /// This is only used when `multi_line` is set to true. The input is at least
13839    /// this many lines tall.
13840    ///
13841    /// default: 1
13842    #[doc(hidden)]
13843    pub fn rows(mut self, rows: usize) -> Self {
13844        match &mut self.mode {
13845            LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
13846                *r = rows
13847            }
13848            LayoutMode::AutoGrow {
13849                max_rows: max_r,
13850                rows: r,
13851                ..
13852            } => {
13853                *r = rows;
13854                *max_r = rows;
13855            }
13856        }
13857        self
13858    }
13859
13860    pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
13861        match &mut self.mode {
13862            LayoutMode::PlainText { rows: value, .. }
13863            | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
13864            LayoutMode::AutoGrow {
13865                rows: value,
13866                max_rows,
13867                ..
13868            } => {
13869                *value = rows;
13870                *max_rows = rows;
13871            }
13872        }
13873        cx.notify();
13874    }
13875
13876    /// Grow with the content from `min_rows` through `max_rows`.
13877    pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
13878        self.mode = LayoutMode::auto_grow(min_rows, max_rows);
13879        self
13880    }
13881}
13882
13883/// Methods that only a source-code editor offers.
13884impl InputBaseState<crate::input::EditorMode> {
13885    /// Create a source-code editor state.
13886    ///
13887    /// Default options: line numbers on, tab size 2 with soft tabs, indent
13888    /// guides on, multi-line, and search enabled. Set the language for syntax
13889    /// highlighting with [`Self::language`]; without one the text is shown
13890    /// unhighlighted.
13891    ///
13892    /// The editor aims at simple code editing or display, not at being a
13893    /// full-featured code editor. It offers syntax highlighting, auto indent,
13894    /// line numbers, and handles large text up to about 50K lines.
13895    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13896        let mut state = Self::new_in_mode(window, cx);
13897        state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
13898        state.searchable = true;
13899        state
13900    }
13901
13902    /// Set the language to highlight, e.g. `"rust"`.
13903    ///
13904    /// See [`Self::set_highlighter`] to change it after construction.
13905    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
13906        if let LayoutMode::CodeEditor {
13907            language: l,
13908            highlighter,
13909            ..
13910        } = &mut self.mode
13911        {
13912            l.set_name(language.into());
13913            *highlighter.borrow_mut() = None;
13914        }
13915        self
13916    }
13917
13918    /// The current language name, e.g. `"rust"`.
13919    pub fn language_name(&self) -> SharedString {
13920        match &self.mode {
13921            LayoutMode::CodeEditor { language, .. } => language.name(),
13922            _ => SharedString::default(),
13923        }
13924    }
13925
13926    /// Set enable/disable code folding.
13927    ///
13928    /// Default: true
13929    #[doc(hidden)]
13930    pub fn folding(mut self, folding: bool) -> Self {
13931        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13932            *f = folding;
13933        }
13934        self
13935    }
13936
13937    /// Set code folding at runtime.
13938    ///
13939    /// When disabling, all existing folds are cleared.
13940    pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
13941        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
13942            *f = folding;
13943        }
13944        if !folding {
13945            self.display_map.clear_folds();
13946        }
13947        cx.notify();
13948    }
13949
13950    /// Fold or unfold the fold candidate that starts at `start_line`
13951    /// (a 0-based buffer line). Returns false when no candidate starts there
13952    /// or folding is disabled.
13953    pub fn set_folded(&mut self, start_line: usize, folded: bool, cx: &mut Context<Self>) -> bool {
13954        if !self.mode.is_folding() || !self.display_map.is_fold_candidate(start_line) {
13955            return false;
13956        }
13957        self.display_map.set_folded(start_line, folded);
13958        cx.notify();
13959        true
13960    }
13961
13962    /// Fold every fold candidate.
13963    pub fn fold_all(&mut self, cx: &mut Context<Self>) {
13964        if !self.mode.is_folding() {
13965            return;
13966        }
13967        let lines: Vec<usize> = self
13968            .display_map
13969            .fold_candidates()
13970            .iter()
13971            .map(|c| c.start_line)
13972            .collect();
13973        self.display_map.set_folded_lines(lines);
13974        cx.notify();
13975    }
13976
13977    /// Unfold every folded range. Fold candidates are kept.
13978    pub fn unfold_all(&mut self, cx: &mut Context<Self>) {
13979        if !self.mode.is_folding() {
13980            return;
13981        }
13982        self.display_map.clear_folds();
13983        cx.notify();
13984    }
13985
13986    /// Fold the candidates at one nesting level and unfold all others, as
13987    /// Zed's `editor::FoldAtLevel`. Level 1 is a candidate that no other
13988    /// candidate contains; level 2 is one inside a level-1 candidate, and so on.
13989    pub fn fold_at_level(&mut self, level: usize, cx: &mut Context<Self>) {
13990        if !self.mode.is_folding() {
13991            return;
13992        }
13993        // One pass: the candidates are sorted by start line with unique starts,
13994        // so the stack holds the end lines of the candidates that contain the
13995        // current one, and its length is the depth.
13996        let mut open: Vec<usize> = Vec::new();
13997        let mut lines = Vec::new();
13998        for c in self.display_map.fold_candidates() {
13999            while open.last().is_some_and(|&end| end < c.end_line) {
14000                open.pop();
14001            }
14002            if open.len() + 1 == level {
14003                lines.push(c.start_line);
14004            }
14005            open.push(c.end_line);
14006        }
14007        self.display_map.set_folded_lines(lines);
14008        cx.notify();
14009    }
14010
14011    /// The fold candidates, as reported by the highlighter.
14012    pub fn fold_candidates(&self) -> &[crate::input::FoldRange] {
14013        self.display_map.fold_candidates()
14014    }
14015
14016    /// Unfold any folded ranges that hide the given position.
14017    ///
14018    /// Use this to reveal a position before acting on it (e.g. before
14019    /// [`Self::set_cursor_position`], which stops at a fold boundary),
14020    /// without touching folds elsewhere in the buffer. Fold candidates are
14021    /// kept, so the opened ranges can be folded again from the gutter.
14022    ///
14023    /// A fold keeps its own first and last line visible, so a position on
14024    /// either of them opens nothing. Nested folds all open, since opening
14025    /// only the outermost would leave the position hidden.
14026    ///
14027    /// Returns whether any fold was opened.
14028    pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
14029        let offset = self.text.position_to_offset(&position.into());
14030        let line = self.text.offset_to_point(offset).row;
14031        // A fold hides start_line + 1 ..= end_line - 1, so a line is hidden
14032        // exactly when some folded range strictly contains it.
14033        let covering: Vec<usize> = self
14034            .display_map
14035            .folded_ranges()
14036            .iter()
14037            .filter(|fold| line > fold.start_line && line < fold.end_line)
14038            .map(|fold| fold.start_line)
14039            .collect();
14040        if covering.is_empty() {
14041            return false;
14042        }
14043
14044        for start_line in covering {
14045            self.display_map.set_folded(start_line, false);
14046        }
14047        cx.notify();
14048        true
14049    }
14050
14051    /// Horizontal offset from the content area's left edge to unscrolled source text.
14052    ///
14053    /// Includes the laid-out gap, line numbers, folding controls, and gutter
14054    /// decorations. Excludes input-frame padding, horizontal scrolling, and
14055    /// text alignment. For left-aligned text, add this to the content area's
14056    /// origin and the horizontal scroll offset to recover the text origin.
14057    ///
14058    /// Returns `None` before the first layout. Like [`Self::range_to_bounds`],
14059    /// this describes the most recent layout; render again after changing
14060    /// gutter settings or typography before using it to align a static view.
14061    pub fn text_origin_offset(&self) -> Option<Pixels> {
14062        self.last_layout
14063            .as_ref()
14064            .map(|layout| layout.line_number_width)
14065    }
14066
14067    /// Set enable/disable line number.
14068    #[doc(hidden)]
14069    pub fn line_number(mut self, line_number: bool) -> Self {
14070        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
14071            *l = line_number;
14072        }
14073        self
14074    }
14075
14076    /// Set line number.
14077    pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
14078        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
14079            if *l == line_number {
14080                return;
14081            }
14082            *l = line_number;
14083        }
14084        cx.notify();
14085    }
14086
14087    /// Set enable/disable showing the active line only while focused.
14088    ///
14089    /// Default: false
14090    #[doc(hidden)]
14091    pub fn active_line_only_when_focused(mut self, active_line_only_when_focused: bool) -> Self {
14092        if let LayoutMode::CodeEditor {
14093            active_line_only_when_focused: a,
14094            ..
14095        } = &mut self.mode
14096        {
14097            *a = active_line_only_when_focused;
14098        }
14099        self
14100    }
14101
14102    /// Set showing the active line only while focused.
14103    pub fn set_active_line_only_when_focused(
14104        &mut self,
14105        active_line_only_when_focused: bool,
14106        _: &mut Window,
14107        cx: &mut Context<Self>,
14108    ) {
14109        if let LayoutMode::CodeEditor {
14110            active_line_only_when_focused: a,
14111            ..
14112        } = &mut self.mode
14113        {
14114            if *a == active_line_only_when_focused {
14115                return;
14116            }
14117            *a = active_line_only_when_focused;
14118        }
14119        cx.notify();
14120    }
14121
14122    /// Set enable/disable automatic closing brackets and quotes.
14123    ///
14124    /// When enabled, typing an opener from [`LanguageConfig::auto_closing_pairs`](crate::input::language_config::LanguageConfig::auto_closing_pairs) inserts the
14125    /// matching closer and places the cursor inside. Typing a closer that is
14126    /// already present just moves past it. Default: true
14127    #[doc(hidden)]
14128    pub fn auto_close(mut self, auto_close: bool) -> Self {
14129        self.mode.set_auto_close(auto_close);
14130        self
14131    }
14132
14133    /// Set automatic closing brackets and quotes at runtime.
14134    pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
14135        self.mode.set_auto_close(auto_close);
14136        cx.notify();
14137    }
14138
14139    /// Set enable/disable smart indent on Enter.
14140    ///
14141    /// When enabled, Enter uses structural brackets and
14142    /// [`LanguageConfig::indentation_rules`](crate::input::language_config::LanguageConfig::indentation_rules) to choose indentation.
14143    /// Default: true
14144    #[doc(hidden)]
14145    pub fn smart_indent(mut self, smart_indent: bool) -> Self {
14146        self.mode.set_smart_indent(smart_indent);
14147        self
14148    }
14149
14150    /// Set smart indent on Enter at runtime.
14151    pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
14152        self.mode.set_smart_indent(smart_indent);
14153        cx.notify();
14154    }
14155}