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, InteractiveElement as _, IntoElement, KeyBinding,
9    MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point,
10    Render, ScrollHandle, ScrollWheelEvent, SharedString, Styled as _, Subscription,
11    UTF16Selection, Window, actions, div, point, prelude::FluentBuilder as _, px,
12};
13use ropey::{Rope, RopeSlice};
14use serde::Deserialize;
15use std::borrow::Cow;
16use std::cell::Cell;
17use std::ops::Range;
18use std::rc::Rc;
19use sum_tree::Bias;
20use unicode_segmentation::*;
21
22use super::{
23    DiagnosticSet, DisplayMap, InputContextMenuCapabilities, InputEditorStyle,
24    InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep, WrappingIndent,
25    blink_cursor::BlinkCursor,
26    change::Change,
27    cursor::{CursorSelection, Selections},
28    element::{EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, TextElement},
29    kind::InputModeKind,
30    mask_pattern::normalize_number_input,
31    mode::LayoutMode,
32    undo_manager::{EditIntent, UndoManager},
33};
34use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
35use crate::input::blink_cursor::CURSOR_WIDTH;
36use crate::input::movement::MoveDirection;
37use crate::input::{
38    InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout,
39};
40use crate::{AutoScroll, StepAction};
41
42/// Vertical clearance to retain when revealing a text position.
43pub(crate) enum ScrollPadding {
44    Minimal,
45    SurroundingLines,
46}
47
48#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
49#[action(namespace = input, no_json)]
50pub struct Enter {
51    /// Is confirm with secondary.
52    pub secondary: bool,
53    /// Whether the Shift modifier was held when Enter was pressed.
54    pub shift: bool,
55}
56
57impl Enter {
58    /// Returns true if `action` is a primary `Enter` action (`secondary: false`),
59    /// regardless of whether Shift was held.
60    pub fn is_primary(action: &dyn Action) -> bool {
61        action.partial_eq(&Enter {
62            secondary: false,
63            shift: false,
64        }) || action.partial_eq(&Enter {
65            secondary: false,
66            shift: true,
67        })
68    }
69}
70
71actions!(
72    input,
73    [
74        ActivateToken,
75        Backspace,
76        Delete,
77        DeleteToBeginningOfLine,
78        DeleteToEndOfLine,
79        DeleteToPreviousWordStart,
80        DeleteToNextWordEnd,
81        Indent,
82        Outdent,
83        IndentInline,
84        OutdentInline,
85        MoveUp,
86        MoveDown,
87        MoveLeft,
88        MoveRight,
89        MoveHome,
90        MoveEnd,
91        MovePageUp,
92        MovePageDown,
93        AddCursorAbove,
94        AddCursorBelow,
95        SelectAll,
96        SelectToStartOfLine,
97        SelectToEndOfLine,
98        SelectToStart,
99        SelectToEnd,
100        SelectToPreviousWordStart,
101        SelectToNextWordEnd,
102        ShowCharacterPalette,
103        Copy,
104        Cut,
105        Paste,
106        Undo,
107        Redo,
108        MoveToStartOfLine,
109        MoveToEndOfLine,
110        MoveToStart,
111        MoveToEnd,
112        MoveToPreviousWord,
113        MoveToNextWord,
114        Escape,
115        ToggleCodeActions,
116        Search,
117        Replace,
118        GoToDefinition,
119    ]
120);
121
122#[derive(Clone)]
123pub enum InputEvent {
124    Change,
125    PressEnter { secondary: bool, shift: bool },
126    Focus,
127    Blur,
128}
129
130pub(super) const CONTEXT: &str = "Input";
131
132pub(crate) fn init(cx: &mut App) {
133    cx.bind_keys([
134        KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
135        KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
136        #[cfg(target_os = "macos")]
137        KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
138        KeyBinding::new("delete", Delete, Some(CONTEXT)),
139        KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
140        #[cfg(target_os = "macos")]
141        KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
142        #[cfg(target_os = "macos")]
143        KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
144        #[cfg(target_os = "macos")]
145        KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
146        #[cfg(not(target_os = "macos"))]
147        KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
148        #[cfg(target_os = "macos")]
149        KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
150        #[cfg(not(target_os = "macos"))]
151        KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
152        KeyBinding::new(
153            "enter",
154            Enter {
155                secondary: false,
156                shift: false,
157            },
158            Some(CONTEXT),
159        ),
160        KeyBinding::new(
161            "shift-enter",
162            Enter {
163                secondary: false,
164                shift: true,
165            },
166            Some(CONTEXT),
167        ),
168        KeyBinding::new(
169            "secondary-enter",
170            Enter {
171                secondary: true,
172                shift: false,
173            },
174            Some(CONTEXT),
175        ),
176        KeyBinding::new("escape", Escape, Some(CONTEXT)),
177        KeyBinding::new("up", MoveUp, Some(CONTEXT)),
178        KeyBinding::new("down", MoveDown, Some(CONTEXT)),
179        KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
180        KeyBinding::new("right", MoveRight, Some(CONTEXT)),
181        KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
182        KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
183        KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
184        KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
185        #[cfg(target_os = "macos")]
186        KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
187        #[cfg(not(target_os = "macos"))]
188        KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
189        #[cfg(target_os = "macos")]
190        KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
191        #[cfg(not(target_os = "macos"))]
192        KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
193        KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
194        KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
195        KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
196        KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
197        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
198        KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
199        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
200        KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
201        // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them.
202        #[cfg(target_os = "macos")]
203        KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
204        #[cfg(target_os = "macos")]
205        KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
206        #[cfg(target_os = "windows")]
207        KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
208        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
209        KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
210        #[cfg(target_os = "windows")]
211        KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
212        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
213        KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
214        KeyBinding::new("home", MoveHome, Some(CONTEXT)),
215        KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
216        #[cfg(not(target_os = "macos"))]
217        KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
218        #[cfg(not(target_os = "macos"))]
219        KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
220        #[cfg(not(target_os = "macos"))]
221        KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
222        #[cfg(not(target_os = "macos"))]
223        KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
224        KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
225        KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
226        #[cfg(target_os = "macos")]
227        KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
228        #[cfg(target_os = "macos")]
229        KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
230        #[cfg(target_os = "macos")]
231        KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
232        #[cfg(target_os = "macos")]
233        KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
234        #[cfg(any(target_os = "macos", target_os = "linux"))]
235        KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
236        #[cfg(not(target_os = "macos"))]
237        KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
238        #[cfg(any(target_os = "macos", target_os = "linux"))]
239        KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
240        #[cfg(not(target_os = "macos"))]
241        KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
242        #[cfg(target_os = "macos")]
243        KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
244        #[cfg(target_os = "macos")]
245        KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
246        #[cfg(not(target_os = "macos"))]
247        KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
248        #[cfg(target_os = "macos")]
249        KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
250        #[cfg(not(target_os = "macos"))]
251        KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
252        #[cfg(target_os = "macos")]
253        KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
254        #[cfg(not(target_os = "macos"))]
255        KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
256        #[cfg(target_os = "macos")]
257        KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
258        #[cfg(not(target_os = "macos"))]
259        KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
260        #[cfg(target_os = "macos")]
261        KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
262        #[cfg(target_os = "macos")]
263        KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
264        #[cfg(target_os = "macos")]
265        KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
266        #[cfg(target_os = "macos")]
267        KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
268        #[cfg(target_os = "macos")]
269        KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
270        #[cfg(target_os = "macos")]
271        KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
272        #[cfg(target_os = "macos")]
273        KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
274        #[cfg(target_os = "macos")]
275        KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
276        #[cfg(target_os = "macos")]
277        KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
278        #[cfg(target_os = "macos")]
279        KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
280        #[cfg(not(target_os = "macos"))]
281        KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
282        #[cfg(not(target_os = "macos"))]
283        KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
284        #[cfg(target_os = "macos")]
285        KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
286        #[cfg(target_os = "macos")]
287        KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
288        #[cfg(not(target_os = "macos"))]
289        KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
290        #[cfg(not(target_os = "macos"))]
291        KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
292        #[cfg(target_os = "macos")]
293        KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
294        #[cfg(not(target_os = "macos"))]
295        KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
296        #[cfg(target_os = "macos")]
297        KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
298        #[cfg(not(target_os = "macos"))]
299        KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
300        #[cfg(target_os = "macos")]
301        KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
302        #[cfg(not(target_os = "macos"))]
303        KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
304    ]);
305}
306
307/// A mouse position resolved for a columnar (block) selection.
308///
309/// A position past the end of a short row has no glyph to land on, so `offset` clips to
310/// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they
311/// say which column the pointer really reached, which is what a block spanning rows of
312/// different lengths has to be measured in.
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
314pub(super) struct ColumnarPoint {
315    offset: usize,
316    columns_past_line_end: usize,
317}
318
319impl ColumnarPoint {
320    pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
321        Self {
322            offset,
323            columns_past_line_end,
324        }
325    }
326}
327
328/// The shared text-editing engine behind [`crate::input::InputState`],
329/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
330///
331/// `M` is the mode marker: it carries no data and only decides which methods
332/// exist, so an ordinary input cannot reach the editor's language features.
333///
334/// The three states are type aliases of this one, which is why this name is
335/// public: an alias is only as usable as the type behind it, so hiding this
336/// would leave `InputState` unable to do anything. Prefer naming the aliases
337/// — write `InputState`, not `InputBaseState<InputMode>`.
338pub struct InputBaseState<M: InputModeKind> {
339    /// State only this mode needs. See [`InputModeKind::Extras`].
340    pub(crate) extras: M::Extras,
341    pub(super) focus_handle: FocusHandle,
342    pub(super) mode: LayoutMode,
343    pub(super) text: Rope,
344    pub(super) display_map: DisplayMap,
345    pub(super) undo_manager: UndoManager,
346    pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
347    pub(super) pending_token: Option<super::InlineToken>,
348    pub(super) replaying_history: bool,
349    pub(super) validated_token_edit: bool,
350    pub(super) document_revision: u64,
351    pub(super) token_presentation: super::InlineTokenPresentation,
352    pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
353    /// The start offset of a pressed token, with the document revision and
354    /// pointer position at the press.
355    pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
356    pub(super) search_session: super::SearchSession,
357    /// Advances every time search is explicitly invoked. See
358    /// [`InputBaseState::search_activation_revision`].
359    pub(super) search_activation_revision: u64,
360    pub(super) searchable: bool,
361    pub(super) replaceable: bool,
362    pub(super) soft_wrap: bool,
363    pub(super) wrapping_indent: WrappingIndent,
364    pub(super) scroll_beyond_last_line: Option<usize>,
365    pub(super) cursor_surrounding_lines: Option<usize>,
366    pub(super) blink_cursor: Entity<BlinkCursor>,
367    pub(super) loading: bool,
368    /// The cursors and selections.
369    ///
370    /// Always contains at least one selection where index 0 is the active cursor.
371    pub(super) selections: Selections,
372    /// Range for save the selected word, use to keep word range when drag move.
373    pub(super) selected_word_range: Option<CursorSelection>,
374    /// The marked range is the temporary insert text on IME typing.
375    pub(super) ime_marked_range: Option<CursorSelection>,
376    pub(super) last_layout: Option<LastLayout>,
377    pub(super) last_cursor: Option<usize>,
378    /// The input container bounds
379    pub(super) input_bounds: Bounds<Pixels>,
380    /// The text bounds
381    pub(super) last_bounds: Option<Bounds<Pixels>>,
382    pub(super) last_selected_range: Option<CursorSelection>,
383    pub(super) selecting: bool,
384    /// Anchor point of an in-progress columnar (block) selection.
385    pub(super) column_select_start: Option<ColumnarPoint>,
386    /// The selection a long press made, with its handles and edit menu.
387    pub(super) touch_selection: super::touch::TouchSelection,
388    pub(crate) disabled: bool,
389    pub(crate) readonly: bool,
390    pub(crate) text_align: TextAlign,
391    pub(super) masked: bool,
392    pub(super) clean_on_escape: bool,
393    pub(super) submit_on_enter: bool,
394    pub(super) show_whitespaces: bool,
395    /// This flag tells the renderer to prefer the end of the current visual line.
396    pub(crate) cursor_line_end_affinity: bool,
397    pub(super) pattern: Option<regex::Regex>,
398    pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
399    /// The step strategy for [`super::NumberInput`] to increment/decrement.
400    /// See [`Self::step`] and [`Self::step_by`].
401    pub(crate) number_step: Option<NumberStep>,
402    /// The minimum value for [`super::NumberInput`]. See [`Self::min`].
403    pub(crate) number_min: Option<f64>,
404    /// The maximum value for [`super::NumberInput`]. See [`Self::max`].
405    pub(crate) number_max: Option<f64>,
406    pub(crate) scroll_handle: ScrollHandle,
407    /// The deferred scroll offset to apply on next layout.
408    pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
409    /// The size of the scrollable content.
410    pub(crate) scroll_size: gpui::Size<Pixels>,
411    pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
412    /// The unwrapped width of the longest line and what it was measured for.
413    pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
414    pub(super) editor_paddings: Edges<Pixels>,
415    /// The style this state paints with: what was projected onto it, with
416    /// every colour left unset resolved from the palette that is current. It
417    /// is rebuilt at the top of every render, which is what keeps it current
418    /// when the palette changes after the state was built.
419    pub(super) editor_style: InputEditorStyle,
420    /// What a consumer projected, kept verbatim so that resolution never
421    /// consumes its own output: resolving in place would fill the unset
422    /// colours once and then never see them as unset again, which is the same
423    /// freeze in a different place.
424    projected_editor_style: InputEditorStyle,
425
426    /// The mask pattern for formatting the input text
427    pub(crate) mask_pattern: MaskPattern,
428    /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`]
429    /// or [`Self::set_mask_pattern`]), to let [`super::NumberInput`] only apply
430    /// its default mask when the user has not made an explicit choice.
431    pub(super) mask_pattern_set: bool,
432    pub(super) placeholder: SharedString,
433
434    /// Diagnostic currently requested by pointer hover; applications render it.
435    pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
436
437    context_menu_handler: Option<
438        Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
439    >,
440    pending_context_menu: Option<(Point<Pixels>, usize)>,
441
442    /// Whether the context menu that shows on right-click is enabled.
443    ///
444    pub(super) enable_context_menu: bool,
445
446    /// A flag to indicate if we are currently inserting a completion item.
447    pub(super) completion_inserting: bool,
448    pub(super) overlay_action_handler: Option<
449        Rc<
450            dyn Fn(
451                super::InputOverlayKind,
452                Box<dyn Action>,
453                &mut Window,
454                &mut Context<InputBaseState<M>>,
455            ) -> bool,
456        >,
457    >,
458
459    /// A flag to indicate if we have a pending update to the text.
460    ///
461    /// If true, will call some update (for example LSP, Syntax Highlight) before render.
462    _pending_update: bool,
463    /// A flag to indicate if we should ignore the next completion event.
464    pub(super) silent_replace_text: bool,
465    /// A flag to indicate if we should emit InputEvents.
466    pub(super) emit_events: bool,
467
468    _subscriptions: Vec<Subscription>,
469
470    pub(super) auto_scroll: AutoScroll,
471}
472
473/// Read-only styling data exposed to presentation facades.
474///
475/// The fields are private and read through the methods below, so that a new
476/// one can be added without breaking the facades.
477#[derive(Clone)]
478pub struct InputPresentation {
479    focus_handle: FocusHandle,
480    disabled: bool,
481    readonly: bool,
482    loading: bool,
483    masked: bool,
484    multi_line: bool,
485    code_editor: bool,
486    text_align: TextAlign,
487    placeholder: SharedString,
488    mask_placeholder: Option<String>,
489}
490
491impl InputPresentation {
492    pub fn focus_handle(&self) -> &FocusHandle {
493        &self.focus_handle
494    }
495
496    pub fn is_disabled(&self) -> bool {
497        self.disabled
498    }
499
500    pub fn is_readonly(&self) -> bool {
501        self.readonly
502    }
503
504    /// Returns true if the user is allowed to change the text.
505    ///
506    /// See also: [`InputBaseState::is_editable`].
507    pub fn is_editable(&self) -> bool {
508        !self.disabled && !self.readonly
509    }
510
511    pub fn is_loading(&self) -> bool {
512        self.loading
513    }
514
515    pub fn is_masked(&self) -> bool {
516        self.masked
517    }
518
519    pub fn is_multi_line(&self) -> bool {
520        self.multi_line
521    }
522
523    pub fn is_code_editor(&self) -> bool {
524        self.code_editor
525    }
526
527    pub fn text_align(&self) -> TextAlign {
528        self.text_align
529    }
530
531    pub fn placeholder(&self) -> &SharedString {
532        &self.placeholder
533    }
534
535    /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
536    pub fn mask_placeholder(&self) -> Option<&str> {
537        self.mask_placeholder.as_deref()
538    }
539}
540
541impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
542
543impl<M: InputModeKind> InputBaseState<M> {
544    #[doc(hidden)]
545    pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
546        let layout = self.last_layout.as_ref()?;
547        Some((layout.cursor_bounds?, layout.line_height))
548    }
549
550    pub fn input_bounds(&self) -> Bounds<Pixels> {
551        self.input_bounds
552    }
553
554    pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
555        self.last_bounds
556    }
557
558    pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
559        self.diagnostic_popover.clone()
560    }
561
562    pub fn presentation(&self) -> InputPresentation {
563        InputPresentation {
564            focus_handle: self.focus_handle.clone(),
565            disabled: self.disabled,
566            readonly: self.readonly,
567            loading: self.loading,
568            masked: self.masked,
569            multi_line: self.is_multi_line(),
570            code_editor: self.is_code_editor(),
571            text_align: self.text_align,
572            placeholder: self.placeholder.clone(),
573            mask_placeholder: self.mask_pattern.placeholder(),
574        }
575    }
576
577    /// Whether this input spans more than one line.
578    ///
579    /// Answered by the mode marker, which is fixed when the state is built.
580    /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
581    #[inline]
582    /// Whether this input paints scrollbars.
583    ///
584    /// Only a multi-line input can scroll: a single-line input keeps its
585    /// caret in view by moving its own offset, and never has a viewport a
586    /// user could drag. Adding the editor scrollbar to every input put a
587    /// thumb inside every text field, which is a control the field does not
588    /// have.
589    pub(crate) fn shows_scrollbar(&self) -> bool {
590        self.is_multi_line()
591    }
592
593    pub fn is_multi_line(&self) -> bool {
594        M::MULTI_LINE
595    }
596
597    /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
598    #[inline]
599    pub fn is_single_line(&self) -> bool {
600        !M::MULTI_LINE
601    }
602
603    /// Whether this input is a source-code editor.
604    #[inline]
605    pub fn is_code_editor(&self) -> bool {
606        M::CODE_EDITOR
607    }
608
609    /// Whether the user is allowed to copy the selection out.
610    ///
611    /// A masked input keeps its value out of the clipboard.
612    pub fn is_copyable(&self) -> bool {
613        self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
614    }
615
616    pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
617        let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
618        InputContextMenuCapabilities::new()
619            .disabled(self.disabled)
620            .readonly(self.readonly)
621            .code_editor(self.is_code_editor())
622            .selection(!self.active_selection().is_empty())
623            .masked(self.masked)
624            .go_to_definition(go_to_definition)
625            .code_actions(code_actions)
626    }
627
628    pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
629        if !self.is_single_line() || self.text_align == text_align {
630            return;
631        }
632
633        self.text_align = text_align;
634        cx.notify();
635    }
636
637    /// Flip the password mask.
638    ///
639    /// Setting the mask is a single-line method, but flipping it stays here:
640    /// the reveal button is rendered from the generic path, and it can only be
641    /// switched on through [`crate::input::InputState`] anyway.
642    pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
643        self.masked = !self.masked;
644        cx.notify();
645    }
646
647    pub fn on_context_menu(
648        &mut self,
649        handler: Rc<
650            dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
651        >,
652    ) {
653        self.context_menu_handler = Some(handler);
654    }
655
656    /// Build the engine. Each mode's own `new` sets its layout on top of this.
657    fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
658        let focus_handle = cx.focus_handle().tab_stop(true);
659        let blink_cursor = cx.new(|_| BlinkCursor::new());
660        let undo_manager = UndoManager::new();
661
662        let _subscriptions = vec![
663            // Key bindings can consume events before on_key_down. Observe input
664            // before action dispatch so every keystroke resets the blink delay.
665            cx.intercept_keystrokes({
666                let focus_handle = focus_handle.clone();
667                let blink_cursor = blink_cursor.downgrade();
668                move |_, window, cx| {
669                    if focus_handle.is_focused(window) {
670                        _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
671                    }
672                }
673            }),
674            // Observe the blink cursor to repaint the view when it changes.
675            cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
676            // Blink the cursor when the window is active, pause when it's not.
677            cx.observe_window_activation(window, |input, window, cx| {
678                if window.is_window_active() {
679                    let focus_handle = input.focus_handle.clone();
680                    if focus_handle.is_focused(window) {
681                        input.blink_cursor.update(cx, |blink_cursor, cx| {
682                            blink_cursor.start(cx);
683                        });
684                    }
685                }
686            }),
687            cx.on_focus(&focus_handle, window, Self::on_focus),
688            cx.on_blur(&focus_handle, window, Self::on_blur),
689        ];
690
691        let text_style = window.text_style();
692
693        Self {
694            extras: M::Extras::default(),
695            focus_handle: focus_handle.clone(),
696            text: "".into(),
697            display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
698            search_session: super::SearchSession::default(),
699            search_activation_revision: 0,
700            searchable: false,
701            replaceable: true,
702            soft_wrap: true,
703            wrapping_indent: WrappingIndent::default(),
704            scroll_beyond_last_line: None,
705            cursor_surrounding_lines: None,
706            blink_cursor,
707            undo_manager,
708            inline_tokens: None,
709            pending_token: None,
710            replaying_history: false,
711            validated_token_edit: false,
712            document_revision: 0,
713            token_presentation: Default::default(),
714            token_layout_cache: None,
715            pressed_token: None,
716            selections: Selections::default(),
717            selected_word_range: None,
718            ime_marked_range: None,
719            input_bounds: Bounds::default(),
720            selecting: false,
721            touch_selection: Default::default(),
722            disabled: false,
723            readonly: false,
724            text_align: TextAlign::Left,
725            masked: false,
726            clean_on_escape: false,
727            submit_on_enter: false,
728            show_whitespaces: false,
729            loading: false,
730            pattern: None,
731            validate: None,
732            number_step: Some(NumberStep::Fixed(1.)),
733            number_min: None,
734            number_max: None,
735            mode: LayoutMode::default(),
736            last_layout: None,
737            last_bounds: None,
738            last_selected_range: None,
739            column_select_start: None,
740            last_cursor: None,
741            scroll_handle: ScrollHandle::new(),
742            scroll_size: gpui::size(px(0.), px(0.)),
743            editor_scrollbar_snapshot: Cell::new(None),
744            longest_line_width: Cell::new(None),
745            editor_paddings: Edges::default(),
746            deferred_scroll_offset: None,
747            placeholder: SharedString::default(),
748            mask_pattern: MaskPattern::default(),
749            mask_pattern_set: false,
750            editor_style: InputEditorStyle::default(),
751            projected_editor_style: InputEditorStyle::default(),
752            diagnostic_popover: None,
753            context_menu_handler: None,
754            pending_context_menu: None,
755            enable_context_menu: true,
756            completion_inserting: false,
757            overlay_action_handler: None,
758            silent_replace_text: false,
759            emit_events: true,
760            _subscriptions,
761            _pending_update: false,
762            cursor_line_end_affinity: false,
763            auto_scroll: AutoScroll::default(),
764        }
765    }
766
767    /// Sets whether the context menu that shows on right-click is enabled.
768    ///
769    /// The context menu is enabled by default. Disabling it turns off the
770    /// right-click menu entirely, including a custom menu set on the element.
771    /// A custom menu already replaces the built-in one, so keep this enabled
772    /// to show only your own items.
773    pub fn context_menu(mut self, enable: bool) -> Self {
774        self.enable_context_menu = enable;
775        self
776    }
777
778    pub fn set_context_menu_enabled(&mut self, enabled: bool) {
779        self.enable_context_menu = enabled;
780    }
781
782    /// Set whether search UI allows replacement, default is true.
783    #[doc(hidden)]
784    pub fn replaceable(mut self, allow: bool) -> Self {
785        self.replaceable = allow;
786        self
787    }
788
789    /// Set placeholder
790    pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
791        self.placeholder = placeholder.into();
792        self
793    }
794
795    /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode.
796    pub fn set_highlighter(
797        &mut self,
798        new_language: impl Into<SharedString>,
799        cx: &mut Context<Self>,
800    ) {
801        match &mut self.mode {
802            LayoutMode::CodeEditor {
803                language,
804                highlighter,
805                ..
806            } => {
807                language.set_name(new_language.into());
808                *highlighter.borrow_mut() = None;
809            }
810            _ => {}
811        }
812        self.refresh(cx);
813    }
814
815    fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
816        match &mut self.mode {
817            LayoutMode::CodeEditor { highlighter, .. } => {
818                *highlighter.borrow_mut() = None;
819            }
820            _ => {}
821        }
822        cx.notify();
823    }
824
825    /// Install the parser/highlighter adapter used by code-editor mode.
826    pub fn set_highlighter_factory(
827        &mut self,
828        factory: InputHighlighterFactory,
829        cx: &mut Context<Self>,
830    ) {
831        self.mode.set_highlighter_factory(factory);
832        self._pending_update = true;
833        self.token_layout_cache = None;
834        cx.notify();
835    }
836
837    /// Install a default adapter without replacing an application-provided one.
838    pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
839        self.mode.ensure_highlighter_factory(factory);
840    }
841
842    pub fn set_editor_style(&mut self, style: InputEditorStyle) {
843        self.editor_style = style.clone();
844        self.projected_editor_style = style;
845    }
846
847    /// Set presentation padding for multi-line text and its scrollbar layout.
848    #[doc(hidden)]
849    pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
850        self.editor_paddings = paddings;
851    }
852
853    pub fn apply_highlighter_fold_candidates(
854        &mut self,
855        candidates: Vec<crate::input::FoldRange>,
856        cx: &mut Context<Self>,
857    ) {
858        if self.mode.is_folding() {
859            self.display_map.set_fold_candidates(candidates);
860        }
861        cx.notify();
862    }
863
864    #[inline]
865    pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
866        self.mode.diagnostics()
867    }
868
869    #[inline]
870    pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
871        self.mode.diagnostics_mut()
872    }
873
874    /// Set placeholder
875    pub fn set_placeholder(
876        &mut self,
877        placeholder: impl Into<SharedString>,
878        _: &mut Window,
879        cx: &mut Context<Self>,
880    ) {
881        self.placeholder = placeholder.into();
882        cx.notify();
883    }
884
885    /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
886    ///
887    /// Returns:
888    ///
889    /// - The index of the line (zero-based) containing the offset.
890    /// - The index of the sub-line (zero-based) within the line containing the offset.
891    /// - The position of the offset.
892    pub(super) fn line_and_position_for_offset(
893        &self,
894        offset: usize,
895    ) -> (usize, usize, Option<Point<Pixels>>) {
896        let Some(last_layout) = &self.last_layout else {
897            return (0, 0, None);
898        };
899        let line_height = last_layout.line_height;
900
901        let mut y_offset = last_layout.visible_top;
902        for (vi, line) in last_layout.lines.iter().enumerate() {
903            let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
904            let local_offset = offset.saturating_sub(prev_lines_offset);
905            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
906                let sub_line_index = (pos.y / line_height) as usize;
907                let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
908                return (vi, sub_line_index, Some(adjusted_pos));
909            }
910
911            y_offset += line.size(line_height).height;
912        }
913        (0, 0, None)
914    }
915
916    /// Set the value of the input field: plain text, or [`InputContent`] to
917    /// restore text together with its inline tokens. Editing history is
918    /// cleared and no [`InputEvent::Change`] is emitted.
919    ///
920    /// For single-line inputs the caret is placed at the end of the text while
921    /// the view is scrolled back to the start, so a long value shows its
922    /// beginning instead of its tail (matching HTML `<input>`). Multi-line
923    /// inputs reset the selection to `0..0`.
924    pub fn set_value(
925        &mut self,
926        value: impl Into<super::InputContent>,
927        window: &mut Window,
928        cx: &mut Context<Self>,
929    ) {
930        let content = value.into();
931        self.inline_tokens = None;
932        self.undo_manager.set_ignoring(true);
933        self.emit_events = false;
934        self.replace_text(content.text().clone(), window, cx);
935        self.install_tokens(content);
936        self.undo_manager.set_ignoring(false);
937        self.emit_events = true;
938
939        self.reset_selection();
940        self.reset_lsp_state();
941        self.reset_scroll_to_start();
942
943        self.undo_manager.clear();
944        cx.notify();
945    }
946
947    /// Replace the entire text content while preserving undo history.
948    ///
949    /// Unlike [`set_value`](Self::set_value), this method records the
950    /// replacement in the undo stack, allowing the user to undo/redo
951    /// the change. The selection is placed at the end of the new text
952    /// for single-line inputs, or cleared (0..0) for multi-line inputs.
953    ///
954    /// Use this when programmatically replacing the full text but the
955    /// user should still be able to undo the operation — e.g. formatting.
956    pub fn replace_all(
957        &mut self,
958        text: impl Into<SharedString>,
959        window: &mut Window,
960        cx: &mut Context<Self>,
961    ) {
962        self.replace_text(text, window, cx);
963        self.reset_selection();
964        self.reset_lsp_state();
965        self.reset_scroll_to_start();
966
967        cx.notify();
968    }
969
970    /// Perform `f` with the user-facing edit restrictions lifted.
971    ///
972    /// The `disabled` and `readonly` modes only reject the changes made by the
973    /// user, the programmatic APIs must always be able to update the text.
974    pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
975        let (was_disabled, was_readonly) = (self.disabled, self.readonly);
976        (self.disabled, self.readonly) = (false, false);
977        f(self);
978        (self.disabled, self.readonly) = (was_disabled, was_readonly);
979    }
980
981    /// Insert text at the current cursor position.
982    ///
983    /// And the cursor will be moved to the end of inserted text.
984    pub fn insert(
985        &mut self,
986        text: impl Into<SharedString>,
987        window: &mut Window,
988        cx: &mut Context<Self>,
989    ) {
990        let text: SharedString = text.into();
991        self.with_edits_allowed(|this| {
992            this.undo_manager.set_pending_intent(EditIntent::Atomic);
993            let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
994            this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
995            let end = this.active_selection().end;
996            this.set_cursor_to(end);
997        });
998    }
999
1000    /// Replace text at the current cursor position.
1001    ///
1002    /// And the cursor will be moved to the end of replaced text.
1003    pub fn replace(
1004        &mut self,
1005        text: impl Into<SharedString>,
1006        window: &mut Window,
1007        cx: &mut Context<Self>,
1008    ) {
1009        let text: SharedString = text.into();
1010        self.with_edits_allowed(|this| {
1011            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1012            this.replace_text_in_range_silent(None, &text, window, cx);
1013            let end = this.active_selection().end;
1014            this.set_cursor_to(end);
1015        });
1016    }
1017
1018    fn replace_text(
1019        &mut self,
1020        text: impl Into<SharedString>,
1021        window: &mut Window,
1022        cx: &mut Context<Self>,
1023    ) {
1024        let text: SharedString = text.into();
1025        self.with_edits_allowed(|this| {
1026            this.undo_manager.set_pending_intent(EditIntent::Atomic);
1027            let range = 0..this.text.chars().map(|c| c.len_utf16()).sum();
1028            this.replace_text_in_range_silent(Some(range), &text, window, cx);
1029            this.reset_highlighter(cx);
1030        });
1031    }
1032
1033    fn reset_selection(&mut self) {
1034        self.selections.remove_all_but_active();
1035
1036        // For single-line inputs the caret is placed at the end of the text
1037        // (matching HTML `<input>`); multi-line inputs reset the selection to
1038        // `0..0`.
1039        if self.is_single_line() {
1040            let end = self.text.len();
1041            self.set_cursor_to(end);
1042        } else {
1043            self.active_selection_mut().clear();
1044        }
1045    }
1046
1047    fn reset_lsp_state(&mut self) {
1048        if self.is_code_editor() {
1049            self._pending_update = true;
1050            M::reset_language_features(self);
1051        }
1052    }
1053
1054    fn reset_scroll_to_start(&mut self) {
1055        // Move scroll to the start. For single-line the caret is at the end, so
1056        // override the cursor-follow scroll for the next painted frame to keep
1057        // the start visible; the deferred offset is consumed during that paint.
1058        self.scroll_handle.set_offset(point(px(0.), px(0.)));
1059        if self.is_single_line() {
1060            self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1061        }
1062    }
1063
1064    /// Set with disabled mode.
1065    ///
1066    /// See also: [`Self::set_disabled`].
1067    #[allow(unused)]
1068    pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1069        self.disabled = disabled;
1070        self
1071    }
1072
1073    pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1074        if self.disabled == disabled {
1075            return;
1076        }
1077
1078        self.disabled = disabled;
1079        if disabled {
1080            M::hide_context_menu(self, cx);
1081            M::clear_inline_completion(self, cx);
1082        }
1083        cx.notify();
1084    }
1085
1086    /// Set with read-only mode.
1087    ///
1088    /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1089    /// focus, cursor, selection and copy behavior, it only rejects any change
1090    /// of the text made by the user.
1091    ///
1092    /// See also: [`Self::set_readonly`].
1093    #[allow(unused)]
1094    pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1095        self.readonly = readonly;
1096        self
1097    }
1098
1099    pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1100        if self.readonly == readonly {
1101            return;
1102        }
1103
1104        self.readonly = readonly;
1105        if readonly {
1106            M::hide_context_menu(self, cx);
1107            M::clear_inline_completion(self, cx);
1108            self.search_session.replace_mode = false;
1109        }
1110        cx.notify();
1111    }
1112
1113    /// Returns true if the user is allowed to change the text.
1114    ///
1115    /// This is false when the input is `disabled` or `readonly`, the programmatic
1116    /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1117    pub fn is_editable(&self) -> bool {
1118        !self.disabled && !self.readonly
1119    }
1120
1121    /// Set true to clear the input by pressing Escape key.
1122    pub fn clean_on_escape(mut self) -> Self {
1123        self.clean_on_escape = true;
1124        self
1125    }
1126
1127    pub fn set_clean_on_escape(&mut self, clean: bool) {
1128        self.clean_on_escape = clean;
1129    }
1130
1131    /// Set true to treat `Enter` as a submit action in multi-line mode,
1132    /// while `Shift+Enter` inserts a newline.
1133    ///
1134    /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1135    #[doc(hidden)]
1136    pub fn submit_on_enter(mut self, submit: bool) -> Self {
1137        self.submit_on_enter = submit;
1138        self
1139    }
1140
1141    pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1142        self.submit_on_enter = submit;
1143        cx.notify();
1144    }
1145
1146    /// Set whether to show whitespace characters.
1147    #[doc(hidden)]
1148    pub fn show_whitespaces(mut self, show: bool) -> Self {
1149        self.show_whitespaces = show;
1150        self
1151    }
1152
1153    /// Update whether to show whitespace characters.
1154    pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1155        self.show_whitespaces = show;
1156        cx.notify();
1157    }
1158
1159    /// Empty rows reserved below the last line of content ("scroll
1160    /// beyond last line"), code-editor mode only. Mirrors VSCode's
1161    /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1162    ///
1163    /// - `None` (default): half the viewport, floored at
1164    ///   [`BOTTOM_MARGIN_ROWS`] line-heights.
1165    /// - `Some(0)`: no trailing space; the cursor sits flush with the
1166    ///   last row at scroll-max.
1167    /// - `Some(n)`: exactly `n` rows.
1168    pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1169        self.scroll_beyond_last_line = rows;
1170        self
1171    }
1172
1173    /// Update [`Self::scroll_beyond_last_line`] after construction.
1174    pub fn set_scroll_beyond_last_line(
1175        &mut self,
1176        rows: Option<usize>,
1177        _: &mut Window,
1178        cx: &mut Context<Self>,
1179    ) {
1180        if self.scroll_beyond_last_line == rows {
1181            return;
1182        }
1183        self.scroll_beyond_last_line = rows;
1184        cx.notify();
1185    }
1186
1187    /// Minimum number of lines the cursor is kept clear of the viewport's
1188    /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1189    /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1190    /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1191    /// empty region; this controls the cursor's resting distance from the
1192    /// edge.
1193    ///
1194    /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to
1195    ///   one line on small viewports.
1196    /// - `Some(n)`: exactly `n` lines, clamped to half the viewport.
1197    pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1198        self.cursor_surrounding_lines = lines;
1199        self
1200    }
1201
1202    /// Update [`Self::cursor_surrounding_lines`] after construction.
1203    pub fn set_cursor_surrounding_lines(
1204        &mut self,
1205        lines: Option<usize>,
1206        _: &mut Window,
1207        cx: &mut Context<Self>,
1208    ) {
1209        if self.cursor_surrounding_lines == lines {
1210            return;
1211        }
1212        self.cursor_surrounding_lines = lines;
1213        cx.notify();
1214    }
1215
1216    /// Set the default value of the input field.
1217    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1218        let text: SharedString = value.into();
1219        self.text = Rope::from(self.normalize_input(&text).as_ref());
1220        if let Some(diagnostics) = self.mode.diagnostics_mut() {
1221            diagnostics.reset(&self.text)
1222        }
1223        // Note: We can't call display_map.set_text here because it needs cx.
1224        // The text will be set during prepare_if_need in element.rs
1225        self._pending_update = true;
1226        self
1227    }
1228
1229    /// Return the value of the input field as an owned string.
1230    ///
1231    /// The string is materialized on each call. See [`Self::text`] for the
1232    /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1233    pub fn value(&self) -> SharedString {
1234        SharedString::new(self.text.to_string())
1235    }
1236
1237    /// Return the portion of the value within the input field that
1238    /// is selected by the user, as an owned string.
1239    ///
1240    /// The string is materialized on each call. See [`Self::selected_text`]
1241    /// for the same selection borrowed out of the [`Rope`] the state owns.
1242    pub fn selected_value(&self) -> SharedString {
1243        SharedString::new(self.selected_text().to_string())
1244    }
1245
1246    /// Return the value without mask.
1247    pub fn unmask_value(&self) -> SharedString {
1248        self.mask_pattern.unmask(&self.text.to_string()).into()
1249    }
1250
1251    /// Kept so existing render paths keep compiling.
1252    ///
1253    /// Configuration used to be collected by a facade and applied here; the
1254    /// state now configures itself, so this does nothing and can be deleted at
1255    /// the call site.
1256    #[doc(hidden)]
1257    pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1258
1259    /// Return the text [`Rope`] of the input field.
1260    ///
1261    /// Borrowed from the state, so reading even a large document copies
1262    /// nothing. See [`Self::value`] when an owned string is wanted.
1263    pub fn text(&self) -> &Rope {
1264        &self.text
1265    }
1266
1267    /// Return the (0-based) [`Position`] of the cursor.
1268    pub fn cursor_position(&self) -> Position {
1269        let offset = self.cursor();
1270        self.text.offset_to_position(offset)
1271    }
1272
1273    /// Set (0-based) [`Position`] of the cursor.
1274    ///
1275    /// This will move the cursor to the specified line and column, and update the selection range.
1276    pub fn set_cursor_position(
1277        &mut self,
1278        position: impl Into<Position>,
1279        window: &mut Window,
1280        cx: &mut Context<Self>,
1281    ) {
1282        let position: Position = position.into();
1283        let offset = self.text.position_to_offset(&position);
1284
1285        self.move_to(offset, None, cx);
1286        self.update_preferred_column();
1287        self.focus(window, cx);
1288    }
1289
1290    /// Focus the input field.
1291    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1292        self.focus_handle.focus(window, cx);
1293        self.blink_cursor.update(cx, |cursor, cx| {
1294            cursor.start(cx);
1295        });
1296    }
1297
1298    /// Refresh the input, so the next render re-runs syntax highlighting and
1299    /// the LSP providers, not just a redraw.
1300    ///
1301    /// Assigning the `lsp` providers (or other render-affecting state) at
1302    /// runtime does not take effect until the text next changes. Call this
1303    /// afterwards to force the refresh on the next render.
1304    ///
1305    /// ```ignore
1306    /// input.update(cx, |state, cx| {
1307    ///     state.extras.lsp.hover_provider = Some(provider);
1308    ///     state.refresh(cx);
1309    /// });
1310    /// ```
1311    pub fn refresh(&mut self, cx: &mut Context<Self>) {
1312        self._pending_update = true;
1313        cx.notify();
1314    }
1315
1316    pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1317        self.undo_manager.break_transaction_coalescing();
1318        self.select_all_cursors_to(|s, sel| s.previous_boundary(sel.cursor_offset()), cx);
1319    }
1320
1321    pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1322        self.select_all_cursors_to(|s, sel| s.next_boundary(sel.cursor_offset()), cx);
1323    }
1324
1325    pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1326        if self.is_single_line() {
1327            return;
1328        }
1329        self.select_all_cursors_to_with_affinity(
1330            |s, sel| {
1331                s.vertical_selection_target(
1332                    sel.cursor_offset(),
1333                    sel.column_anchor,
1334                    s.line_end_affinity_for(sel),
1335                    -1,
1336                )
1337            },
1338            true,
1339            cx,
1340        );
1341    }
1342
1343    pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1344        if self.is_single_line() {
1345            return;
1346        }
1347        self.select_all_cursors_to_with_affinity(
1348            |s, sel| {
1349                s.vertical_selection_target(
1350                    sel.cursor_offset(),
1351                    sel.column_anchor,
1352                    s.line_end_affinity_for(sel),
1353                    1,
1354                )
1355            },
1356            true,
1357            cx,
1358        );
1359    }
1360
1361    pub(super) fn on_action_select_all(
1362        &mut self,
1363        _: &SelectAll,
1364        window: &mut Window,
1365        cx: &mut Context<Self>,
1366    ) {
1367        self.select_all(window, cx);
1368    }
1369
1370    pub(super) fn select_to_start(
1371        &mut self,
1372        _: &SelectToStart,
1373        _: &mut Window,
1374        cx: &mut Context<Self>,
1375    ) {
1376        self.undo_manager.break_transaction_coalescing();
1377        self.select_all_cursors_to(|_, _| 0, cx);
1378    }
1379
1380    pub(super) fn select_to_end(
1381        &mut self,
1382        _: &SelectToEnd,
1383        _: &mut Window,
1384        cx: &mut Context<Self>,
1385    ) {
1386        self.undo_manager.break_transaction_coalescing();
1387        let end = self.text.len();
1388        self.select_all_cursors_to(move |_, _| end, cx);
1389    }
1390
1391    pub(super) fn select_to_start_of_line(
1392        &mut self,
1393        _: &SelectToStartOfLine,
1394        _: &mut Window,
1395        cx: &mut Context<Self>,
1396    ) {
1397        self.undo_manager.break_transaction_coalescing();
1398        self.select_all_cursors_to(
1399            |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1400            cx,
1401        );
1402    }
1403
1404    pub(super) fn select_to_end_of_line(
1405        &mut self,
1406        _: &SelectToEndOfLine,
1407        _: &mut Window,
1408        cx: &mut Context<Self>,
1409    ) {
1410        self.undo_manager.break_transaction_coalescing();
1411        self.select_all_cursors_to_with_affinity(
1412            |s, sel| {
1413                (
1414                    s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1415                    true,
1416                )
1417            },
1418            false,
1419            cx,
1420        );
1421    }
1422
1423    pub(super) fn select_to_previous_word(
1424        &mut self,
1425        _: &SelectToPreviousWordStart,
1426        _: &mut Window,
1427        cx: &mut Context<Self>,
1428    ) {
1429        self.undo_manager.break_transaction_coalescing();
1430        self.select_all_cursors_to(
1431            |s, sel| s.previous_start_of_word_at(sel.cursor_offset()),
1432            cx,
1433        );
1434    }
1435
1436    pub(super) fn select_to_next_word(
1437        &mut self,
1438        _: &SelectToNextWordEnd,
1439        _: &mut Window,
1440        cx: &mut Context<Self>,
1441    ) {
1442        self.undo_manager.break_transaction_coalescing();
1443        self.select_all_cursors_to(|s, sel| s.next_end_of_word_at(sel.cursor_offset()), cx);
1444    }
1445
1446    /// Return the start offset of the previous word.
1447    /// Return the previous start offset of the word before `offset`.
1448    pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1449        if self.masked {
1450            // The mask replaces every character, so the displayed text has no
1451            // word boundaries to move or delete by. Collapse the word to the
1452            // whole text.
1453            return 0;
1454        }
1455
1456        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1457        // FIXME: Avoid to_string
1458        let left_part = self.text.slice(0..offset).to_string();
1459
1460        let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1461            .rfind(|(_, s)| !s.trim_start().is_empty())
1462            .map(|(i, _)| i)
1463            .unwrap_or(0);
1464        self.token_boundary(target, Bias::Left)
1465    }
1466
1467    /// Return the next end offset of the word after `offset`.
1468    pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1469        if self.masked {
1470            // See `previous_start_of_word_at`.
1471            return self.text.len();
1472        }
1473
1474        let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1475        let right_part = self.text.slice(offset..self.text.len()).to_string();
1476
1477        let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1478            .find(|(_, s)| !s.trim_start().is_empty())
1479            .map(|(i, s)| offset + i + s.len())
1480            .unwrap_or(self.text.len());
1481        self.token_boundary(target, Bias::Right)
1482    }
1483
1484    /// Get start of line byte offset for the given `offset`.
1485    ///
1486    /// When soft wrap is active, first press goes to visual line start,
1487    /// second press (already at visual start) goes to logical line start.
1488    pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1489        if self.is_single_line() {
1490            return 0;
1491        }
1492
1493        let row = self.text.offset_to_point(offset).row;
1494        let logical_start = self.text.line_start_offset(row);
1495
1496        if self.soft_wrap && self.is_code_editor() {
1497            let wrap_point = self
1498                .display_map
1499                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1500            if let Some(line) = self.display_map.line(row)
1501                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1502            {
1503                let visual_start = logical_start + range.start;
1504                if offset != visual_start {
1505                    return visual_start;
1506                }
1507            }
1508        }
1509
1510        logical_start
1511    }
1512
1513    /// Get end of line byte offset for the given `offset`.
1514    ///
1515    /// When soft wrap is active, first press goes to visual line end,
1516    /// second press (already at visual end) goes to logical line end.
1517    pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1518        if self.is_single_line() {
1519            return self.text.len();
1520        }
1521
1522        let row = self.text.offset_to_point(offset).row;
1523        let logical_start = self.text.line_start_offset(row);
1524        let logical_end = self.text.line_end_offset(row);
1525
1526        if self.soft_wrap && self.is_code_editor() {
1527            // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
1528            // the next row, and a second End press would keep walking down instead of falling
1529            // through to the logical line end.
1530            let wrap_point = self
1531                .display_map
1532                .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1533            if let Some(line) = self.display_map.line(row)
1534                && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1535            {
1536                let visual_end = logical_start + range.end;
1537                if offset != visual_end {
1538                    return visual_end;
1539                }
1540            }
1541        }
1542
1543        logical_end
1544    }
1545
1546    /// Get indent string of next line.
1547    ///
1548    /// To get current and next line indent, to return more depth one.
1549    pub(super) fn indent_of_next_line(&mut self) -> String {
1550        self.indent_of_next_line_at(self.cursor())
1551    }
1552
1553    /// Get indent string of the next line, relative to the given `offset`.
1554    pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
1555        if self.is_single_line() {
1556            return "".into();
1557        }
1558
1559        let mut current_indent = String::new();
1560        let mut next_indent = String::new();
1561        let line_end_affinity = self.line_end_affinity_at(offset);
1562        let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
1563        let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
1564        for c in self.text.slice(current_line_start_pos..).chars() {
1565            if !c.is_whitespace() {
1566                break;
1567            }
1568            if c == '\n' || c == '\r' {
1569                break;
1570            }
1571            current_indent.push(c);
1572        }
1573
1574        for c in self.text.slice(next_line_start_pos..).chars() {
1575            if !c.is_whitespace() {
1576                break;
1577            }
1578            if c == '\n' || c == '\r' {
1579                break;
1580            }
1581            next_indent.push(c);
1582        }
1583
1584        if next_indent.len() > current_indent.len() {
1585            return next_indent;
1586        }
1587
1588        // Smart indent: one extra level after lines ending with a trigger.
1589        // Skipped inside strings and comments: the trigger is literal text.
1590        if let Some(rules) = self.mode.language_config() {
1591            if self.mode.is_smart_indent()
1592                && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
1593            {
1594                let line_before: String = self
1595                    .text
1596                    .slice(current_line_start_pos..offset)
1597                    .chars()
1598                    .collect();
1599                if rules.opens_indent(line_before.trim_end()) {
1600                    let tab = self.mode.tab_size();
1601                    if tab.hard_tabs {
1602                        current_indent.push('\t');
1603                    } else {
1604                        for _ in 0..tab.tab_size {
1605                            current_indent.push(' ');
1606                        }
1607                    }
1608                } else {
1609                    let line_after = self.text.slice(offset..next_line_start_pos).to_string();
1610                    if rules.closes_indent(&line_after) {
1611                        let tab = self.mode.tab_size();
1612                        if current_indent.ends_with('\t') {
1613                            current_indent.pop();
1614                        } else {
1615                            for _ in 0..tab.tab_size {
1616                                if !current_indent.ends_with(' ') {
1617                                    break;
1618                                }
1619                                current_indent.pop();
1620                            }
1621                        }
1622                    }
1623                }
1624            }
1625        }
1626
1627        current_indent
1628    }
1629
1630    /// Delete every selection as one batch. Collapsed cursors are first
1631    /// expanded to a deletion range by `collapsed_target` and non-empty
1632    /// selections delete their own range.
1633    ///
1634    /// `collapsed_intent` is the intent to record when every cursor is
1635    /// collapsed, which is what makes a run of single-character deletes undo
1636    /// as one gesture. Deleting a real selection is always atomic.
1637    fn delete_selections(
1638        &mut self,
1639        silent: bool,
1640        collapsed_intent: EditIntent,
1641        mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
1642        window: &mut Window,
1643        cx: &mut Context<Self>,
1644    ) {
1645        if !self.is_editable() {
1646            return;
1647        }
1648        let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
1649        let intent = if cursors.iter().all(|sel| sel.is_empty()) {
1650            collapsed_intent
1651        } else {
1652            EditIntent::Atomic
1653        };
1654        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
1655        for sel in &cursors {
1656            let range = if sel.is_empty() {
1657                collapsed_target(self, sel.cursor_offset())
1658            } else {
1659                sel.start..sel.end
1660            };
1661            let (start, end) = (range.start.min(range.end), range.start.max(range.end));
1662            let mut selection = *sel;
1663            selection.start = start;
1664            selection.end = end;
1665            new_selections.push(selection);
1666        }
1667        // Capture the user's selections before expanding or merging deletion
1668        // ranges. The edit ranges cannot reconstruct their original carets.
1669        self.undo_manager.begin_transaction_with(intent);
1670        self.undo_manager
1671            .record_selections(cursors.clone(), cursors.clone());
1672        self.selections.replace_all(new_selections);
1673        self.undo_manager.set_pending_intent(intent);
1674
1675        let was_silent = self.silent_replace_text;
1676        self.silent_replace_text = silent;
1677        self.replace_text_in_range(None, "", window, cx);
1678        self.silent_replace_text = was_silent;
1679        self.undo_manager
1680            .record_selections(cursors, self.selections.iter().copied().collect());
1681        self.undo_manager.commit_transaction();
1682        self.pause_blink_cursor(cx);
1683    }
1684
1685    /// Decide pairing against the pre-edit text, before an opening quote can
1686    /// change its own syntax context. Ordinary characters never query syntax.
1687    fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
1688        if self.silent_replace_text
1689            || self.ime_marked_range.is_some()
1690            || !self.selections.is_single()
1691            || !self.active_selection().is_empty()
1692            || !range.is_empty()
1693            || range.start != self.cursor()
1694            || text.chars().count() != 1
1695            || !self.mode.is_auto_close()
1696        {
1697            return None;
1698        }
1699        let rules = self.mode.language_config()?;
1700        if self
1701            .text
1702            .chars_at(range.start)
1703            .next()
1704            .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
1705        {
1706            return None;
1707        }
1708        for (open, close, not_in) in rules.closing_pairs() {
1709            let Some(prefix) = open.strip_suffix(text) else {
1710                continue;
1711            };
1712            if !self.text_before_matches(range.start, prefix) {
1713                continue;
1714            }
1715            let start = range.start - prefix.len();
1716            if open == close
1717                && (self.is_escaped_at(start)
1718                    || self
1719                        .text
1720                        .chars_at(start)
1721                        .reversed()
1722                        .next()
1723                        .is_some_and(|c| c.is_alphanumeric() || c == '_'))
1724            {
1725                continue;
1726            }
1727            if not_in.contains(&M::editing_syntax_context(self, start)) {
1728                continue;
1729            }
1730            return Some((open.len(), close.into()));
1731        }
1732        None
1733    }
1734
1735    fn text_before_matches(&self, offset: usize, text: &str) -> bool {
1736        offset >= text.len()
1737            && self.text.is_char_boundary(offset - text.len())
1738            && self.text.slice(offset - text.len()..offset) == text
1739    }
1740
1741    fn text_after_matches(&self, offset: usize, text: &str) -> bool {
1742        offset + text.len() <= self.text.len()
1743            && self.text.is_char_boundary(offset + text.len())
1744            && self.text.slice(offset..offset + text.len()) == text
1745    }
1746
1747    fn is_escaped_at(&self, offset: usize) -> bool {
1748        self.text
1749            .chars_at(offset)
1750            .reversed()
1751            .take_while(|c| *c == '\\')
1752            .count()
1753            % 2
1754            == 1
1755    }
1756
1757    /// Cursor target when a typed closer should skip over an existing one.
1758    ///
1759    /// Returns `Some(offset)` when `new_text` is a single closer from the
1760    /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
1761    /// not escaped. The caller then moves the cursor without editing text or
1762    /// history. `None` means insert normally.
1763    fn skip_over_target(&self, new_text: &str) -> Option<usize> {
1764        if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
1765            return None;
1766        }
1767        let rules = self.mode.language_config()?;
1768        let cursor = self.cursor();
1769        for (open, close, not_in) in rules.closing_pairs() {
1770            for (index, _) in close.char_indices() {
1771                if !close[index..].starts_with(new_text)
1772                    || !self.text_before_matches(cursor, &close[..index])
1773                    || !self.text_after_matches(cursor, &close[index..])
1774                {
1775                    continue;
1776                }
1777                let context = M::editing_syntax_context(self, cursor);
1778                let generated =
1779                    self.mode
1780                        .auto_closed_pairs()
1781                        .contains_closer(cursor, index, close.len());
1782                if !generated
1783                    && not_in.contains(&context)
1784                    && !(context == crate::input::SyntaxContext::String && open == close)
1785                {
1786                    continue;
1787                }
1788                if self.is_escaped_at(cursor - index) {
1789                    continue;
1790                }
1791                return Some(cursor + new_text.len());
1792            }
1793        }
1794        None
1795    }
1796
1797    pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
1798        // Nothing to delete at the start of the text. Propagate so an ancestor
1799        // (e.g. a command palette navigating back a level) can act on it.
1800        // This is harmless when nothing upstream is bound to backspace. With multiple
1801        // cursors the others can still delete, so only the lone-cursor case
1802        // propagates.
1803        if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
1804            cx.propagate();
1805            return;
1806        }
1807
1808        // Pair deletion follows automatic closing rules, independently of
1809        // structural brackets used by Enter.
1810        if self.mode.is_auto_close()
1811            && self.selections.is_single()
1812            && self.active_selection().is_empty()
1813        {
1814            let off = self.cursor();
1815            let deletion = self.mode.language_config().and_then(|rules| {
1816                rules.closing_pairs().find_map(|(open, close, not_in)| {
1817                    if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
1818                    {
1819                        return None;
1820                    }
1821                    let start = off - open.len();
1822                    let generated = self
1823                        .mode
1824                        .auto_closed_pairs()
1825                        .contains(start..off, off..off + close.len());
1826                    if self.is_escaped_at(start)
1827                        || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
1828                    {
1829                        return None;
1830                    }
1831                    Some(start..off + close.len())
1832                })
1833            });
1834            if let Some(range) = deletion {
1835                let utf16 = self.range_to_utf16(&range);
1836                self.replace_text_in_range_silent(Some(utf16), "", window, cx);
1837                return;
1838            }
1839        }
1840
1841        self.delete_selections(
1842            false,
1843            EditIntent::Backspace,
1844            |s, offset| s.previous_boundary(offset)..offset,
1845            window,
1846            cx,
1847        );
1848    }
1849
1850    pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
1851        self.delete_selections(
1852            false,
1853            EditIntent::DeleteForward,
1854            |s, offset| offset..s.next_boundary(offset),
1855            window,
1856            cx,
1857        );
1858    }
1859
1860    pub(super) fn delete_to_beginning_of_line(
1861        &mut self,
1862        _: &DeleteToBeginningOfLine,
1863        window: &mut Window,
1864        cx: &mut Context<Self>,
1865    ) {
1866        self.delete_selections(
1867            true,
1868            EditIntent::Atomic,
1869            |s, offset| {
1870                let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
1871                if start == offset {
1872                    start = start.saturating_sub(1);
1873                }
1874                start..offset
1875            },
1876            window,
1877            cx,
1878        );
1879    }
1880
1881    pub(super) fn delete_to_end_of_line(
1882        &mut self,
1883        _: &DeleteToEndOfLine,
1884        window: &mut Window,
1885        cx: &mut Context<Self>,
1886    ) {
1887        self.delete_selections(
1888            true,
1889            EditIntent::Atomic,
1890            |s, offset| {
1891                let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
1892                if end == offset {
1893                    end = (end + 1).clamp(0, s.text.len());
1894                }
1895                offset..end
1896            },
1897            window,
1898            cx,
1899        );
1900    }
1901
1902    pub(super) fn delete_previous_word(
1903        &mut self,
1904        _: &DeleteToPreviousWordStart,
1905        window: &mut Window,
1906        cx: &mut Context<Self>,
1907    ) {
1908        self.delete_selections(
1909            true,
1910            EditIntent::Atomic,
1911            |s, offset| s.previous_start_of_word_at(offset)..offset,
1912            window,
1913            cx,
1914        );
1915    }
1916
1917    pub(super) fn delete_next_word(
1918        &mut self,
1919        _: &DeleteToNextWordEnd,
1920        window: &mut Window,
1921        cx: &mut Context<Self>,
1922    ) {
1923        self.delete_selections(
1924            true,
1925            EditIntent::Atomic,
1926            |s, offset| offset..s.next_end_of_word_at(offset),
1927            window,
1928            cx,
1929        );
1930    }
1931
1932    pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
1933        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
1934            return;
1935        }
1936
1937        // Clear inline completion on enter (user chose not to accept it)
1938        if M::has_inline_completion(self) {
1939            M::clear_inline_completion(self, cx);
1940        }
1941
1942        // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
1943        // (without Shift) is treated as submit: propagate the action and emit
1944        // PressEnter without inserting a newline. `Shift+Enter` still inserts
1945        // a newline.
1946        let insert_newline = self.is_multi_line() && (!self.submit_on_enter || action.shift);
1947
1948        if insert_newline {
1949            if !self.selections.is_single() {
1950                // Insert a newline (with per-line indent) at every cursor.
1951                self.selections.merge_overlapping();
1952                let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
1953                let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
1954                for sel in &selections {
1955                    let indent = if self.is_code_editor() {
1956                        self.indent_of_next_line_at(sel.cursor_offset())
1957                    } else {
1958                        String::new()
1959                    };
1960                    edits.push((sel.start..sel.end, format!("\n{}", indent)));
1961                }
1962                edits.sort_by_key(|(range, _)| range.start);
1963                self.replace_text_in_ranges(&edits, window, cx);
1964                self.pause_blink_cursor(cx);
1965            } else {
1966                // Bracket split: Enter between `{|}` produces `{\n  \n}`
1967                // with the cursor on the middle line. Controlled by smart_indent,
1968                // independently of automatic closing.
1969                // Skipped inside strings and comments: splitting there would
1970                // restructure literal text.
1971                let mut split = false;
1972                if self.is_code_editor() && self.active_selection().is_empty() {
1973                    if let Some(rules) = self.mode.language_config() {
1974                        if self.mode.is_smart_indent()
1975                            && M::editing_syntax_context(self, self.cursor())
1976                                == crate::input::SyntaxContext::Code
1977                        {
1978                            let off = self.cursor();
1979                            let is_pair = rules.brackets.iter().any(|p| {
1980                                !p.open.is_empty()
1981                                    && !p.close.is_empty()
1982                                    && p.open != p.close
1983                                    && self.text_before_matches(off, p.open.as_ref())
1984                                    && self.text_after_matches(off, p.close.as_ref())
1985                            });
1986                            if is_pair {
1987                                // Base indent: leading whitespace only.
1988                                let line_end_affinity = self.line_end_affinity_at(off);
1989                                let line_start = self.start_of_line_at(off, line_end_affinity);
1990                                let mut indent = String::new();
1991                                for c in self.text.slice(line_start..).chars() {
1992                                    if !c.is_whitespace() || c == '\n' || c == '\r' {
1993                                        break;
1994                                    }
1995                                    indent.push(c);
1996                                }
1997                                // Extra level only with smart indent enabled.
1998                                let mut inner = indent.clone();
1999                                if self.mode.is_smart_indent() {
2000                                    let tab = self.mode.tab_size();
2001                                    if tab.hard_tabs {
2002                                        inner.push('\t');
2003                                    } else {
2004                                        for _ in 0..tab.tab_size {
2005                                            inner.push(' ');
2006                                        }
2007                                    }
2008                                }
2009                                let new_line_text = format!("\n{inner}\n{indent}");
2010                                self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2011                                self.set_cursor_to(off + 1 + inner.len());
2012                                self.update_preferred_column();
2013                                let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2014                                self.undo_manager
2015                                    .record_selections(cursors.clone(), cursors);
2016                                self.pause_blink_cursor(cx);
2017                                split = true;
2018                            }
2019                        }
2020                    }
2021                }
2022                if !split {
2023                    // Get current line indent
2024                    let indent = if self.is_code_editor() {
2025                        self.indent_of_next_line()
2026                    } else {
2027                        "".to_string()
2028                    };
2029
2030                    // Add newline and indent
2031                    let new_line_text = format!("\n{}", indent);
2032                    self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2033                    self.pause_blink_cursor(cx);
2034                }
2035            }
2036        } else {
2037            // Single line input or submit-on-enter: just emit the event
2038            // (e.g.: in a dialog to confirm, or a chat textarea to send).
2039            self.undo_manager.break_transaction_coalescing();
2040            cx.propagate();
2041        }
2042
2043        cx.emit(InputEvent::PressEnter {
2044            secondary: action.secondary,
2045            shift: action.shift,
2046        });
2047    }
2048
2049    pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2050        self.replace_text("", window, cx);
2051        self.set_selection(0, 0);
2052        self.scroll_to(0, None, cx);
2053    }
2054
2055    pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2056        if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2057            return;
2058        }
2059
2060        // Escape also dismisses a request whose popup has not arrived yet.
2061        M::hide_context_menu(self, cx);
2062
2063        // Collapse extra cursors back to the active one first.
2064        if !self.selections.is_single() {
2065            self.undo_manager.break_transaction_coalescing();
2066            self.selections.remove_all_but_active();
2067            cx.notify();
2068            return;
2069        }
2070
2071        // Clear inline completion on escape
2072        if M::has_inline_completion(self) {
2073            M::clear_inline_completion(self, cx);
2074            return; // Consume the escape, don't propagate
2075        }
2076        M::clear_inline_completion(self, cx);
2077
2078        // The handles and the edit menu are the topmost surface to dismiss.
2079        if self.touch_selection().is_some() {
2080            self.dismiss_touch_selection(cx);
2081            return;
2082        }
2083
2084        if self.ime_marked_range.is_some() {
2085            self.unmark_text(window, cx);
2086        }
2087
2088        if self.clean_on_escape {
2089            return self.clean(window, cx);
2090        }
2091
2092        cx.propagate();
2093    }
2094
2095    /// Show the right-click context menu as a native OS menu.
2096    pub(crate) fn handle_right_click_menu(
2097        &mut self,
2098        position: Point<Pixels>,
2099        offset: usize,
2100        window: &mut Window,
2101        cx: &mut Context<Self>,
2102    ) {
2103        if self.disabled {
2104            return;
2105        }
2106        if crate::GlobalState::is_in_deferred_context(cx) {
2107            return;
2108        }
2109
2110        if !self.active_selection().contains(offset) {
2111            self.move_to(offset, None, cx);
2112        }
2113
2114        if self.is_code_editor() {
2115            M::on_hover_definition(self, offset, window, cx);
2116        }
2117
2118        if let Some(handler) = self.context_menu_handler.clone() {
2119            let capabilities = self.context_menu_capabilities();
2120            cx.defer_in(window, move |_, window, cx| {
2121                handler(NativeMenu::new(), capabilities, position, window, cx);
2122            });
2123        }
2124    }
2125
2126    pub(super) fn add_cursor_above(
2127        &mut self,
2128        _: &AddCursorAbove,
2129        _: &mut Window,
2130        cx: &mut Context<Self>,
2131    ) {
2132        self.add_cursor_vertical(-1, cx);
2133    }
2134
2135    pub(super) fn add_cursor_below(
2136        &mut self,
2137        _: &AddCursorBelow,
2138        _: &mut Window,
2139        cx: &mut Context<Self>,
2140    ) {
2141        self.add_cursor_vertical(1, cx);
2142    }
2143
2144    /// Add a new cursor one display line above (`move_lines < 0`) or below each
2145    /// existing cursor, preserving the column. Cursors that would not move (at
2146    /// the first/last display row) or that would duplicate an existing cursor
2147    /// are skipped.
2148    fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2149        if !self.is_multi_line() {
2150            return;
2151        }
2152
2153        self.pause_blink_cursor(cx);
2154        // Changing the cursor set ends the editing gesture that came before it.
2155        self.undo_manager.break_transaction_coalescing();
2156
2157        let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2158            .selections
2159            .iter()
2160            .map(|sel| {
2161                (
2162                    sel.cursor_offset(),
2163                    sel.column_anchor,
2164                    self.line_end_affinity_for(sel),
2165                )
2166            })
2167            .collect();
2168        let mut offsets: std::collections::HashSet<usize> =
2169            sources.iter().map(|(offset, _, _)| *offset).collect();
2170
2171        let mut newest: Option<usize> = None;
2172        for (offset, anchor, line_end_affinity) in sources {
2173            let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2174            let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2175            if target == offset || offsets.contains(&target) {
2176                continue;
2177            }
2178            offsets.insert(target);
2179            let id = self.selections.generate_id();
2180            let mut cursor = CursorSelection::new(id, target, target);
2181            cursor.column_anchor = anchor;
2182            self.selections.add(cursor);
2183            newest = Some(target);
2184        }
2185
2186        if let Some(newest) = newest {
2187            self.scroll_to(newest, None, cx);
2188        }
2189        cx.notify();
2190    }
2191
2192    /// Add an additional collapsed cursor at `offset`.
2193    ///
2194    /// Rejected when `offset` lands inside an existing selection or exactly on
2195    /// an existing cursor.
2196    pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2197        if !self.is_multi_line() {
2198            return;
2199        }
2200
2201        for sel in self.selections.iter() {
2202            if sel.contains(offset) {
2203                return;
2204            }
2205            if sel.is_collapsed() && sel.cursor_offset() == offset {
2206                return;
2207            }
2208        }
2209
2210        self.undo_manager.break_transaction_coalescing();
2211        let id = self.selections.generate_id();
2212        let mut selection = CursorSelection::new(id, offset, offset);
2213        selection.column_anchor = self.preferred_column_for(offset);
2214        self.selections.add(selection);
2215        cx.notify();
2216    }
2217
2218    /// Build a columnar (block) selection spanning the rows between the two
2219    /// points, one selection per display row at the same column span.
2220    ///
2221    /// The span keeps the columns the pointer sat past the end of a short row, so a row
2222    /// that runs out of text does not narrow the block for the rows that do reach that
2223    /// far. Each row is then clipped to its own end, selecting as much of the span as it
2224    /// actually has.
2225    pub(super) fn build_columnar_selection(
2226        &mut self,
2227        start: ColumnarPoint,
2228        end: ColumnarPoint,
2229        cx: &mut Context<Self>,
2230    ) {
2231        if !self.is_multi_line() {
2232            return;
2233        }
2234
2235        self.undo_manager.break_transaction_coalescing();
2236
2237        let (start_row, start_col) = self.columnar_row_column(start);
2238        let (end_row, end_col) = self.columnar_row_column(end);
2239        let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2240        let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2241
2242        let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2243        for row in start_row..=end_row {
2244            let sel_start = self
2245                .display_map
2246                .display_row_column_to_offset(row, start_col);
2247            let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2248            let id = self.selections.generate_id();
2249            let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2250            let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2251            new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2252        }
2253
2254        self.selections.replace_all(new_selections);
2255        cx.notify();
2256    }
2257
2258    /// Resolve a columnar point to the display row it is on and the column it reaches,
2259    /// counting the columns beyond the row's end so a short row keeps the full span.
2260    fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2261        let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2262        let row = self
2263            .display_map
2264            .wrap_row_to_display_row(display_point.row)
2265            .unwrap_or_else(|| {
2266                self.display_map
2267                    .nearest_visible_display_row(display_point.row)
2268            });
2269
2270        (row, display_point.column + point.columns_past_line_end)
2271    }
2272
2273    pub(super) fn on_mouse_down(
2274        &mut self,
2275        event: &MouseDownEvent,
2276        window: &mut Window,
2277        cx: &mut Context<Self>,
2278    ) {
2279        // A token that consumed the press (a double click selecting it) must
2280        // not also place the caret.
2281        if window.default_prevented() {
2282            return;
2283        }
2284        self.undo_manager.break_transaction_coalescing();
2285        // Input has its own text selection; suppress the window-level text
2286        // selection (Root) so it does not start a drag from here.
2287        crate::global_state::GlobalState::suppress_text_selection(cx);
2288
2289        // Clear inline completion on any mouse interaction
2290        M::clear_inline_completion(self, cx);
2291        // A tap on the touch selection asks for its menu back. Any other press
2292        // places the caret or starts a new drag, and the handles and the menu
2293        // no longer belong to what is selected.
2294        if event.button == MouseButton::Left
2295            && event.click_count == 1
2296            && self.reopen_edit_menu_at(event.position, cx)
2297        {
2298            return;
2299        }
2300        self.dismiss_touch_selection(cx);
2301
2302        // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2303        // Clear the marked range.
2304        if let Some(ime_marked_range) = &self.ime_marked_range {
2305            if ime_marked_range.len() == 0 {
2306                self.ime_marked_range = None;
2307            }
2308        }
2309
2310        self.selecting = true;
2311        let (offset, line_end_affinity, columns_past_line_end) =
2312            self.resolve_mouse_position(event.position);
2313
2314        if M::on_click(self, event, offset, window, cx) {
2315            return;
2316        }
2317
2318        // Triple click to select line
2319        if event.button == MouseButton::Left && event.click_count >= 3 {
2320            self.select_line(offset, window, cx);
2321            return;
2322        }
2323
2324        // Double click to select word
2325        if event.button == MouseButton::Left && event.click_count == 2 {
2326            self.select_word(offset, window, cx);
2327            // A double tap is touch's other way to select a word, and it
2328            // gets the handles and the menu like a long press does.
2329            if crate::GlobalState::is_touch_press(cx) {
2330                self.keep_touch_selection(cx);
2331            }
2332            return;
2333        }
2334
2335        // Show Mouse context menu
2336        if event.button == MouseButton::Right {
2337            if self.enable_context_menu {
2338                if !self.active_selection().contains(offset) {
2339                    self.move_to(offset, None, cx);
2340                }
2341                self.pending_context_menu = Some((event.position, offset));
2342            }
2343            return;
2344        }
2345
2346        // Multi-cursor placement, multi-line only.
2347        if self.is_multi_line() && event.button == MouseButton::Left {
2348            if event.modifiers.alt
2349                && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2350            {
2351                // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2352                // Mark selecting so the drag handler extends the block.
2353                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2354                self.selecting = true;
2355                self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2356                return;
2357            } else if event.modifiers.alt {
2358                self.add_cursor_at(offset, cx);
2359                // Keep click-to-add behavior, but use this press as the block
2360                // anchor if the user continues dragging with the left button.
2361                self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2362                return;
2363            }
2364        }
2365
2366        if event.modifiers.shift {
2367            self.select_to_with_affinity(offset, line_end_affinity, cx);
2368        } else {
2369            self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2370        }
2371    }
2372
2373    pub(super) fn on_mouse_up(
2374        &mut self,
2375        event: &MouseUpEvent,
2376        window: &mut Window,
2377        cx: &mut Context<Self>,
2378    ) {
2379        if event.button == MouseButton::Right {
2380            if let Some((position, offset)) = self.pending_context_menu.take() {
2381                self.handle_right_click_menu(position, offset, window, cx);
2382            }
2383        }
2384        if self.active_selection().is_empty() {
2385            self.active_selection_mut().reversed = false;
2386        }
2387        self.selecting = false;
2388        self.selected_word_range = None;
2389        self.column_select_start = None;
2390        self.auto_scroll.stop();
2391    }
2392
2393    pub(super) fn on_mouse_move(
2394        &mut self,
2395        event: &MouseMoveEvent,
2396        window: &mut Window,
2397        cx: &mut Context<Self>,
2398    ) {
2399        // Check if mouse is within bounds
2400        let within_bounds = self
2401            .last_bounds
2402            .as_ref()
2403            .map(|bounds| bounds.contains(&event.position))
2404            .unwrap_or(false);
2405
2406        if !within_bounds {
2407            // Clear hover when mouse leaves the input
2408            M::clear_hover_state(self, cx);
2409            return;
2410        }
2411
2412        // Show diagnostic popover on mouse move
2413        let (offset, _) = self.index_for_mouse_position(event.position);
2414        M::on_mouse_move(self, offset, event, window, cx);
2415
2416        if self.is_code_editor() {
2417            // Keep the current popover while the pointer stays on the same
2418            // diagnostic, so moving over a squiggle neither repaints nor
2419            // rebuilds the popover.
2420            match self
2421                .mode
2422                .diagnostics()
2423                .and_then(|set| set.for_offset(offset))
2424            {
2425                Some(diagnostic) => {
2426                    if self.diagnostic_popover.as_deref() != Some(diagnostic) {
2427                        self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
2428                        cx.notify();
2429                    }
2430                }
2431                None => {
2432                    if self.diagnostic_popover.take().is_some() {
2433                        cx.notify();
2434                    }
2435                }
2436            }
2437        }
2438    }
2439
2440    pub(super) fn on_scroll_wheel(
2441        &mut self,
2442        event: &ScrollWheelEvent,
2443        window: &mut Window,
2444        cx: &mut Context<Self>,
2445    ) {
2446        let line_height = self
2447            .last_layout
2448            .as_ref()
2449            .map(|layout| layout.line_height)
2450            .unwrap_or(window.line_height());
2451        let delta = event.delta.pixel_delta(line_height);
2452
2453        let old_offset = self.scroll_handle.offset();
2454        self.update_scroll_offset(Some(old_offset + delta), cx);
2455
2456        // Only stop propagation if the offset actually changed
2457        if self.scroll_handle.offset() != old_offset {
2458            cx.stop_propagation();
2459        }
2460
2461        if self.diagnostic_popover.take().is_some() {
2462            cx.notify();
2463        }
2464        // The handles follow the text; the menu would sit over whatever
2465        // scrolls underneath it, so it steps aside until the finger lifts.
2466        self.edit_menu_on_scroll(event.touch_phase, cx);
2467    }
2468
2469    pub(super) fn update_scroll_offset(
2470        &mut self,
2471        offset: Option<Point<Pixels>>,
2472        cx: &mut Context<Self>,
2473    ) {
2474        let mut offset = offset.unwrap_or(self.scroll_handle.offset());
2475        // In addition to left alignment, a cursor position will be reserved on the right side
2476        let safe_x_offset = if self.text_align == TextAlign::Left {
2477            px(0.)
2478        } else {
2479            -CURSOR_WIDTH
2480        };
2481
2482        let safe_y_range =
2483            (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.);
2484        let safe_x_range = (-self.scroll_size.width + self.input_bounds.size.width + safe_x_offset)
2485            .min(safe_x_offset)..px(0.);
2486
2487        offset.y = if self.is_single_line() {
2488            px(0.)
2489        } else {
2490            offset.y.clamp(safe_y_range.start, safe_y_range.end)
2491        };
2492        offset.x = offset.x.clamp(safe_x_range.start, safe_x_range.end);
2493        if self.scroll_handle.offset() != offset {
2494            self.scroll_handle.set_offset(offset);
2495            cx.notify();
2496        }
2497    }
2498
2499    /// Scroll to make the given offset visible.
2500    ///
2501    /// If `direction` is Some, will keep edges at the same side.
2502    pub(crate) fn scroll_to(
2503        &mut self,
2504        offset: usize,
2505        direction: Option<MoveDirection>,
2506        cx: &mut Context<Self>,
2507    ) {
2508        let padding = if direction.is_some() {
2509            ScrollPadding::SurroundingLines
2510        } else {
2511            ScrollPadding::Minimal
2512        };
2513        self.scroll_to_with_padding(offset, direction, padding, cx);
2514    }
2515
2516    /// Reveal an offset with independently chosen direction restriction and padding.
2517    /// Search uses surrounding lines without restricting movement to match order.
2518    pub(crate) fn scroll_to_with_padding(
2519        &mut self,
2520        offset: usize,
2521        direction: Option<MoveDirection>,
2522        padding: ScrollPadding,
2523        cx: &mut Context<Self>,
2524    ) {
2525        let Some(last_layout) = self.last_layout.as_ref() else {
2526            return;
2527        };
2528        let Some(bounds) = self.last_bounds.as_ref() else {
2529            return;
2530        };
2531
2532        let mut scroll_offset = self.scroll_handle.offset();
2533        let was_offset = scroll_offset;
2534        let line_height = last_layout.line_height;
2535
2536        let point = self.text.offset_to_point(offset);
2537
2538        let row = point.row;
2539
2540        // Resolve the wrapped row even when the target is outside the last layout.
2541        let display_pos = self
2542            .display_map
2543            .buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column));
2544        let row_offset_y = line_height * display_pos.row;
2545
2546        // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
2547        // in layout_cursors, so shifting the text here would cause a first-click visual jump.
2548        let safety_margin = match last_layout.text_align {
2549            TextAlign::Start | TextAlign::Left => RIGHT_MARGIN,
2550            TextAlign::End | TextAlign::Right => px(0.),
2551            TextAlign::Center => CURSOR_WIDTH,
2552        };
2553        if let Some(vi) = last_layout
2554            .visible_buffer_lines
2555            .iter()
2556            .position(|&line| line == row)
2557        {
2558            let line = &last_layout.lines[vi];
2559            let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
2560            if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
2561                let bounds_width = bounds.size.width - last_layout.line_number_width;
2562                let col_offset_x = pos.x;
2563                if col_offset_x - safety_margin < -scroll_offset.x {
2564                    // If the position is out of the visible area, scroll to make it visible
2565                    scroll_offset.x = -col_offset_x + safety_margin;
2566                } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
2567                    scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
2568                }
2569            }
2570        }
2571
2572        // Scroll the row into view. Use the same edge clearance helper as
2573        // `TextElement::layout_cursors` so both scroll-into-view paths agree
2574        // (a mismatch flickered on `Down` at end-of-buffer with a small
2575        // `cursor_surrounding_lines` override).
2576        let edge_height =
2577            if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
2578                super::element::cursor_surrounding_padding(
2579                    self.mode.is_auto_grow(),
2580                    self.cursor_surrounding_lines,
2581                    super::element::viewport_visible_lines(bounds.size.height, line_height),
2582                    line_height,
2583                )
2584            } else {
2585                line_height
2586            };
2587        if row_offset_y - edge_height + line_height < -scroll_offset.y {
2588            // Scroll up
2589            scroll_offset.y = -row_offset_y + edge_height - line_height;
2590        } else if row_offset_y + edge_height > -scroll_offset.y + bounds.size.height {
2591            // Scroll down
2592            scroll_offset.y = -(row_offset_y - bounds.size.height + edge_height);
2593        }
2594
2595        // Avoid necessary scroll, when it was already in the correct position.
2596        if direction == Some(MoveDirection::Up) {
2597            scroll_offset.y = scroll_offset.y.max(was_offset.y);
2598        } else if direction == Some(MoveDirection::Down) {
2599            scroll_offset.y = scroll_offset.y.min(was_offset.y);
2600        }
2601
2602        // Clamp the deferred target into the same safe range that
2603        // `update_scroll_offset` enforces on persist, so paint never shows an
2604        // over-scrolled frame before the post-paint clamp pulls it back.
2605        let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.));
2606        scroll_offset.x = scroll_offset.x.min(px(0.));
2607        scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.));
2608        self.deferred_scroll_offset = Some(scroll_offset);
2609        cx.notify();
2610    }
2611
2612    pub(super) fn show_character_palette(
2613        &mut self,
2614        _: &ShowCharacterPalette,
2615        window: &mut Window,
2616        _: &mut Context<Self>,
2617    ) {
2618        window.show_character_palette();
2619    }
2620
2621    /// The text of every non-empty selection, in document order.
2622    fn selected_texts(&self) -> Vec<String> {
2623        let mut selections: Vec<CursorSelection> = self
2624            .selections
2625            .iter()
2626            .copied()
2627            .filter(|sel| !sel.is_empty())
2628            .collect();
2629        selections.sort_by_key(|sel| sel.start);
2630        selections
2631            .iter()
2632            .map(|sel| self.text.slice(*sel).to_string())
2633            .collect()
2634    }
2635
2636    pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2637        if !self.is_copyable() {
2638            return;
2639        }
2640
2641        let texts = self.selected_texts();
2642
2643        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
2644    }
2645
2646    pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
2647        if !self.is_copyable() {
2648            return;
2649        }
2650
2651        let texts = self.selected_texts();
2652
2653        cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
2654
2655        self.undo_manager.set_pending_intent(EditIntent::Atomic);
2656        self.replace_text_in_range_silent(None, "", window, cx);
2657    }
2658
2659    pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
2660        if !self.is_editable() {
2661            return;
2662        }
2663        if let Some(clipboard) = cx.read_from_clipboard() {
2664            self.insert_clipboard(clipboard, window, cx);
2665        }
2666    }
2667
2668    /// Inserts the clipboard text the way `Paste` does: one atomic edit,
2669    /// newlines dropped on a single-line input, one line per selection when
2670    /// the counts match on a multi-line one. A clipboard without text (an
2671    /// image, say) is left alone rather than replacing the selection with
2672    /// nothing.
2673    fn insert_clipboard(
2674        &mut self,
2675        clipboard: ClipboardItem,
2676        window: &mut Window,
2677        cx: &mut Context<Self>,
2678    ) {
2679        let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
2680            return;
2681        };
2682        // A paste is one atomic edit, never part of a typing run.
2683        self.undo_manager.set_pending_intent(EditIntent::Atomic);
2684
2685        if !self.is_multi_line() {
2686            new_text = new_text.replace('\n', "");
2687            self.replace_text_in_range_silent(None, &new_text, window, cx);
2688            self.scroll_to(self.cursor(), None, cx);
2689            return;
2690        }
2691
2692        // Distribute one clipboard line per selection when the counts match.
2693        // Otherwise insert the whole clipboard text at each cursor.
2694        if !self.selections.is_single() {
2695            self.selections.merge_overlapping();
2696        }
2697        let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
2698        let count = self.selections.len();
2699        if count > 1 && lines.len() == count {
2700            let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2701            selections.sort_by_key(|sel| sel.start);
2702            let edits: Vec<(Range<usize>, String)> = selections
2703                .iter()
2704                .zip(lines)
2705                .map(|(sel, line)| (sel.start..sel.end, line))
2706                .collect();
2707            self.replace_text_in_ranges(&edits, window, cx);
2708        } else {
2709            self.replace_text_in_range_silent(None, &new_text, window, cx);
2710        }
2711        self.scroll_to(self.cursor(), None, cx);
2712    }
2713
2714    /// The intent of a batch the caller did not label: inserting text at
2715    /// collapsed cursors is typing, anything else stands on its own.
2716    fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
2717        if !new_text.is_empty()
2718            && !new_text.contains(['\n', '\r'])
2719            && edits.iter().all(|(range, _)| range.is_empty())
2720        {
2721            EditIntent::Typing
2722        } else {
2723            EditIntent::Atomic
2724        }
2725    }
2726
2727    /// Where a cursor stood before an edit made with this intent.
2728    ///
2729    /// Backspace and forward delete expand a collapsed cursor over the text
2730    /// they are about to remove, so the recorded cursor has to collapse back to
2731    /// the side it came from for undo to restore it where the user left it.
2732    fn collapse_for_intent(
2733        intent: EditIntent,
2734        mut selection: CursorSelection,
2735        range: &Range<usize>,
2736    ) -> CursorSelection {
2737        match intent {
2738            EditIntent::Backspace => selection.place_at(range.end, None),
2739            EditIntent::DeleteForward => selection.place_at(range.start, None),
2740            EditIntent::Typing | EditIntent::Atomic => {}
2741        }
2742        selection
2743    }
2744
2745    fn push_history(
2746        &mut self,
2747        text: &Rope,
2748        range: &Range<usize>,
2749        new_text: &str,
2750        requested_intent: Option<EditIntent>,
2751        selection_before: CursorSelection,
2752        selection_after: Option<CursorSelection>,
2753    ) -> bool {
2754        self.document_revision = self.document_revision.wrapping_add(1);
2755        let token_delta = self.edit_tokens(range, new_text.len());
2756        if self.undo_manager.is_ignoring() {
2757            return false;
2758        }
2759
2760        let range =
2761            text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
2762        let old_text = text.slice(range.clone()).to_string();
2763        let new_range = range.start..range.start + new_text.len();
2764
2765        let intent = requested_intent.unwrap_or_else(|| {
2766            if range.is_empty()
2767                && old_text.is_empty()
2768                && !new_text.is_empty()
2769                && !new_text.contains(['\n', '\r'])
2770            {
2771                EditIntent::Typing
2772            } else {
2773                EditIntent::Atomic
2774            }
2775        });
2776
2777        let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
2778        let selection_after =
2779            selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
2780
2781        let open_transaction = self.undo_manager.has_open_transaction();
2782        let mut change = Change::new(range, &old_text, new_range, new_text);
2783        change.token_delta = token_delta;
2784        let recorded = self.undo_manager.record_transaction(change, intent);
2785        // A batch records its own cursor sets. This covers a change that is a
2786        // transaction on its own.
2787        if recorded && !open_transaction {
2788            self.undo_manager
2789                .record_selections(vec![selection_before], vec![selection_after]);
2790        }
2791        recorded
2792    }
2793
2794    pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
2795        self.replay_history(true, window, cx);
2796    }
2797
2798    pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
2799        self.replay_history(false, window, cx);
2800    }
2801
2802    fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
2803        if !self.is_editable() {
2804            return;
2805        }
2806        let replay = if undo {
2807            self.undo_manager.undo()
2808        } else {
2809            self.undo_manager.redo()
2810        };
2811        let Some(replay) = replay else {
2812            return;
2813        };
2814        let token_aware = self.inline_tokens.is_some()
2815            || replay
2816                .changes
2817                .iter()
2818                .any(|change| change.token_delta.is_some());
2819        let emit_events = self.emit_events;
2820        if token_aware {
2821            self.emit_events = false;
2822        }
2823        self.replaying_history = token_aware;
2824        self.undo_manager.set_ignoring(true);
2825        for change in &replay.changes {
2826            let (range, text) = if undo {
2827                (change.new_range.into(), &change.old_text)
2828            } else {
2829                (change.old_range.into(), &change.new_text)
2830            };
2831            let range_utf16 = self.range_to_utf16(&range);
2832            self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
2833            self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
2834        }
2835        self.restore_selections(replay.selections);
2836        self.mode
2837            .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
2838        if token_aware {
2839            // Token replay bypasses IME normalization; a stale marked range
2840            // would otherwise describe text that no longer exists.
2841            self.ime_marked_range = None;
2842        }
2843        self.undo_manager.set_ignoring(false);
2844        self.replaying_history = false;
2845        self.emit_events = emit_events;
2846        if token_aware && emit_events {
2847            cx.emit(InputEvent::Change);
2848        }
2849        cx.notify();
2850    }
2851
2852    /// Restore a set of selections captured in a transaction, clamping offsets
2853    /// to the current text length. `None` leaves the current selections as the
2854    /// replay left them.
2855    fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
2856        let Some(selections) = selections else {
2857            return;
2858        };
2859
2860        let len = self.text.len();
2861        let restored: Vec<CursorSelection> = selections
2862            .into_iter()
2863            .map(|mut sel| {
2864                sel.start = sel.start.min(len);
2865                sel.end = sel.end.min(len);
2866                sel
2867            })
2868            .collect();
2869        self.selections.replace_all(restored);
2870        self.selections.merge_overlapping();
2871    }
2872
2873    /// Get byte offset of the cursor.
2874    ///
2875    /// The offset is the UTF-8 offset.
2876    pub fn cursor(&self) -> usize {
2877        if let Some(ime_marked_range) = &self.ime_marked_range {
2878            return ime_marked_range.end;
2879        }
2880
2881        self.selections.active().cursor_offset()
2882    }
2883
2884    /// Returns the active selection.
2885    pub(super) fn active_selection(&self) -> &CursorSelection {
2886        self.selections.active()
2887    }
2888
2889    /// Returns a mutable reference to the active selection.
2890    pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
2891        self.selections.active_mut()
2892    }
2893
2894    /// Sets the active selection to the given range, keeping its `reversed`
2895    /// and `column_anchor` state untouched.
2896    pub(super) fn set_selection(&mut self, start: usize, end: usize) {
2897        let range = self.normalize_token_range(start..end);
2898        let (start, end) = (range.start, range.end);
2899        let active = self.active_selection_mut();
2900        active.start = start;
2901        active.end = end;
2902    }
2903
2904    /// Collapses the active selection to a cursor at the given offset,
2905    /// clearing `reversed`.
2906    pub(super) fn set_cursor_to(&mut self, offset: usize) {
2907        let offset = self.token_boundary(offset, Bias::Right);
2908        let active = self.active_selection_mut();
2909        active.start = offset;
2910        active.end = offset;
2911        active.reversed = false;
2912    }
2913
2914    /// Visible row range in the last laid-out viewport, `None` before first layout.
2915    pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
2916        self.last_layout.as_ref().map(|l| l.visible_range.clone())
2917    }
2918
2919    /// Current scroll offset of the editor viewport.
2920    pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
2921        self.scroll_handle.offset()
2922    }
2923
2924    /// Set scroll offset of the editor viewport.
2925    ///
2926    /// The offset will be clamped to the valid range, and applied after the next layout.
2927    pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
2928        self.deferred_scroll_offset = Some(offset);
2929        cx.notify();
2930    }
2931
2932    /// Laid-out line height; `None` before first layout.
2933    pub fn line_height(&self) -> Option<gpui::Pixels> {
2934        self.last_layout.as_ref().map(|l| l.line_height)
2935    }
2936
2937    /// Returns the active selection as a byte range into the text.
2938    ///
2939    /// With multiple cursors, this reads only the active selection.
2940    ///
2941    /// The range is empty (`start == end`) when no text is selected; in
2942    /// that case the offset equals `cursor()`. Byte offsets are measured
2943    /// in the underlying rope's byte units.
2944    pub fn selected_range(&self) -> std::ops::Range<usize> {
2945        (*self.selections.active()).into()
2946    }
2947
2948    pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
2949        self.undo_manager.break_transaction_coalescing();
2950        self.selections.remove_all_but_active();
2951        self.set_selection(0, self.text.len());
2952        cx.notify();
2953    }
2954
2955    /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
2956    ///
2957    /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
2958    /// clipped to the preceding character boundary.
2959    pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
2960        let range = self.normalize_token_range(range);
2961        let end_bias = if range.start == range.end {
2962            Bias::Left
2963        } else {
2964            Bias::Right
2965        };
2966        let start = self.text.clip_offset(range.start, Bias::Left);
2967        let end = self.text.clip_offset(range.end, end_bias);
2968
2969        self.move_to(start, None, cx);
2970        self.active_selection_mut().reversed = false;
2971        self.selected_word_range = None;
2972        self.select_to(end, cx);
2973    }
2974
2975    /// Resolve a mouse position to a byte offset in the text.
2976    ///
2977    /// Also reports the caret's line-end affinity for that offset: `true` when the position
2978    /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
2979    /// end of that row rather than at the start of the next one. Callers that place or extend a
2980    /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
2981    /// caret one row below the pointer.
2982    pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
2983        let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
2984        (offset, line_end_affinity)
2985    }
2986
2987    /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
2988    /// how many columns the pointer sits past the end of that row.
2989    ///
2990    /// Only a columnar selection needs the third value; everywhere else a position past
2991    /// the end of a row means the end of that row, and
2992    /// [`Self::index_for_mouse_position`] is the call to make.
2993    pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
2994        // If the text is empty, always return 0
2995        if self.text.len() == 0 {
2996            return (0, false, 0);
2997        }
2998
2999        let (Some(bounds), Some(last_layout)) =
3000            (self.last_bounds.as_ref(), self.last_layout.as_ref())
3001        else {
3002            return (0, false, 0);
3003        };
3004
3005        let line_height = last_layout.line_height;
3006        let line_number_width = last_layout.line_number_width;
3007
3008        // TIP: About the IBeam cursor
3009        //
3010        // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3011
3012        // The position is relative to the bounds of the text input
3013        //
3014        // bounds.origin:
3015        //
3016        // - included the input padding.
3017        // - included the scroll offset.
3018        let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3019
3020        let mut y_offset = last_layout.visible_top;
3021        // Position relative to the last line walked, kept for a pointer that ends up
3022        // below every line.
3023        let mut last_line_pos = None;
3024
3025        // Traverse visible buffer lines (compact, no hidden entries)
3026        for (vi, (line_layout, _buffer_line)) in last_layout
3027            .lines
3028            .iter()
3029            .zip(last_layout.visible_buffer_lines.iter())
3030            .enumerate()
3031        {
3032            let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3033
3034            // Calculate line origin for this display row
3035            let line_origin = point(px(0.), y_offset);
3036            let pos = inner_position - line_origin;
3037
3038            // Return offset by use closest_index_for_x if is single line mode.
3039            if self.is_single_line() {
3040                let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3041                // A single line never wraps, so there is no boundary to disambiguate.
3042                return (
3043                    self.resolve_index(line_start_offset + local_index),
3044                    false,
3045                    0,
3046                );
3047            }
3048
3049            // Check if mouse is in this line's bounds
3050            if let Some((local_index, line_end_affinity)) =
3051                line_layout.closest_index_for_position(pos, last_layout)
3052            {
3053                return (
3054                    self.resolve_index(line_start_offset + local_index),
3055                    line_end_affinity,
3056                    line_layout.columns_past_line_end(pos, last_layout),
3057                );
3058            } else if pos.y < px(0.) {
3059                // Mouse is above this line, return start of this line
3060                return (self.resolve_index(line_start_offset), false, 0);
3061            }
3062
3063            y_offset += line_layout.size(line_height).height;
3064            last_line_pos = Some(pos);
3065        }
3066
3067        // Clamp to the last laid-out row. Returning the end of the whole document
3068        // would select unseen text before drag autoscroll has reached it.
3069        let last_position = last_layout
3070            .lines
3071            .last()
3072            .zip(last_line_pos)
3073            .zip(last_layout.visible_line_byte_offsets.last())
3074            .map(|((line_layout, pos), line_start)| {
3075                let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
3076                let pos = point(pos.x, last_row_top);
3077                (
3078                    self.resolve_index(line_start + line_layout.len()),
3079                    false,
3080                    line_layout.columns_past_line_end(pos, last_layout),
3081                )
3082            });
3083
3084        last_position.unwrap_or((self.text.len(), false, 0))
3085    }
3086
3087    /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3088    /// is masked.
3089    fn resolve_index(&self, index: usize) -> usize {
3090        if self.masked {
3091            self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3092        } else {
3093            index.min(self.text.len())
3094        }
3095    }
3096
3097    /// Returns a y offsetted point for the line origin.
3098    /// Select the text from the current cursor position to the given offset.
3099    ///
3100    /// The offset is the UTF-8 offset.
3101    ///
3102    /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
3103    /// Extend a single selection so its moving end lands at `offset`, flipping
3104    /// `reversed` when the ends cross. When a sticky `word_range` is given the
3105    /// selection is kept covering it.
3106    fn extend_selection(
3107        sel: &mut CursorSelection,
3108        offset: usize,
3109        word_range: Option<CursorSelection>,
3110    ) {
3111        if sel.reversed {
3112            sel.start = offset;
3113        } else {
3114            sel.end = offset;
3115        }
3116
3117        if sel.end < sel.start {
3118            sel.reversed = !sel.reversed;
3119            std::mem::swap(&mut sel.start, &mut sel.end);
3120        }
3121
3122        if let Some(word_range) = word_range {
3123            if sel.start > word_range.start {
3124                sel.start = word_range.start;
3125            }
3126            if sel.end < word_range.end {
3127                sel.end = word_range.end;
3128            }
3129        }
3130    }
3131
3132    /// Extend only the active selection to `offset`. Used by mouse drag.
3133    pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
3134        self.select_to_with_affinity(offset, false, cx);
3135    }
3136
3137    /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
3138    ///
3139    /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
3140    /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
3141    /// the text rather than from a visual position, so the caret has no reason to keep sticking
3142    /// to the end of a wrapped row.
3143    pub(crate) fn select_to_with_affinity(
3144        &mut self,
3145        offset: usize,
3146        line_end_affinity: bool,
3147        cx: &mut Context<Self>,
3148    ) {
3149        M::clear_inline_completion(self, cx);
3150
3151        self.cursor_line_end_affinity = line_end_affinity;
3152        let offset = self.cursor_boundary(offset, Bias::Left);
3153        let word_range = self.selected_word_range;
3154        Self::extend_selection(self.active_selection_mut(), offset, word_range);
3155        let range = self.normalize_token_range(self.selected_range());
3156        self.set_selection(range.start, range.end);
3157
3158        if self.active_selection().is_empty() {
3159            self.update_preferred_column();
3160        }
3161        cx.notify()
3162    }
3163
3164    /// Extend every selection to the offset produced by `f`, then merge any
3165    /// selections that now overlap. Used by keyboard selection commands.
3166    fn select_all_cursors_to(
3167        &mut self,
3168        f: impl Fn(&Self, &CursorSelection) -> usize,
3169        cx: &mut Context<Self>,
3170    ) {
3171        self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
3172    }
3173
3174    /// Extend selections with caret affinity, preserving their column anchors even
3175    /// when vertical movement collapses a selection to a cursor.
3176    fn select_all_cursors_to_with_affinity(
3177        &mut self,
3178        f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
3179        preserve_column: bool,
3180        cx: &mut Context<Self>,
3181    ) {
3182        self.pause_blink_cursor(cx);
3183        self.undo_manager.break_transaction_coalescing();
3184        M::clear_inline_completion(self, cx);
3185
3186        let mut active_affinity = false;
3187        let new_selections: Vec<CursorSelection> = self
3188            .selections
3189            .iter()
3190            .map(|sel| {
3191                let (offset, affinity) = f(self, sel);
3192                if sel.id == self.active_selection().id {
3193                    active_affinity = affinity;
3194                }
3195                let offset = self.cursor_boundary(offset, Bias::Left);
3196                let mut new_sel = *sel;
3197                Self::extend_selection(&mut new_sel, offset, None);
3198                let range = self.normalize_token_range(new_sel.start..new_sel.end);
3199                new_sel.start = range.start;
3200                new_sel.end = range.end;
3201                if !preserve_column {
3202                    new_sel.column_anchor =
3203                        self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
3204                } else if new_sel.column_anchor.is_none() {
3205                    new_sel.column_anchor = self.preferred_column_for_with_affinity(
3206                        sel.cursor_offset(),
3207                        self.line_end_affinity_for(sel),
3208                    );
3209                }
3210                new_sel
3211            })
3212            .collect();
3213        self.cursor_line_end_affinity = active_affinity;
3214        self.selections.replace_all(new_selections);
3215        self.selections.merge_overlapping();
3216
3217        self.scroll_to(self.cursor(), None, cx);
3218        cx.notify()
3219    }
3220
3221    /// Unselects the currently selected text.
3222    pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3223        self.undo_manager.break_transaction_coalescing();
3224        let offset = self.cursor();
3225        self.set_cursor_to(offset);
3226        cx.notify()
3227    }
3228
3229    #[inline]
3230    pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
3231        self.text.offset_utf16_to_offset(offset)
3232    }
3233
3234    #[inline]
3235    pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
3236        self.text.offset_to_offset_utf16(offset)
3237    }
3238
3239    #[inline]
3240    pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
3241        self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
3242    }
3243
3244    #[inline]
3245    pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
3246        self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
3247    }
3248
3249    /// If offset falls on a hidden (folded) line, clamp backward to the end of
3250    /// the fold header line (last visible position before the fold).
3251    fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
3252        let line = self.text.offset_to_point(offset).row;
3253        if self.display_map.is_buffer_line_hidden(line) {
3254            for fold in self.display_map.folded_ranges() {
3255                if line > fold.start_line && line <= fold.end_line {
3256                    return self.text.line_end_offset(fold.start_line);
3257                }
3258            }
3259        }
3260        offset
3261    }
3262
3263    /// If offset falls on a hidden (folded) line, clamp forward to the start of
3264    /// the fold end line (first visible position after the fold).
3265    fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
3266        let line = self.text.offset_to_point(offset).row;
3267        if self.display_map.is_buffer_line_hidden(line) {
3268            for fold in self.display_map.folded_ranges() {
3269                if line > fold.start_line && line <= fold.end_line {
3270                    return self.text.line_start_offset(fold.end_line);
3271                }
3272            }
3273        }
3274        offset
3275    }
3276
3277    /// Clip a cursor/selection offset without splitting a CRLF newline. This does
3278    /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
3279    pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
3280        let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
3281        if offset > 0
3282            && self.text.char_at(offset - 1) == Some('\r')
3283            && self.text.char_at(offset) == Some('\n')
3284        {
3285            if bias == Bias::Left {
3286                offset - 1
3287            } else {
3288                offset + 1
3289            }
3290        } else {
3291            offset
3292        }
3293    }
3294
3295    pub(super) fn previous_boundary(&self, offset: usize) -> usize {
3296        let offset = self.cursor_boundary(offset.saturating_sub(1), Bias::Left);
3297        self.clamp_offset_to_visible_backward(offset)
3298    }
3299
3300    pub(super) fn next_boundary(&self, offset: usize) -> usize {
3301        let offset = self.cursor_boundary(offset.saturating_add(1), Bias::Right);
3302        self.clamp_offset_to_visible_forward(offset)
3303    }
3304
3305    /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
3306    pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
3307        (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
3308            && !self.disabled
3309            && self.blink_cursor.read(cx).visible()
3310            && window.is_window_active()
3311    }
3312
3313    fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3314        self.blink_cursor.update(cx, |cursor, cx| {
3315            cursor.start(cx);
3316        });
3317        cx.emit(InputEvent::Focus);
3318    }
3319
3320    fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3321        if M::is_context_menu_open(self, cx) {
3322            return;
3323        }
3324
3325        M::hide_context_menu(self, cx);
3326        self.undo_manager.break_transaction_coalescing();
3327
3328        // NOTE: Do not cancel select, when blur.
3329        // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
3330
3331        M::clear_hover_state(self, cx);
3332        self.diagnostic_popover = None;
3333        M::clear_inline_completion(self, cx);
3334        self.dismiss_touch_selection(cx);
3335        self.blink_cursor.update(cx, |cursor, cx| {
3336            cursor.stop(cx);
3337        });
3338        self.clamp_number_value(window, cx);
3339        cx.emit(InputEvent::Blur);
3340        cx.notify();
3341    }
3342
3343    /// Clamp the number value to the `min`/`max` range, used on blur.
3344    ///
3345    /// Out-of-range values are allowed while typing (e.g. `1` is an
3346    /// intermediate state of `15` when min is 10), and clamped on blur.
3347    fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3348        if !self.is_single_line() {
3349            return;
3350        }
3351        if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
3352            return;
3353        }
3354        if self.number_min.is_none() && self.number_max.is_none() {
3355            return;
3356        }
3357
3358        let Ok(value) = self.unmask_value().parse::<f64>() else {
3359            return;
3360        };
3361
3362        let clamped = match (self.number_min, self.number_max) {
3363            (Some(min), _) if value < min => min,
3364            (_, Some(max)) if value > max => max,
3365            _ => return,
3366        };
3367
3368        // The clamped value must pass the `pattern`/`validate` check,
3369        // otherwise keep the value as is.
3370        let new_text = clamped.to_string();
3371        if !self.is_valid_input(&new_text, cx) {
3372            return;
3373        }
3374
3375        let range = self.range_to_utf16(&(0..self.text.len()));
3376        self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
3377    }
3378
3379    pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
3380        self.blink_cursor.update(cx, |cursor, cx| {
3381            cursor.pause(cx);
3382        });
3383    }
3384
3385    pub(super) fn on_drag_move(
3386        &mut self,
3387        event: &MouseMoveEvent,
3388        window: &mut Window,
3389        cx: &mut Context<Self>,
3390    ) {
3391        if self.text.len() == 0 {
3392            return;
3393        }
3394
3395        if self.last_layout.is_none() {
3396            return;
3397        }
3398
3399        if !self.focus_handle.is_focused(window) {
3400            return;
3401        }
3402
3403        if !self.selecting {
3404            return;
3405        }
3406
3407        self.auto_scroll.last_drag_position = Some(event.position);
3408        let (offset, line_end_affinity, columns_past_line_end) =
3409            self.resolve_mouse_position(event.position);
3410        if let Some(start) = self.column_select_start {
3411            let end = ColumnarPoint::new(offset, columns_past_line_end);
3412            self.build_columnar_selection(start, end, cx);
3413        } else {
3414            self.select_to_with_affinity(offset, line_end_affinity, cx);
3415        }
3416
3417        if !self.is_single_line() {
3418            let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
3419            // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
3420            let scroll_delta = delta.map(|d| -d);
3421            self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
3422                let current = state.scroll_handle.offset();
3423                state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
3424                if let Some(pos) = state.auto_scroll.last_drag_position {
3425                    let (offset, line_end_affinity, columns_past_line_end) =
3426                        state.resolve_mouse_position(pos);
3427                    if let Some(start) = state.column_select_start {
3428                        let end = ColumnarPoint::new(offset, columns_past_line_end);
3429                        state.build_columnar_selection(start, end, cx);
3430                    } else {
3431                        state.select_to_with_affinity(offset, line_end_affinity, cx);
3432                    }
3433                }
3434            });
3435        }
3436    }
3437
3438    /// Normalize the inserted text before applying it to the input.
3439    ///
3440    /// For number inputs (with [`MaskPattern::Number`]), this converts
3441    /// full-width number characters into their ASCII equivalents,
3442    /// e.g. `12。5` -> `12.5`.
3443    pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
3444        let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
3445            normalize_number_input(new_text)
3446        } else {
3447            Cow::Borrowed(new_text)
3448        };
3449
3450        if self.is_single_line() && normalized.contains(['\n', '\r']) {
3451            Cow::Owned(normalized.replace(['\n', '\r'], ""))
3452        } else {
3453            normalized
3454        }
3455    }
3456
3457    pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
3458        if new_text.is_empty() {
3459            return true;
3460        }
3461
3462        if let Some(validate) = &self.validate {
3463            if !validate(new_text, cx) {
3464                return false;
3465            }
3466        }
3467
3468        if !self.mask_pattern.is_valid(new_text) {
3469            return false;
3470        }
3471
3472        let Some(pattern) = &self.pattern else {
3473            return true;
3474        };
3475
3476        pattern.is_match(new_text)
3477    }
3478
3479    /// Set the mask pattern for formatting the input text.
3480    ///
3481    /// The pattern can contain:
3482    /// - 9: Any digit or dot
3483    /// - A: Any letter
3484    /// - *: Any character
3485    /// - Other characters will be treated as literal mask characters
3486    ///
3487    /// Example: "(999)999-999" for phone numbers
3488    pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
3489        self.mask_pattern = pattern.into();
3490        self.mask_pattern_set = true;
3491        if let Some(placeholder) = self.mask_pattern.placeholder() {
3492            self.placeholder = placeholder.into();
3493        }
3494        self
3495    }
3496
3497    pub fn set_mask_pattern(
3498        &mut self,
3499        pattern: impl Into<MaskPattern>,
3500        _: &mut Window,
3501        cx: &mut Context<Self>,
3502    ) {
3503        self.mask_pattern = pattern.into();
3504        self.mask_pattern_set = true;
3505        if let Some(placeholder) = self.mask_pattern.placeholder() {
3506            self.placeholder = placeholder.into();
3507        }
3508        cx.notify();
3509    }
3510
3511    /// Apply the default numeric mask unless the caller explicitly selected a mask.
3512    pub fn ensure_number_mask(&mut self) {
3513        if self.mask_pattern_set {
3514            return;
3515        }
3516        self.mask_pattern = MaskPattern::Number {
3517            separator: None,
3518            fraction: None,
3519        };
3520    }
3521
3522    pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
3523        let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
3524        self.input_bounds = new_bounds;
3525
3526        // Update display_map wrap_width if changed.
3527        if let Some(last_layout) = self.last_layout.as_ref() {
3528            if wrap_width_changed {
3529                let wrap_width = if !self.soft_wrap {
3530                    // None to disable wrapping (will use Pixels::MAX)
3531                    None
3532                } else {
3533                    last_layout.wrap_width
3534                };
3535
3536                self.display_map.on_layout_changed(wrap_width, cx);
3537                if self.is_multi_line() {
3538                    self.mode.update_auto_grow(&self.display_map);
3539                }
3540                cx.notify();
3541            }
3542        }
3543    }
3544
3545    /// Return the active selection's text, borrowed out of the [`Rope`]
3546    /// the state owns.
3547    ///
3548    /// See [`Self::selected_value`] when an owned string is wanted.
3549    pub fn selected_text(&self) -> RopeSlice<'_> {
3550        let range_utf16 = self.range_to_utf16(&self.selected_range());
3551        let range = self.range_from_utf16(&range_utf16);
3552        self.text.slice(range)
3553    }
3554
3555    /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
3556    ///
3557    /// Returns `None` when the requested range is not currently laid out or visible.
3558    pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
3559        let Some(last_layout) = self.last_layout.as_ref() else {
3560            return None;
3561        };
3562
3563        let Some(last_bounds) = self.last_bounds else {
3564            return None;
3565        };
3566
3567        let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
3568        let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
3569
3570        let Some(start_pos) = start_pos else {
3571            return None;
3572        };
3573        let Some(end_pos) = end_pos else {
3574            return None;
3575        };
3576
3577        Some(Bounds::from_corners(
3578            last_bounds.origin + start_pos,
3579            last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
3580        ))
3581    }
3582
3583    /// Replace text in range in silent.
3584    ///
3585    /// This will not trigger any UI interaction, such as auto-completion.
3586    pub(crate) fn replace_text_in_range_silent(
3587        &mut self,
3588        range_utf16: Option<Range<usize>>,
3589        new_text: &str,
3590        window: &mut Window,
3591        cx: &mut Context<Self>,
3592    ) {
3593        self.silent_replace_text = true;
3594        self.replace_text_in_range(range_utf16, new_text, window, cx);
3595        self.silent_replace_text = false;
3596    }
3597
3598    /// Apply a batch of edits as one atomic history transaction.
3599    ///
3600    /// `edits` are `(byte range in the current pre-edit document, replacement)`
3601    /// pairs.
3602    pub(crate) fn replace_text_in_ranges(
3603        &mut self,
3604        edits: &[(Range<usize>, String)],
3605        window: &mut Window,
3606        cx: &mut Context<Self>,
3607    ) {
3608        if !self.is_editable() || edits.is_empty() {
3609            return;
3610        }
3611
3612        // Every edit invalidates provider responses for the previous document,
3613        // including deletion and indentation which do not trigger completion.
3614        M::hide_context_menu(self, cx);
3615        M::clear_inline_completion(self, cx);
3616
3617        // Sort descending by start so applying front-of-vec first edits the
3618        // highest offsets first, leaving lower offsets unchanged.
3619        let mut sorted: Vec<(Range<usize>, &str)> = edits
3620            .iter()
3621            .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
3622            .collect();
3623        sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
3624        if !self.token_spans().is_empty() {
3625            let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
3626            for (range, text) in sorted {
3627                if let Some(last) = merged
3628                    .last_mut()
3629                    .filter(|last| range.end > last.0.start || range == last.0)
3630                {
3631                    last.0.start = range.start.min(last.0.start);
3632                    last.0.end = range.end.max(last.0.end);
3633                } else {
3634                    merged.push((range, text));
3635                }
3636            }
3637            sorted = merged;
3638        }
3639
3640        #[cfg(debug_assertions)]
3641        for pair in sorted.windows(2) {
3642            debug_assert!(
3643                pair[1].0.end <= pair[0].0.start,
3644                "replace_text_in_ranges requires disjoint ranges"
3645            );
3646        }
3647
3648        // Wrap multiple edits in one explicit transaction so they undo as a
3649        // unit. A single edit records directly, which keeps it eligible for
3650        // the undo manager's typing coalescing.
3651        let requested_intent = self.undo_manager.take_pending_intent();
3652        let selection_before = *self.active_selection();
3653        let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3654        // Snapshot the cursors before applying, so undo can restore them. A
3655        // delete has already expanded them over the text it removes, so they
3656        // collapse back to where the user left them.
3657        let selections_before: Vec<CursorSelection> = self
3658            .selections
3659            .iter()
3660            .map(|selection| {
3661                Self::collapse_for_intent(
3662                    requested_intent.unwrap_or(EditIntent::Atomic),
3663                    *selection,
3664                    &(selection.start..selection.end),
3665                )
3666            })
3667            .collect();
3668        let group = sorted.len() > 1;
3669        if group {
3670            self.undo_manager.begin_transaction();
3671        }
3672
3673        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
3674        let mut recorded = false;
3675        // Several edits reach the highlighter as one batch, so it reparses
3676        // once for the change instead of once per edit.
3677        let mut highlighter_edits = Vec::new();
3678        for (range, new_text) in &sorted {
3679            let old_text = self.text.clone();
3680            self.mode.adjust_auto_closed_pair(range, new_text.len());
3681            self.text.replace(range.clone(), new_text);
3682
3683            M::adjust_annotations(self, range, new_text.len());
3684            recorded |= self.push_history(
3685                &old_text,
3686                range,
3687                new_text,
3688                requested_intent,
3689                selection_before,
3690                None,
3691            );
3692
3693            // Incremental, single-range updates must run per edit.
3694            self.display_map
3695                .adjust_folds_for_edit(&old_text, range, new_text);
3696            self.display_map
3697                .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
3698
3699            if group {
3700                if self.is_code_editor() {
3701                    let edit =
3702                        super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
3703                    highlighter_edits.push((edit, self.text.clone()));
3704                }
3705            } else {
3706                self.mode.update_highlighter(
3707                    super::mode::HighlighterUpdate {
3708                        selected_range: range,
3709                        old_text: &old_text,
3710                        new_text: &self.text,
3711                        change_text: new_text,
3712                        force: true,
3713                    },
3714                    window,
3715                    cx,
3716                );
3717
3718                self.update_fold_candidates_incremental(range, new_text);
3719            }
3720        }
3721
3722        if group {
3723            self.mode
3724                .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
3725
3726            // Fold candidates are read from the reparsed document, so each
3727            // edit is located where it ended up once every edit was applied.
3728            // `sorted` runs from the highest offset down.
3729            let mut shift = 0isize;
3730            for (range, new_text) in sorted.iter().rev() {
3731                let start = (range.start as isize + shift) as usize;
3732                self.update_fold_candidates_incremental(&(start..start), new_text);
3733                shift += new_text.len() as isize - range.len() as isize;
3734            }
3735
3736            self.undo_manager.commit_transaction();
3737        }
3738
3739        // One observable update per batch instead of one per edit.
3740        if let Some(diagnostics) = self.mode.diagnostics_mut() {
3741            diagnostics.reset(&self.text)
3742        }
3743        M::refresh_language_features(self, window, cx);
3744        self.update_search(cx);
3745
3746        // Compute the resulting cursors.
3747        // One collapsed cursor per edit, at the end of its inserted text.
3748        let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
3749        ascending.sort_by_key(|edit| edit.0.start);
3750        let text_len = self.text.len();
3751        let mut delta: isize = 0;
3752        let mut edit_results = Vec::with_capacity(ascending.len());
3753        for (range, new_text) in &ascending {
3754            let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
3755            edit_results.push((range.clone(), offset));
3756            delta += new_text.len() as isize - (range.end as isize - range.start as isize);
3757        }
3758
3759        let mut used = vec![false; edit_results.len()];
3760        let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
3761        for selection in original_selections {
3762            if let Ok(index) = edit_results
3763                .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
3764                    (range.start, range.end)
3765                })
3766                && !used[index]
3767            {
3768                let offset = edit_results[index].1;
3769                used[index] = true;
3770                let mut selection = selection;
3771                selection.place_at(offset, None);
3772                new_selections.push(selection);
3773            }
3774        }
3775        for (index, (_, offset)) in edit_results.into_iter().enumerate() {
3776            if !used[index] {
3777                new_selections.push(CursorSelection::new(
3778                    self.selections.generate_id(),
3779                    offset,
3780                    offset,
3781                ));
3782            }
3783        }
3784        self.selections.replace_all(new_selections);
3785        self.selections.merge_overlapping();
3786
3787        // Record the cursor snapshots for undo/redo restore.
3788        let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
3789        if recorded {
3790            self.undo_manager.record_auto_closed_pairs(
3791                auto_closed_pairs_before,
3792                self.mode.auto_closed_pairs().clone(),
3793            );
3794            self.undo_manager
3795                .record_selections(selections_before, selections_after);
3796        }
3797
3798        self.ime_marked_range.take();
3799        self.update_preferred_column();
3800        self.dismiss_touch_selection(cx);
3801        if self.is_multi_line() {
3802            self.mode.update_auto_grow(&self.display_map);
3803        }
3804        if self.emit_events {
3805            cx.emit(InputEvent::Change);
3806        }
3807        cx.notify();
3808    }
3809
3810    /// Update fold candidates from tree-sitter syntax tree (full extraction).
3811    /// Used only on initial load or language changes.
3812    fn update_fold_candidates(&mut self) {
3813        if !self.mode.is_folding() {
3814            return;
3815        }
3816
3817        let Some(highlighter_rc) = self.mode.highlighter() else {
3818            return;
3819        };
3820
3821        let highlighter = highlighter_rc.borrow();
3822        let Some(highlighter) = highlighter.as_ref() else {
3823            return;
3824        };
3825
3826        let fold_ranges = highlighter.fold_ranges(&self.text);
3827        self.display_map.set_fold_candidates(fold_ranges);
3828    }
3829
3830    /// Incrementally update fold candidates after a text edit.
3831    /// Only traverses the edited region of the syntax tree instead of the full tree.
3832    fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
3833        if !self.mode.is_folding() {
3834            return;
3835        }
3836
3837        let Some(highlighter_rc) = self.mode.highlighter() else {
3838            return;
3839        };
3840
3841        let highlighter = highlighter_rc.borrow();
3842        let Some(highlighter) = highlighter.as_ref() else {
3843            return;
3844        };
3845
3846        // The new byte range in the updated text after the edit
3847        let new_end = edit_range.start + new_text.len();
3848        self.display_map.update_fold_candidates_for_edit(
3849            |range, text| highlighter.fold_ranges_for_edit(range, text),
3850            edit_range.start..new_end,
3851            &self.text,
3852        );
3853    }
3854}
3855
3856impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
3857    fn text_for_range(
3858        &mut self,
3859        range_utf16: Range<usize>,
3860        adjusted_range: &mut Option<Range<usize>>,
3861        _window: &mut Window,
3862        _cx: &mut Context<Self>,
3863    ) -> Option<String> {
3864        let range = self.range_from_utf16(&range_utf16);
3865        adjusted_range.replace(self.range_to_utf16(&range));
3866        Some(self.text.slice(range).to_string())
3867    }
3868
3869    fn selected_text_range(
3870        &mut self,
3871        _ignore_disabled_input: bool,
3872        _window: &mut Window,
3873        _cx: &mut Context<Self>,
3874    ) -> Option<UTF16Selection> {
3875        Some(UTF16Selection {
3876            range: self.range_to_utf16(&self.selected_range()),
3877            reversed: self.active_selection().reversed,
3878        })
3879    }
3880
3881    fn marked_text_range(
3882        &self,
3883        _window: &mut Window,
3884        _cx: &mut Context<Self>,
3885    ) -> Option<Range<usize>> {
3886        self.ime_marked_range
3887            .map(|range| self.range_to_utf16(&range.into()))
3888    }
3889
3890    fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
3891        self.ime_marked_range = None;
3892        self.undo_manager.commit_transaction();
3893    }
3894
3895    /// Replace text in range.
3896    ///
3897    /// - If the new text is invalid, it will not be replaced.
3898    /// - If `range_utf16` is not provided, the current selected range will be used.
3899    fn replace_text_in_range(
3900        &mut self,
3901        range_utf16: Option<Range<usize>>,
3902        new_text: &str,
3903        window: &mut Window,
3904        cx: &mut Context<Self>,
3905    ) {
3906        let requested_intent = self.undo_manager.take_pending_intent();
3907        if !self.is_editable() {
3908            return;
3909        }
3910        let selection_before = *self.active_selection();
3911        // Committing a composition ends the transaction it opened, whether or
3912        // not the platform follows up with `unmark_text`.
3913        let ends_composition = self.ime_marked_range.is_some();
3914
3915        self.pause_blink_cursor(cx);
3916
3917        // NOTE: The normalization keeps the UTF-16 length, but may change the
3918        // UTF-8 byte length, so all the byte-offset calculations below must
3919        // use the normalized text.
3920        let new_text = if self.replaying_history {
3921            Cow::Borrowed(new_text)
3922        } else {
3923            self.normalize_input(new_text)
3924        };
3925        let new_text: &str = &new_text;
3926
3927        let range = range_utf16
3928            .as_ref()
3929            .map(|range_utf16| self.range_from_utf16(range_utf16))
3930            .or(self.ime_marked_range.map(|range| {
3931                let range = self.range_to_utf16(&(range.start..range.end));
3932                self.range_from_utf16(&range)
3933            }))
3934            .unwrap_or(self.selected_range());
3935        let range = self.normalize_token_range(range);
3936
3937        // Skip-over as a pure cursor move: a typed closer that already follows
3938        // the cursor moves past it without touching text or history, so Undo
3939        // never exposes a transient duplicate. Only for interactive single
3940        // keystrokes (current selection, no IME mark, not silent replays).
3941        // `take_pending_intent` above already consumed any request.
3942        if range.is_empty()
3943            && range.start == self.cursor()
3944            && self.ime_marked_range.is_none()
3945            && !self.silent_replace_text
3946            && self.is_code_editor()
3947            && self.selections.is_single()
3948            && self.active_selection().is_empty()
3949        {
3950            if let Some(target) = self.skip_over_target(new_text) {
3951                self.set_cursor_to(target);
3952                self.update_preferred_column();
3953                cx.notify();
3954                return;
3955            }
3956        }
3957
3958        if self.is_multi_line() {
3959            let multi_cursor = range_utf16.is_none()
3960                && self.ime_marked_range.is_none()
3961                && !self.selections.is_single();
3962            if multi_cursor {
3963                self.selections.merge_overlapping();
3964                let mut edits: Vec<(Range<usize>, String)> = self
3965                    .selections
3966                    .iter()
3967                    .map(|sel| (sel.start..sel.end, new_text.to_string()))
3968                    .collect();
3969                edits.sort_by_key(|(range, _)| range.start);
3970                // One keystroke across several cursors is one batch, committed
3971                // with the intent of the keystroke so a run of them coalesces
3972                // into one undo just like single-cursor typing.
3973                let intent =
3974                    requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
3975                self.undo_manager.begin_transaction_with(intent);
3976                self.undo_manager.set_pending_intent(intent);
3977                self.replace_text_in_ranges(&edits, window, cx);
3978                self.undo_manager.commit_transaction();
3979            } else {
3980                if range_utf16.is_some() {
3981                    self.selections.remove_all_but_active();
3982                }
3983                if let Some(intent) = requested_intent {
3984                    self.undo_manager.set_pending_intent(intent);
3985                }
3986                if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
3987                    // One edit keeps the pair atomic even at undo coalescing limits.
3988                    let replacement = format!("{new_text}{closer}");
3989                    self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
3990                    let cursor = range.start + new_text.len();
3991                    self.mode.track_auto_closed_pair(
3992                        cursor - open_len..cursor,
3993                        cursor..cursor + closer.len(),
3994                    );
3995                    self.undo_manager
3996                        .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
3997                    self.set_cursor_to(cursor);
3998                    self.update_preferred_column();
3999                    self.undo_manager.record_selections(
4000                        vec![selection_before],
4001                        self.selections.iter().copied().collect(),
4002                    );
4003                } else {
4004                    self.replace_text_in_ranges(
4005                        &[(range.clone(), new_text.to_string())],
4006                        window,
4007                        cx,
4008                    );
4009                }
4010            }
4011            if ends_composition {
4012                self.undo_manager.commit_transaction();
4013            }
4014
4015            if !self.silent_replace_text {
4016                M::on_text_typed(self, &range, new_text, window, cx);
4017            }
4018            return;
4019        }
4020
4021        // Single-line path
4022        let old_text = self.text.clone();
4023        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4024        self.text.replace(range.clone(), new_text);
4025
4026        let mut new_offset = (range.start + new_text.len()).min(self.text.len());
4027
4028        // True if the mask has changed the text, e.g. regrouping the
4029        // separators or completing a leading dot.
4030        let mut mask_changed = false;
4031
4032        if self.is_single_line() {
4033            let pending_text = self.text.to_string();
4034            // Check if the new text is valid.
4035            //
4036            // Only reject the edit if the old text was valid, to avoid
4037            // trapping a pre-existing invalid text (e.g. a `default_value`
4038            // that does not conform), the user can still edit to fix it.
4039            if !self.replaying_history
4040                && !self.validated_token_edit
4041                && !self.is_valid_input(&pending_text, cx)
4042                && self.is_valid_input(&old_text.to_string(), cx)
4043            {
4044                self.text = old_text;
4045                return;
4046            }
4047
4048            if !self.replaying_history && !self.mask_pattern.is_none() {
4049                let mask_text = self.mask_pattern.mask(&pending_text);
4050                mask_changed = mask_text.as_str() != pending_text;
4051                self.text = Rope::from(mask_text.as_str());
4052                let new_text_len =
4053                    (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
4054                new_offset = (range.start + new_text_len).min(mask_text.len());
4055            }
4056        }
4057
4058        if mask_changed {
4059            // Masking rewrites the whole document, so ranges recorded against
4060            // the old text no longer point at anything.
4061            M::reset_annotations(self);
4062        } else {
4063            M::adjust_annotations(self, &range, new_text.len());
4064        }
4065        if mask_changed {
4066            // A segment-based history entry no longer matches the masked
4067            // document, record a whole-document change instead, so that
4068            // undo/redo can restore the text exactly.
4069            self.push_history(
4070                &old_text,
4071                &(0..old_text.len()),
4072                &self.text.to_string(),
4073                Some(EditIntent::Atomic),
4074                selection_before,
4075                Some((new_offset..new_offset).into()),
4076            );
4077        } else {
4078            self.push_history(
4079                &old_text,
4080                &range,
4081                &new_text,
4082                requested_intent,
4083                selection_before,
4084                None,
4085            );
4086        }
4087        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4088            diagnostics.reset(&self.text)
4089        }
4090        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4091        self.display_map
4092            .adjust_folds_for_edit(&old_text, &range, new_text);
4093        self.display_map
4094            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4095
4096        self.mode.update_highlighter::<M>(
4097            super::mode::HighlighterUpdate {
4098                selected_range: &range,
4099                old_text: &old_text,
4100                new_text: &self.text,
4101                change_text: &new_text,
4102                force: true,
4103            },
4104            window,
4105            cx,
4106        );
4107
4108        self.update_fold_candidates_incremental(&range, new_text);
4109        M::refresh_language_features(self, window, cx);
4110        self.set_cursor_to(new_offset);
4111        self.ime_marked_range.take();
4112        // A commit ends the IME composition: macOS delivers `insertText:` for
4113        // the confirmed candidate without a following `unmarkText`, so close
4114        // the transaction here. Leaving it open would keep merging every later
4115        // edit into the same change, which then carries the text and selection
4116        // of the first composition.
4117        if ends_composition {
4118            self.undo_manager
4119                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4120            self.undo_manager.commit_transaction();
4121        }
4122        self.update_preferred_column();
4123        self.update_search(cx);
4124        self.dismiss_touch_selection(cx);
4125        if self.is_multi_line() {
4126            self.mode.update_auto_grow(&self.display_map);
4127        }
4128        if !self.silent_replace_text {
4129            M::on_text_typed(self, &range, &new_text, window, cx);
4130        }
4131        if self.emit_events {
4132            cx.emit(InputEvent::Change);
4133        }
4134        cx.notify();
4135    }
4136
4137    /// Mark text is the IME temporary insert on typing.
4138    fn replace_and_mark_text_in_range(
4139        &mut self,
4140        range_utf16: Option<Range<usize>>,
4141        new_text: &str,
4142        new_selected_range_utf16: Option<Range<usize>>,
4143        window: &mut Window,
4144        cx: &mut Context<Self>,
4145    ) {
4146        let requested_intent = self.undo_manager.take_pending_intent();
4147        if !self.is_editable() {
4148            return;
4149        }
4150        let selection_before = *self.active_selection();
4151
4152        let starts_composition = self.ime_marked_range.is_none();
4153        if starts_composition {
4154            // Even a canceled preedit separates the typing gestures on either
4155            // side; its no-op transaction must not reconnect those gestures.
4156            self.undo_manager.break_transaction_coalescing();
4157            self.undo_manager.begin_transaction();
4158        }
4159
4160        // Collapse any extra cursors so we never leave stale secondary cursors behind.
4161        self.selections.remove_all_but_active();
4162
4163        M::reset_language_features(self);
4164
4165        // See the same NOTE in `replace_text_in_range`.
4166        let new_text = if self.replaying_history {
4167            Cow::Borrowed(new_text)
4168        } else {
4169            self.normalize_input(new_text)
4170        };
4171        let new_text: &str = &new_text;
4172
4173        let range = range_utf16
4174            .as_ref()
4175            .map(|range_utf16| self.range_from_utf16(range_utf16))
4176            .or(self.ime_marked_range.map(|range| {
4177                let range = self.range_to_utf16(&(range.start..range.end));
4178                self.range_from_utf16(&range)
4179            }))
4180            .unwrap_or(self.selected_range());
4181        let range = self.normalize_token_range(range);
4182
4183        let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4184        let old_text = self.text.clone();
4185        self.mode.adjust_auto_closed_pair(&range, new_text.len());
4186        self.text.replace(range.clone(), new_text);
4187
4188        if self.is_single_line() {
4189            let pending_text = self.text.to_string();
4190            // See the same NOTE in `replace_text_in_range`.
4191            if !self.replaying_history
4192                && !self.validated_token_edit
4193                && !self.is_valid_input(&pending_text, cx)
4194                && self.is_valid_input(&old_text.to_string(), cx)
4195            {
4196                self.text = old_text;
4197                if starts_composition {
4198                    self.undo_manager.commit_transaction();
4199                }
4200                return;
4201            }
4202        }
4203
4204        M::adjust_annotations(self, &range, new_text.len());
4205        if let Some(diagnostics) = self.mode.diagnostics_mut() {
4206            diagnostics.reset(&self.text)
4207        }
4208        // Adjust folds before updating wrap map: remove overlapping folds and shift others
4209        self.display_map
4210            .adjust_folds_for_edit(&old_text, &range, new_text);
4211        self.display_map
4212            .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4213
4214        self.mode.update_highlighter::<M>(
4215            super::mode::HighlighterUpdate {
4216                selected_range: &range,
4217                old_text: &old_text,
4218                new_text: &self.text,
4219                change_text: &new_text,
4220                force: true,
4221            },
4222            window,
4223            cx,
4224        );
4225
4226        self.update_fold_candidates_incremental(&range, new_text);
4227        M::refresh_language_features(self, window, cx);
4228        if new_text.is_empty() {
4229            // Cancel selection, when cancel IME input.
4230            self.set_cursor_to(range.start);
4231            self.ime_marked_range = None;
4232        } else {
4233            self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
4234            let new_range = new_selected_range_utf16
4235                .as_ref()
4236                .map(|range_utf16| {
4237                    let new_text = Rope::from(new_text);
4238                    range.start + new_text.offset_utf16_to_offset(range_utf16.start)
4239                        ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
4240                })
4241                .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
4242            self.set_selection(new_range.start, new_range.end);
4243        }
4244        if self.is_multi_line() {
4245            self.mode.update_auto_grow(&self.display_map);
4246        }
4247        if self.push_history(
4248            &old_text,
4249            &range,
4250            new_text,
4251            requested_intent,
4252            selection_before,
4253            Some(*self.active_selection()),
4254        ) {
4255            self.undo_manager
4256                .record_selections(vec![selection_before], vec![*self.active_selection()]);
4257            self.undo_manager.record_auto_closed_pairs(
4258                auto_closed_pairs_before,
4259                self.mode.auto_closed_pairs().clone(),
4260            );
4261        }
4262        if new_text.is_empty() {
4263            self.undo_manager.commit_transaction();
4264        }
4265        cx.notify();
4266    }
4267
4268    /// Used to position IME candidates.
4269    fn bounds_for_range(
4270        &mut self,
4271        range_utf16: Range<usize>,
4272        bounds: Bounds<Pixels>,
4273        _window: &mut Window,
4274        _cx: &mut Context<Self>,
4275    ) -> Option<Bounds<Pixels>> {
4276        let last_layout = self.last_layout.as_ref()?;
4277        let line_height = last_layout.line_height;
4278        let line_number_width = last_layout.line_number_width;
4279        let range = self.range_from_utf16(&range_utf16);
4280
4281        let mut start_origin = None;
4282        let mut end_origin = None;
4283        let line_number_origin = point(line_number_width, px(0.));
4284        let mut y_offset = last_layout.visible_top;
4285
4286        for (vi, line) in last_layout.lines.iter().enumerate() {
4287            if start_origin.is_some() && end_origin.is_some() {
4288                break;
4289            }
4290
4291            let index_offset = last_layout.visible_line_byte_offsets[vi];
4292
4293            if start_origin.is_none() {
4294                if let Some(p) = line.position_for_index(
4295                    range.start.saturating_sub(index_offset),
4296                    last_layout,
4297                    false,
4298                ) {
4299                    start_origin = Some(p + point(px(0.), y_offset));
4300                }
4301            }
4302
4303            if end_origin.is_none() {
4304                if let Some(p) = line.position_for_index(
4305                    range.end.saturating_sub(index_offset),
4306                    last_layout,
4307                    false,
4308                ) {
4309                    end_origin = Some(p + point(px(0.), y_offset));
4310                }
4311            }
4312
4313            y_offset += line.size(line_height).height;
4314        }
4315
4316        let start_origin = start_origin.unwrap_or_default();
4317        let mut end_origin = end_origin.unwrap_or_default();
4318        // Ensure at same line.
4319        end_origin.y = start_origin.y;
4320
4321        Some(Bounds::from_corners(
4322            bounds.origin + line_number_origin + start_origin,
4323            // + line_height for show IME panel under the cursor line.
4324            bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + line_height),
4325        ))
4326    }
4327
4328    fn character_index_for_point(
4329        &mut self,
4330        point: gpui::Point<Pixels>,
4331        _window: &mut Window,
4332        _cx: &mut Context<Self>,
4333    ) -> Option<usize> {
4334        let last_layout = self.last_layout.as_ref()?;
4335        let line_point = self.last_bounds?.localize(&point)?;
4336
4337        for (vi, line) in last_layout.lines.iter().enumerate() {
4338            let offset = last_layout.visible_line_byte_offsets[vi];
4339            if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
4340                return Some(self.offset_to_utf16(offset + utf8_index));
4341            }
4342        }
4343
4344        None
4345    }
4346}
4347
4348impl<M: InputModeKind> Focusable for InputBaseState<M> {
4349    fn focus_handle(&self, _cx: &App) -> FocusHandle {
4350        self.focus_handle.clone()
4351    }
4352}
4353
4354impl<M: InputModeKind> Render for InputBaseState<M> {
4355    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4356        // Before anything reads it: the element resolves this style during
4357        // layout and paint, and both happen after this call in the same frame.
4358        self.editor_style = self
4359            .projected_editor_style
4360            .resolved(&crate::Theme::global(cx).tokens);
4361        let entity = cx.entity();
4362        if self._pending_update {
4363            self.mode.update_highlighter::<M>(
4364                super::mode::HighlighterUpdate {
4365                    selected_range: &(0..0),
4366                    old_text: &self.text,
4367                    new_text: &self.text,
4368                    change_text: "",
4369                    force: false,
4370                },
4371                window,
4372                cx,
4373            );
4374
4375            self.update_fold_candidates();
4376            M::refresh_language_features(self, window, cx);
4377            self._pending_update = false;
4378        }
4379
4380        let element = div()
4381            .id("input-state")
4382            .key_context(CONTEXT)
4383            .track_focus(&self.focus_handle)
4384            .when(self.is_editable(), |this| {
4385                this.on_action(window.listener_for(&entity, InputBaseState::backspace))
4386                    .on_action(window.listener_for(&entity, InputBaseState::delete))
4387                    .on_action(
4388                        window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
4389                    )
4390                    .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
4391                    .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
4392                    .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
4393                    .on_action(window.listener_for(&entity, InputBaseState::enter))
4394                    .on_action(window.listener_for(&entity, InputBaseState::escape))
4395                    .on_action(window.listener_for(&entity, InputBaseState::paste))
4396                    .on_action(window.listener_for(&entity, InputBaseState::cut))
4397                    .on_action(window.listener_for(&entity, InputBaseState::undo))
4398                    .on_action(window.listener_for(&entity, InputBaseState::redo))
4399                    .when(self.is_multi_line(), |this| {
4400                        this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
4401                            .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
4402                            .on_action(window.listener_for(&entity, InputBaseState::indent_block))
4403                            .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
4404                    })
4405            })
4406            .on_action(window.listener_for(&entity, InputBaseState::left))
4407            .on_action(window.listener_for(&entity, InputBaseState::right))
4408            .on_action(window.listener_for(&entity, InputBaseState::select_left))
4409            .on_action(window.listener_for(&entity, InputBaseState::select_right))
4410            .when(self.is_multi_line(), |this| {
4411                this.on_action(window.listener_for(&entity, InputBaseState::up))
4412                    .on_action(window.listener_for(&entity, InputBaseState::down))
4413                    .on_action(window.listener_for(&entity, InputBaseState::select_up))
4414                    .on_action(window.listener_for(&entity, InputBaseState::select_down))
4415                    .on_action(window.listener_for(&entity, InputBaseState::page_up))
4416                    .on_action(window.listener_for(&entity, InputBaseState::page_down))
4417                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
4418                    .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
4419            })
4420            .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
4421            .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
4422            .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
4423            .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
4424            .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
4425            .on_action(window.listener_for(&entity, InputBaseState::home))
4426            .on_action(window.listener_for(&entity, InputBaseState::end))
4427            .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
4428            .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
4429            .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
4430            .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
4431            .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
4432            .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
4433            .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
4434            .on_action({
4435                let entity = entity.clone();
4436                move |_: &ActivateToken, window, cx| {
4437                    let state = entity.read(cx);
4438                    let activation = state
4439                        .token_spans()
4440                        .iter()
4441                        .find(|span| span.range() == state.selected_range())
4442                        .and_then(|span| {
4443                            state.range_to_bounds(&span.range()).and_then(|bounds| {
4444                                state.token_activation(
4445                                    span.range().start,
4446                                    bounds,
4447                                    gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
4448                                        bounds,
4449                                        ..Default::default()
4450                                    }),
4451                                )
4452                            })
4453                        });
4454                    if let Some((listener, event)) = activation {
4455                        listener(&event, window, cx);
4456                    }
4457                }
4458            })
4459            .on_action(window.listener_for(&entity, InputBaseState::copy))
4460            .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
4461            .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
4462            .on_mouse_down(
4463                MouseButton::Left,
4464                window.listener_for(&entity, InputBaseState::on_mouse_down),
4465            )
4466            .on_mouse_down(
4467                MouseButton::Right,
4468                window.listener_for(&entity, InputBaseState::on_mouse_down),
4469            )
4470            .on_mouse_up(
4471                MouseButton::Left,
4472                window.listener_for(&entity, InputBaseState::on_mouse_up),
4473            )
4474            .on_mouse_up(
4475                MouseButton::Right,
4476                window.listener_for(&entity, InputBaseState::on_mouse_up),
4477            )
4478            .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
4479            .on_scroll_wheel(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
4480            .when(self.is_multi_line() && !self.disabled, |this| {
4481                this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
4482            })
4483            .when(!self.disabled, |this| {
4484                if self.is_multi_line() && window.modifiers().alt {
4485                    this.cursor_crosshair()
4486                } else {
4487                    this.cursor_text()
4488                }
4489            })
4490            .flex_1()
4491            .h_full()
4492            // A single line fills the frame and sits at its vertical center,
4493            // so the frame needs no layout of its own to hold it.
4494            .when(!self.is_multi_line(), |this| this.flex().items_center())
4495            .flex_grow_1()
4496            .overflow_x_hidden()
4497            .when(self.is_multi_line(), |this| {
4498                this.pt(self.editor_paddings.top)
4499                    .pr(self.editor_paddings.right)
4500                    .pb(self.editor_paddings.bottom)
4501                    .pl(self.editor_paddings.left)
4502            })
4503            .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
4504            .when(self.shows_scrollbar(), |this| {
4505                this.child(EditorScrollbar::new(entity.clone()))
4506            });
4507
4508        // Actions only one mode handles are registered by that mode, where
4509        // `Self` is concrete enough to name its own entity type.
4510        M::register_actions(element, &entity, window)
4511    }
4512}
4513
4514#[cfg(test)]
4515mod tests {
4516    use super::*;
4517    #[gpui::test]
4518    fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
4519        use crate::input::{InlineToken, InlineTokenPresentation};
4520        let width = Rc::new(Cell::new(4000.));
4521        let render_width = width.clone();
4522        let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
4523        view.window_handle
4524            .update(cx, |_, window, cx| {
4525                view.input.update(cx, |state, cx| {
4526                    state
4527                        .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
4528                        .unwrap();
4529                    state
4530                        .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
4531                        .unwrap();
4532                    state.set_token_presentation(
4533                        InlineTokenPresentation::default()
4534                            .token(move |_, _, _| div().w(px(render_width.get()))),
4535                    );
4536                });
4537            })
4538            .unwrap();
4539        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4540        visual.update(|window, cx| window.draw(cx).clear(cx));
4541        view.input.read_with(&visual, |state, _| {
4542            assert_eq!(state.display_map.wrap_row_count(), 2);
4543            let first = state.range_to_bounds(&(0..2)).unwrap();
4544            let second = state.range_to_bounds(&(2..4)).unwrap();
4545            assert!(second.origin.y > first.origin.y);
4546            assert_eq!(
4547                state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
4548                2
4549            );
4550        });
4551        width.set(100.);
4552        view.input.update(&mut visual, |_, cx| cx.notify());
4553        visual.update(|window, cx| window.draw(cx).clear(cx));
4554        view.input.read_with(&visual, |state, _| {
4555            assert_eq!(state.display_map.wrap_row_count(), 1)
4556        });
4557    }
4558
4559    #[gpui::test]
4560    fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
4561        use crate::input::{InlineToken, InlineTokenPresentation};
4562        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
4563        let target = view.input.clone();
4564        view.window_handle
4565            .update(cx, |_, window, cx| {
4566                view.input.update(cx, |state, cx| {
4567                    state
4568                        .replace_range_with_token(
4569                            7..13,
4570                            InlineToken::new("a", "@alice"),
4571                            window,
4572                            cx,
4573                        )
4574                        .unwrap();
4575                    state.set_token_presentation(
4576                        InlineTokenPresentation::default()
4577                            .token(|_, _, _| div().w(px(100.)).h(px(20.)))
4578                            .on_token_click(move |_, window, cx| {
4579                                target.update(cx, |state, cx| {
4580                                    state.set_value("activated", window, cx)
4581                                })
4582                            }),
4583                    );
4584                    state.focus(window, cx);
4585                    state.set_selected_range(7..13, cx);
4586                });
4587            })
4588            .unwrap();
4589        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4590        visual.update(|window, cx| window.draw(cx).clear(cx));
4591        visual.update(|window, cx| {
4592            let state = view.input.read(cx);
4593            let bounds = state.range_to_bounds(&(7..13)).unwrap();
4594            assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
4595            let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
4596            let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
4597            assert_eq!((left, right), (7, 13));
4598            window.dispatch_action(Box::new(ActivateToken), cx);
4599        });
4600        visual.run_until_parked();
4601        view.input.read_with(&visual, |state, _| {
4602            assert_eq!(state.value().as_ref(), "activated")
4603        });
4604    }
4605
4606    #[gpui::test]
4607    fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
4608        use crate::input::InlineToken;
4609        cx.update(crate::init);
4610        let view = InputView::build(cx, |state| state.default_value("before @alice after"));
4611        view.window_handle
4612            .update(cx, |_, window, cx| {
4613                view.input.update(cx, |state, cx| {
4614                    state
4615                        .replace_range_with_token(
4616                            7..13,
4617                            InlineToken::new("a", "@alice"),
4618                            window,
4619                            cx,
4620                        )
4621                        .unwrap();
4622                    state.set_selected_range(0..0, cx);
4623                });
4624            })
4625            .unwrap();
4626        let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4627        visual.update(|window, cx| window.draw(cx).clear(cx));
4628        let bounds = view
4629            .input
4630            .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
4631        visual.simulate_click(bounds.center(), gpui::Modifiers::default());
4632        visual.run_until_parked();
4633        view.input.read_with(&visual, |state, _| {
4634            assert_eq!(state.selected_range(), 7..13, "a click selects the token");
4635        });
4636    }
4637
4638    #[gpui::test]
4639    fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
4640        let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
4641        view.window_handle
4642            .update(cx, |_, window, cx| {
4643                view.input.update(cx, |state, cx| {
4644                    let token =
4645                        crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
4646                    state
4647                        .replace_range_with_token(4..10, token.clone(), window, cx)
4648                        .unwrap();
4649                    assert_eq!(state.value().as_ref(), "问 @alice!");
4650                    assert_eq!(state.tokens()[0].range(), 4..10);
4651                    assert_eq!(state.next_end_of_word_at(4), 10);
4652                    assert_eq!(state.previous_start_of_word_at(10), 4);
4653                    state.undo(&Undo, window, cx);
4654                    assert!(
4655                        state.tokens().is_empty(),
4656                        "identity-only association is undoable"
4657                    );
4658                    assert_eq!(state.value().as_ref(), "问 @alice!");
4659                    state.redo(&Redo, window, cx);
4660                    assert_eq!(state.tokens()[0].token(), &token);
4661                    state.set_selected_range(6..7, cx);
4662                    assert_eq!(state.selected_range(), 4..10);
4663                    state.replace("", window, cx);
4664                    assert_eq!(state.value().as_ref(), "问 !");
4665                    assert!(state.tokens().is_empty());
4666                    state.undo(&Undo, window, cx);
4667                    assert_eq!(state.tokens()[0].token(), &token);
4668                    state.set_selected_range(0..0, cx);
4669                    state.replace("🙂", window, cx);
4670                    assert_eq!(state.tokens()[0].range(), 8..14);
4671                    state.undo(&Undo, window, cx);
4672                    assert_eq!(state.tokens()[0].range(), 4..10);
4673                    let before = state.content();
4674                    state
4675                        .replace_range_with_token(0..0, token.clone(), window, cx)
4676                        .expect("the same reference may occur twice");
4677                    assert_eq!(state.value().as_ref(), "@alice问 @alice!");
4678                    assert_eq!(state.tokens().len(), 2);
4679                    assert_eq!(state.tokens()[1].token(), &token);
4680                    state.undo(&Undo, window, cx);
4681                    assert_eq!(state.content(), before);
4682                    state.set_value(before.text().clone(), window, cx);
4683                    assert!(state.tokens().is_empty());
4684                    assert!(!state.undo_manager.has_undos());
4685                });
4686            })
4687            .unwrap();
4688    }
4689
4690    #[gpui::test]
4691    fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
4692        use crate::input::{InlineToken, InlineTokenError, InputContent};
4693        let view = InputView::build_textarea(cx, |state| state);
4694        view.window_handle
4695            .update(cx, |_, window, cx| {
4696                view.input.update(cx, |state, cx| {
4697                    let content = InputContent::new("@a@b\n后面")
4698                        .with_token(0..2, InlineToken::new("a", "@a"))
4699                        .unwrap()
4700                        .with_token(2..4, InlineToken::new("b", "@b"))
4701                        .unwrap();
4702                    state.set_value(content.clone(), window, cx);
4703                    state.set_selected_range(2..2, cx);
4704                    assert_eq!(state.previous_boundary(2), 0);
4705                    assert_eq!(state.next_boundary(2), 4);
4706                    state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
4707                    assert_eq!(state.value().as_ref(), "中@b\n后面");
4708                    assert_eq!(state.tokens().len(), 1);
4709                    assert_eq!(
4710                        state.replace_with_token(InlineToken::new("x", "x"), window, cx),
4711                        Err(InlineTokenError::CompositionActive)
4712                    );
4713                    state.replace_text_in_range(None, "中文", window, cx);
4714                    state.undo(&Undo, window, cx);
4715                    assert_eq!(state.content(), content);
4716                    state.redo(&Redo, window, cx);
4717                    assert_eq!(state.value().as_ref(), "中文@b\n后面");
4718                    state.undo(&Undo, window, cx);
4719                    state.replace_all("plain", window, cx);
4720                    assert!(state.tokens().is_empty());
4721                    state.undo(&Undo, window, cx);
4722                    assert_eq!(state.content(), content);
4723                });
4724            })
4725            .unwrap();
4726        let view = InputView::build(cx, |state| state);
4727        view.window_handle
4728            .update(cx, |_, window, cx| {
4729                view.input.update(cx, |state, cx| {
4730                    assert_eq!(
4731                        InputContent::new("a\u{301}")
4732                            .with_token(0..1, InlineToken::new("bad", "a"))
4733                            .err(),
4734                        Some(InlineTokenError::InvalidBoundary)
4735                    );
4736                    assert_eq!(
4737                        InputContent::new("@a@a")
4738                            .with_token(0..2, InlineToken::new("a", "@a"))
4739                            .unwrap()
4740                            .with_token(1..3, InlineToken::new("x", "a@"))
4741                            .err(),
4742                        Some(InlineTokenError::OverlappingTokens)
4743                    );
4744                    state
4745                        .replace_with_token(InlineToken::new("a", "@a"), window, cx)
4746                        .unwrap();
4747                    let before = state.content();
4748                    state.set_masked(true, window, cx);
4749                    assert!(!state.tokens_visible());
4750                    assert_eq!(
4751                        state.replace_with_token(InlineToken::new("b", "b"), window, cx),
4752                        Err(InlineTokenError::UnsupportedMode)
4753                    );
4754                    assert_eq!(state.content(), before);
4755                    state.undo(&Undo, window, cx);
4756                    assert!(state.tokens().is_empty());
4757                    state.redo(&Redo, window, cx);
4758                    assert_eq!(state.content(), before);
4759                    assert!(!state.tokens_visible());
4760                });
4761            })
4762            .unwrap();
4763    }
4764
4765    use crate::theme::Theme;
4766    use gpui::{TestAppContext, VisualTestContext, size};
4767
4768    use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TextareaMode};
4769
4770    fn set_test_syntax_provider(
4771        provider: Rc<dyn crate::input::SyntaxContextProvider>,
4772        cx: &mut App,
4773    ) {
4774        struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
4775        impl crate::input::LanguageProvider for TestLanguages {
4776            fn syntax_context_provider(
4777                &self,
4778                _: &str,
4779            ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
4780                Some(self.0.clone())
4781            }
4782        }
4783        crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
4784    }
4785
4786    struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
4787
4788    impl<M: InputModeKind> Render for TestRoot<M> {
4789        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4790            div().size_full().child(self.0.clone())
4791        }
4792    }
4793
4794    struct InputView<M: InputModeKind> {
4795        input: Entity<InputBaseState<M>>,
4796        window_handle: gpui::WindowHandle<TestRoot<M>>,
4797    }
4798
4799    /// Helper to open a state of one mode in a window for testing.
4800    impl<M: InputModeKind> InputView<M> {
4801        fn build_with(
4802            cx: &mut TestAppContext,
4803            make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
4804            + 'static,
4805        ) -> Self {
4806            let mut input: Option<Entity<InputBaseState<M>>> = None;
4807
4808            let window = cx.update(|cx| {
4809                cx.open_window(Default::default(), |window, cx| {
4810                    // Set up the theme first
4811                    cx.set_global(Theme::default());
4812                    // Initialize input keybindings
4813                    super::super::init(cx);
4814
4815                    input = Some(cx.new(|cx| make(window, cx)));
4816
4817                    cx.new(|_| TestRoot(input.clone().unwrap()))
4818                })
4819                .unwrap()
4820            });
4821
4822            Self {
4823                input: input.clone().unwrap(),
4824                window_handle: window,
4825            }
4826        }
4827    }
4828
4829    impl InputView<EditorMode> {
4830        /// An editor state, for the tests that exercise code-editor behavior.
4831        fn new(cx: &mut TestAppContext) -> Self {
4832            Self::build_editor(cx, |state| state)
4833        }
4834
4835        fn build_editor(
4836            cx: &mut TestAppContext,
4837            f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
4838        ) -> Self {
4839            Self::build_with(cx, move |window, cx| {
4840                f(crate::input::EditorState::new(window, cx).language("sql"))
4841            })
4842        }
4843    }
4844
4845    impl InputView<TextareaMode> {
4846        fn build_textarea(
4847            cx: &mut TestAppContext,
4848            f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
4849        ) -> Self {
4850            Self::build_with(cx, move |window, cx| {
4851                f(crate::input::TextareaState::new(window, cx))
4852            })
4853        }
4854    }
4855
4856    impl InputView<InputMode> {
4857        /// A single-line state, the default these tests were written against.
4858        fn build(
4859            cx: &mut TestAppContext,
4860            f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
4861        ) -> Self {
4862            Self::build_with(cx, move |window, cx| {
4863                f(crate::input::InputState::new(window, cx))
4864            })
4865        }
4866    }
4867
4868    /// The frame is laid out by the application, which should not have to
4869    /// center a single line inside it.
4870    #[gpui::test]
4871    fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
4872        struct Frame(Entity<InputBaseState<InputMode>>);
4873        impl Render for Frame {
4874            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4875                crate::input::InputBase::new("frame")
4876                    .h(px(60.))
4877                    .child(crate::input::Input::new(&self.0))
4878            }
4879        }
4880
4881        cx.update(crate::init);
4882        let mut input = None;
4883        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
4884            let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
4885            input = Some(state.clone());
4886            Frame(state)
4887        });
4888        let input = input.unwrap();
4889        let mut cx = VisualTestContext::from_window(window.into(), cx);
4890        cx.update(|window, cx| window.draw(cx).clear(cx));
4891
4892        input.read_with(&cx, |state, _| {
4893            let line = state.input_bounds;
4894            assert_eq!(line.center().y, px(30.), "line {line:?}");
4895        });
4896    }
4897
4898    #[gpui::test]
4899    fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
4900        use std::{cell::Cell, rc::Rc};
4901
4902        cx.update(crate::init);
4903        let mut input = None;
4904        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
4905            input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
4906            gpui::EmptyView
4907        });
4908        let input = input.unwrap();
4909        input.update(cx, |state, cx| {
4910            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
4911            state.scroll_size = size(px(100.), px(20.));
4912            state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
4913        });
4914        let notifications = Rc::new(Cell::new(0));
4915        let count = notifications.clone();
4916        let _subscription =
4917            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
4918
4919        window
4920            .update(cx, |_, window, cx| {
4921                input.update(cx, |state, cx| {
4922                    state.on_scroll_wheel(
4923                        &ScrollWheelEvent {
4924                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
4925                            ..Default::default()
4926                        },
4927                        window,
4928                        cx,
4929                    );
4930                    assert_eq!(state.scroll_handle.offset(), Point::default());
4931                    assert!(state.diagnostic_popover().is_none());
4932                });
4933            })
4934            .unwrap();
4935        assert_eq!(
4936            notifications.get(),
4937            1,
4938            "clearing a diagnostic must notify even when scrolling is clamped"
4939        );
4940        window
4941            .update(cx, |_, window, cx| {
4942                input.update(cx, |state, cx| {
4943                    state.on_scroll_wheel(
4944                        &ScrollWheelEvent {
4945                            delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
4946                            ..Default::default()
4947                        },
4948                        window,
4949                        cx,
4950                    );
4951                });
4952            })
4953            .unwrap();
4954        assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
4955    }
4956
4957    #[gpui::test]
4958    fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
4959        use std::{cell::Cell, rc::Rc};
4960        struct Panel {
4961            input: Entity<crate::input::EditorState>,
4962            observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
4963        }
4964        impl Render for Panel {
4965            fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4966                self.observed.set(self.input.read(cx).cursor_layout());
4967                div().size_full().child(self.input.clone())
4968            }
4969        }
4970        struct Root(Entity<Panel>);
4971        impl Render for Root {
4972            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4973                div().size_full().child(
4974                    self.0
4975                        .clone()
4976                        .cached(gpui::StyleRefinement::default().size_full()),
4977                )
4978            }
4979        }
4980        cx.update(crate::init);
4981        let observed = Rc::new(Cell::new(None));
4982        let mut input = None;
4983        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
4984            let state = cx.new(|cx| {
4985                let mut state = crate::input::EditorState::new(window, cx);
4986                state.set_value("abcdefgh", window, cx);
4987                state
4988            });
4989            input = Some(state.clone());
4990            Root(cx.new(|_| Panel {
4991                input: state,
4992                observed: observed.clone(),
4993            }))
4994        });
4995        cx.run_until_parked();
4996        let input = input.unwrap();
4997        let before = input.read_with(cx, |state, _| state.cursor_layout());
4998        // The caret geometry only exists once the input has painted, and a
4999        // notify sent from inside a draw marks the view dirty without asking
5000        // for another frame, so the consumer reads the geometry on the next
5001        // invalidation rather than during the paint that produced it.
5002        input.update(cx, |_, cx| cx.notify());
5003        cx.run_until_parked();
5004        assert_eq!(observed.get(), before);
5005        window
5006            .update(cx, |_, _, cx| {
5007                input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
5008            })
5009            .unwrap();
5010        cx.run_until_parked();
5011        window.update(cx, |_, _, cx| cx.notify()).unwrap();
5012        let after = input.read_with(cx, |state, _| state.cursor_layout());
5013        assert_ne!(after, before, "the caret must actually move");
5014        assert_eq!(
5015            observed.get(),
5016            after,
5017            "render consumers must receive the newly painted caret geometry"
5018        );
5019    }
5020
5021    #[gpui::test]
5022    fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
5023        use std::{cell::Cell, rc::Rc};
5024
5025        cx.update(crate::init);
5026        let mut input = None;
5027        let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5028            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
5029            gpui::EmptyView
5030        });
5031        let input = input.unwrap();
5032        let notifications = Rc::new(Cell::new(0));
5033        let count = notifications.clone();
5034        let _subscription =
5035            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
5036
5037        input.update(cx, |state, _| {
5038            state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
5039            state.scroll_size = size(px(300.), px(20.));
5040        });
5041        for target in [
5042            None,
5043            Some(point(px(0.), px(0.))),
5044            Some(point(px(20.), px(50.))),
5045        ] {
5046            input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
5047            assert_eq!(
5048                notifications.get(),
5049                0,
5050                "an unchanged clamped offset must stay quiet"
5051            );
5052        }
5053        input.update(cx, |state, cx| {
5054            state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
5055            assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
5056        });
5057        assert_eq!(notifications.get(), 1, "a scroll must notify");
5058        input.update(cx, |state, cx| {
5059            state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
5060            assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
5061        });
5062        assert_eq!(notifications.get(), 2);
5063        input.update(cx, |state, cx| {
5064            state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
5065        });
5066        assert_eq!(
5067            notifications.get(),
5068            2,
5069            "clamping to the current offset must stay quiet"
5070        );
5071        input.update(cx, |state, cx| {
5072            state.scroll_size.width = px(110.);
5073            state.update_scroll_offset(None, cx);
5074            assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
5075        });
5076        assert_eq!(
5077            notifications.get(),
5078            3,
5079            "a smaller scroll range must clamp and notify"
5080        );
5081    }
5082
5083    #[gpui::test]
5084    fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
5085        use std::{cell::Cell, rc::Rc};
5086
5087        cx.update(crate::init);
5088        let mut input = None;
5089        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5090            input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
5091            gpui::EmptyView
5092        });
5093        let input = input.unwrap();
5094        cx.run_until_parked();
5095
5096        let notifications = Rc::new(Cell::new(0));
5097        let count = notifications.clone();
5098        let _subscription =
5099            cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
5100        cx.run_until_parked();
5101
5102        // Seeding a form is a write, so it notifies once. The input is not
5103        // focused and draws no caret, so nothing may notify after that.
5104        window
5105            .update(cx, |_, window, cx| {
5106                input.update(cx, |state, cx| state.set_value("seeded", window, cx));
5107            })
5108            .unwrap();
5109        cx.run_until_parked();
5110        let settled = notifications.get();
5111
5112        cx.executor()
5113            .advance_clock(std::time::Duration::from_secs(3));
5114        cx.run_until_parked();
5115
5116        assert_eq!(
5117            notifications.get(),
5118            settled,
5119            "an unfocused input is blinking, and every blink repaints the view it is in"
5120        );
5121    }
5122
5123    #[gpui::test]
5124    fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
5125        use std::{cell::Cell, rc::Rc};
5126
5127        struct Panel {
5128            input: Entity<crate::input::InputState>,
5129            renders: Rc<Cell<usize>>,
5130        }
5131        impl Render for Panel {
5132            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5133                self.renders.set(self.renders.get() + 1);
5134                div().size_full().child(self.input.clone())
5135            }
5136        }
5137        struct Root(Entity<Panel>);
5138        impl Render for Root {
5139            fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
5140                div().size_full().child(
5141                    self.0
5142                        .clone()
5143                        .cached(gpui::StyleRefinement::default().size_full()),
5144                )
5145            }
5146        }
5147
5148        cx.update(crate::init);
5149        let renders = Rc::new(Cell::new(0));
5150        let mut input = None;
5151        let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
5152            let state = cx.new(|cx| crate::input::InputState::new(window, cx));
5153            input = Some(state.clone());
5154            Root(cx.new(|_| Panel {
5155                input: state,
5156                renders: renders.clone(),
5157            }))
5158        });
5159        cx.run_until_parked();
5160        let before = renders.get();
5161        assert!(before > 0);
5162        for _ in 0..60 {
5163            window.update(cx, |_, _, cx| cx.notify()).unwrap();
5164        }
5165        assert_eq!(
5166            renders.get(),
5167            before,
5168            "an idle input must not invalidate its cached parent"
5169        );
5170
5171        let input = input.unwrap();
5172        window
5173            .update(cx, |_, window, cx| {
5174                input.update(cx, |state, cx| state.set_value("changed", window, cx));
5175            })
5176            .unwrap();
5177        assert!(
5178            renders.get() > before,
5179            "text changes must invalidate the parent"
5180        );
5181        // The first paint reports the changed text extent to layout consumers.
5182        window.update(cx, |_, _, cx| cx.notify()).unwrap();
5183        let before = renders.get();
5184        for _ in 0..60 {
5185            window.update(cx, |_, _, cx| cx.notify()).unwrap();
5186        }
5187        assert_eq!(renders.get(), before, "the edited input must settle again");
5188
5189        cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
5190        cx.run_until_parked();
5191        assert!(renders.get() > before, "resizing must invalidate layout");
5192    }
5193
5194    #[gpui::test]
5195    fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
5196        cx.update(crate::init);
5197        let view = InputView::build_textarea(cx, |state| state);
5198        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
5199        cx.update(|window, cx| {
5200            view.input.update(cx, |state, cx| {
5201                for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
5202                    state.set_value(original, window, cx);
5203                    let newline = original.find('\n').unwrap();
5204                    let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
5205                        newline - 1
5206                    } else {
5207                        newline
5208                    };
5209                    state.end(&MoveEnd, window, cx);
5210                    assert_eq!(state.cursor(), end);
5211                    state.right(&MoveRight, window, cx);
5212                    assert_eq!(state.cursor(), newline + 1);
5213                    state.left(&MoveLeft, window, cx);
5214                    assert_eq!(state.cursor(), end);
5215                    state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
5216                    assert_eq!(state.selected_range(), end..end);
5217                    state.move_to_end(&MoveToEnd, window, cx);
5218                    assert_eq!(state.cursor(), original.len());
5219                    state.move_to_start(&MoveToStart, window, cx);
5220                    assert_eq!(state.cursor(), 0);
5221                    assert_eq!(state.value().as_bytes(), original.as_bytes());
5222                }
5223                // A lone CR is an ordinary character; it must not skip its neighbour.
5224                state.set_value("a\rb", window, cx);
5225                state.right(&MoveRight, window, cx);
5226                assert_eq!(state.cursor(), 1);
5227                state.right(&MoveRight, window, cx);
5228                assert_eq!(state.cursor(), 2);
5229            })
5230        });
5231    }
5232
5233    #[gpui::test]
5234    fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
5235        cx.update(crate::init);
5236
5237        // A single-line input keeps its caret in view by moving its own offset;
5238        // it has no viewport to drag, so a scrollbar in a text field is a
5239        // control that does not exist.
5240        let single = InputView::build(cx, |state| state);
5241        single
5242            .input
5243            .update(cx, |state, _| assert!(!state.shows_scrollbar()));
5244
5245        let multi = InputView::build_textarea(cx, |state| state);
5246        multi
5247            .input
5248            .update(cx, |state, _| assert!(state.shows_scrollbar()));
5249    }
5250
5251    #[gpui::test]
5252    fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
5253        use std::{cell::Cell, rc::Rc};
5254        cx.update(crate::init);
5255        let input_view = InputView::new(cx);
5256        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5257        let input = input_view.input;
5258        let calls = Rc::new(Cell::new(0usize));
5259        let items = Rc::new(Cell::new(0usize));
5260
5261        cx.update(|window, cx| {
5262            input.update(cx, |state, cx| {
5263                let calls2 = calls.clone();
5264                let items2 = items.clone();
5265                state.on_context_menu(Rc::new(move |menu, _, _, _, _| {
5266                    calls2.set(calls2.get() + 1);
5267                    items2.set(menu.items.len());
5268                }));
5269                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
5270            })
5271        });
5272        assert_eq!(calls.get(), 1);
5273        assert_eq!(items.get(), 0);
5274
5275        cx.update(|window, cx| {
5276            input.update(cx, |state, cx| {
5277                state.disabled = true;
5278                state.handle_right_click_menu(point(px(0.), px(0.)), 0, window, cx);
5279            })
5280        });
5281        assert_eq!(calls.get(), 1);
5282    }
5283
5284    #[gpui::test]
5285    fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
5286        let input_view = InputView::new(cx);
5287        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5288        let input = input_view.input;
5289
5290        cx.update(|window, cx| {
5291            input.update(cx, |state, cx| {
5292                state.set_value("hello", window, cx);
5293                state.set_readonly(true, cx);
5294            });
5295        });
5296
5297        cx.update(|_, cx| {
5298            input.read_with(cx, |state, _| {
5299                assert!(!state.is_editable());
5300                assert!(!state.is_replaceable());
5301            });
5302        });
5303
5304        // Typing (and IME) goes through the input handler, it must be rejected.
5305        cx.update(|window, cx| {
5306            input.update(cx, |state, cx| {
5307                state.replace_text_in_range(None, " world", window, cx);
5308                state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
5309            });
5310        });
5311        cx.update(|_, cx| {
5312            input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
5313        });
5314
5315        // The programmatic APIs are not limited by the readonly mode.
5316        cx.update(|window, cx| {
5317            input.update(cx, |state, cx| {
5318                state.insert(" world", window, cx);
5319                state.set_value("changed", window, cx);
5320            });
5321        });
5322        cx.update(|_, cx| {
5323            input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
5324        });
5325
5326        // And the user can edit again after leaving the readonly mode.
5327        // The caret is at the start, because `set_value` has reset the selection.
5328        cx.update(|window, cx| {
5329            input.update(cx, |state, cx| {
5330                state.set_readonly(false, cx);
5331                state.replace_text_in_range(None, "!", window, cx);
5332            });
5333        });
5334        cx.update(|_, cx| {
5335            input.read_with(cx, |state, _| {
5336                assert!(state.is_editable());
5337                assert_eq!(state.value(), "!changed");
5338            });
5339        });
5340    }
5341
5342    /// Regression test: editing at a caret that sits far outside the viewport
5343    /// must reveal it in one frame. The cursor-follow in `layout_cursors` runs
5344    /// only on the frame the selection changes, so its old one-line step left
5345    /// the caret offscreen after typing at the end of a long paste.
5346    #[gpui::test]
5347    fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
5348        let mut input = None;
5349        let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
5350            cx.set_global(Theme::default());
5351            super::super::init(cx);
5352            let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
5353            input = Some(state.clone());
5354            TestRoot(state)
5355        });
5356        let mut cx = VisualTestContext::from_window(window.into(), cx);
5357        let input = input.unwrap();
5358
5359        let text: String = (1..=100)
5360            .map(|i| format!("line {i}"))
5361            .collect::<Vec<_>>()
5362            .join("\n");
5363        cx.update(|window, cx| {
5364            input.update(cx, |state, cx| {
5365                state.set_value(text, window, cx);
5366                let end = state.text.len();
5367                state.set_selection(end, end);
5368            });
5369        });
5370        cx.run_until_parked();
5371
5372        // The user scrolled back to the top to read the pasted text.
5373        cx.update(|_, cx| {
5374            input.update(cx, |state, cx| {
5375                state.scroll_handle.set_offset(point(px(0.), px(0.)));
5376                cx.notify();
5377            });
5378        });
5379        cx.run_until_parked();
5380
5381        cx.update(|window, cx| {
5382            input.update(cx, |state, cx| {
5383                state.replace_text_in_range(None, "X", window, cx);
5384            });
5385        });
5386        cx.run_until_parked();
5387
5388        cx.update(|_, cx| {
5389            input.read_with(cx, |state, _| {
5390                assert!(state.value().ends_with("line 100X"));
5391                let (caret, _) = state.cursor_layout().expect("caret painted");
5392                let viewport = state.input_bounds();
5393                let scroll_y = state.scroll_handle.offset().y;
5394                let top = caret.origin.y - viewport.origin.y + scroll_y;
5395                assert!(
5396                    top >= px(0.) && top + caret.size.height <= viewport.size.height,
5397                    "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
5398                    viewport.size.height,
5399                );
5400            });
5401        });
5402    }
5403
5404    /// Regression test: `scroll_to` at end-of-buffer must produce a deferred
5405    /// scroll target within the safe scroll range, so the painted frame
5406    /// matches what `update_scroll_offset` persists (no jitter). A small
5407    /// `cursor_surrounding_lines` override used to mismatch the hardcoded
5408    /// 3-line edge clearance in `scroll_to`, overshooting `safe_y_min`.
5409    #[gpui::test]
5410    fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
5411        let input_view = InputView::new(cx);
5412        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5413        let input = input_view.input;
5414
5415        // JetBrains-style: 1 trailing empty row + 1-line cursor surrounding.
5416        cx.update(|window, cx| {
5417            input.update(cx, |state, cx| {
5418                state.set_scroll_beyond_last_line(Some(1), window, cx);
5419                state.set_cursor_surrounding_lines(Some(1), window, cx);
5420                let text: String = (1..=50)
5421                    .map(|i| format!("line {i}"))
5422                    .collect::<Vec<_>>()
5423                    .join("\n");
5424                state.set_value(text, window, cx);
5425            });
5426        });
5427        cx.run_until_parked();
5428
5429        // Sanity: paint populated `scroll_size` and `input_bounds` — without
5430        // these, `safe_y_min` below collapses to 0 and the assertion is vacuous.
5431        cx.update(|_, cx| {
5432            input.read_with(cx, |state, _| {
5433                assert!(
5434                    state.scroll_size.height > px(0.),
5435                    "scroll_size not populated by initial paint"
5436                );
5437                assert!(
5438                    state.input_bounds.size.height > px(0.),
5439                    "input_bounds not populated by initial paint"
5440                );
5441            });
5442        });
5443
5444        // Move cursor to end with downward direction — same code path as a
5445        // `Down` keystroke at EOB. `scroll_to` runs synchronously inside
5446        // `move_to`; inspect `deferred_scroll_offset` in the same closure
5447        // before the next paint consumes and clears it.
5448        cx.update(|_, cx| {
5449            input.update(cx, |state, cx| {
5450                let end = state.text.len();
5451                state.move_to(end, Some(MoveDirection::Down), cx);
5452
5453                let deferred = state
5454                    .deferred_scroll_offset
5455                    .expect("scroll_to should populate deferred_scroll_offset");
5456                let safe_y_min =
5457                    (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
5458
5459                assert!(
5460                    deferred.y >= safe_y_min,
5461                    "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
5462                     — paint would jitter (Bug C regression)",
5463                    deferred.y,
5464                    safe_y_min,
5465                );
5466            });
5467        });
5468    }
5469
5470    #[gpui::test]
5471    fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
5472        assert_search_reveals_with_padding_after_manual_scroll(false, cx);
5473    }
5474
5475    #[gpui::test]
5476    fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
5477        cx: &mut TestAppContext,
5478    ) {
5479        assert_search_reveals_with_padding_after_manual_scroll(true, cx);
5480    }
5481
5482    fn assert_search_reveals_with_padding_after_manual_scroll(
5483        previous: bool,
5484        cx: &mut TestAppContext,
5485    ) {
5486        let input_view = InputView::new(cx);
5487        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5488        let input = input_view.input;
5489        let text = (0..160)
5490            .map(|row| {
5491                if matches!(row, 20 | 60 | 100) {
5492                    format!("match on row {row}")
5493                } else {
5494                    format!("line {row}")
5495                }
5496            })
5497            .collect::<Vec<_>>()
5498            .join("\n");
5499        let start = text.match_indices("match").nth(1).unwrap().0;
5500        let expected_match = start..start + "match".len();
5501        cx.update(|window, cx| {
5502            input.update(cx, |state, cx| {
5503                state.set_cursor_surrounding_lines(Some(3), window, cx);
5504                state.set_value(text, window, cx);
5505                state.set_search_query("match", true, cx);
5506                if previous {
5507                    state.search_session.matcher.next();
5508                    state.search_session.matcher.next();
5509                }
5510            });
5511        });
5512        cx.run_until_parked();
5513        cx.update(|_, cx| {
5514            input.update(cx, |state, cx| {
5515                let line_height = state.last_layout.as_ref().unwrap().line_height;
5516                let y = if previous { px(0.) } else { -line_height * 80. };
5517                state.set_scroll_offset(point(px(0.), y), cx);
5518            });
5519        });
5520        cx.run_until_parked();
5521        input.read_with(&cx, |state, _| {
5522            let visible = state.visible_row_range().unwrap();
5523            if previous {
5524                assert!(visible.end <= 60, "target must be below the viewport");
5525            } else {
5526                assert!(visible.start > 60, "target must be above the viewport");
5527            }
5528        });
5529        cx.update(|_, cx| {
5530            input.update(cx, |state, cx| {
5531                let range = if previous {
5532                    state.previous_search_match(cx)
5533                } else {
5534                    state.next_search_match(cx)
5535                };
5536                assert_eq!(range, Some(expected_match));
5537                assert_eq!(state.search_session.matcher.label(), "2/3");
5538            });
5539        });
5540        cx.run_until_parked();
5541        input.read_with(&cx, |state, _| {
5542            assert!(state.visible_row_range().unwrap().contains(&60));
5543            let line_height = state.last_layout.as_ref().unwrap().line_height;
5544            let target_y = line_height * 60. + state.scroll_handle.offset().y;
5545            // Three lines of edge clearance include the matched line itself.
5546            assert!(target_y >= line_height * 2. - px(0.1));
5547            assert!(
5548                target_y + line_height * 3.
5549                    <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
5550                "search must preserve the configured surrounding-line padding"
5551            );
5552        });
5553    }
5554
5555    /// A host that wants the search shortcut for its own search UI.
5556    struct SearchHost {
5557        editor: Entity<InputBaseState<EditorMode>>,
5558        search_requests: Rc<Cell<usize>>,
5559    }
5560
5561    impl Render for SearchHost {
5562        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5563            let search_requests = self.search_requests.clone();
5564            div()
5565                .size_full()
5566                .on_action(cx.listener(move |_, _: &Search, _, _| {
5567                    search_requests.set(search_requests.get() + 1);
5568                }))
5569                .child(self.editor.clone())
5570        }
5571    }
5572
5573    /// Opens an editor inside [`SearchHost`], focused, and presses the search
5574    /// shortcut once. Returns the editor and the host's request count.
5575    fn press_search_shortcut(
5576        cx: &mut TestAppContext,
5577        searchable: bool,
5578    ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
5579        let search_requests = Rc::new(Cell::new(0));
5580        let mut editor = None;
5581        let window = cx.update(|cx| {
5582            cx.open_window(Default::default(), |window, cx| {
5583                cx.set_global(Theme::default());
5584                super::super::init(cx);
5585                let state =
5586                    cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
5587                editor = Some(state.clone());
5588                cx.new(|_| SearchHost {
5589                    editor: state,
5590                    search_requests: search_requests.clone(),
5591                })
5592            })
5593            .unwrap()
5594        });
5595        let editor = editor.unwrap();
5596        let mut cx = VisualTestContext::from_window(window.into(), cx);
5597        cx.update(|window, cx| {
5598            editor.update(cx, |state, cx| state.focus(window, cx));
5599        });
5600        cx.run_until_parked();
5601        #[cfg(target_os = "macos")]
5602        cx.simulate_keystrokes("cmd-f");
5603        #[cfg(not(target_os = "macos"))]
5604        cx.simulate_keystrokes("ctrl-f");
5605        cx.run_until_parked();
5606        (editor, search_requests)
5607    }
5608
5609    #[gpui::test]
5610    fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
5611        let (editor, search_requests) = press_search_shortcut(cx, false);
5612        assert_eq!(search_requests.get(), 1);
5613        editor.read_with(cx, |state, _| {
5614            assert!(!state.search_session().open);
5615            assert!(!state.search_session().is_active());
5616        });
5617    }
5618
5619    #[gpui::test]
5620    fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
5621        let (editor, search_requests) = press_search_shortcut(cx, true);
5622        assert_eq!(search_requests.get(), 0);
5623        editor.read_with(cx, |state, _| {
5624            assert!(state.search_session().open);
5625            assert!(state.search_session().is_active());
5626        });
5627    }
5628
5629    #[gpui::test]
5630    fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
5631        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
5632        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5633        let input = input_view.input;
5634        cx.update(|window, cx| {
5635            input.update(cx, |state, cx| {
5636                state.set_value("foo bar foo", window, cx);
5637                state.set_search_query("foo", true, cx);
5638            });
5639        });
5640        cx.run_until_parked();
5641        input.read_with(&cx, |state, _| {
5642            let session = state.search_session();
5643            assert!(session.is_active());
5644            assert!(!session.open);
5645            assert_eq!(session.matcher.len(), 2);
5646        });
5647        cx.update(|_, cx| {
5648            input.update(cx, |state, cx| state.close_search(cx));
5649        });
5650        input.read_with(&cx, |state, _| {
5651            assert!(!state.search_session().is_active());
5652        });
5653    }
5654
5655    /// A closed search skips rescanning on edits, so every path that reads
5656    /// the matches again must see the edited text, not the text at close.
5657    #[gpui::test]
5658    fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
5659        let input_view = InputView::build_editor(cx, |state| state.searchable(false));
5660        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5661        let input = input_view.input;
5662        cx.update(|window, cx| {
5663            input.update(cx, |state, cx| {
5664                state.set_value("foo bar foo", window, cx);
5665                state.set_search_query("foo", true, cx);
5666                state.close_search(cx);
5667
5668                state.set_value("bar foo", window, cx);
5669                assert_eq!(state.next_search_match(cx), Some(4..7));
5670
5671                state.set_value("foo foo foo", window, cx);
5672                state.set_search_query("foo", true, cx);
5673                assert_eq!(state.search_session().matcher.len(), 3);
5674            });
5675        });
5676    }
5677
5678    #[gpui::test]
5679    fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
5680        let input_view = InputView::new(cx);
5681        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5682        let input = input_view.input;
5683        let text = format!(
5684            "match\n{}\n{}match\n{}",
5685            "line\n".repeat(80),
5686            "wrapped text ".repeat(500),
5687            "line\n".repeat(80)
5688        );
5689        cx.update(|window, cx| {
5690            input.update(cx, |state, cx| {
5691                state.set_cursor_surrounding_lines(Some(3), window, cx);
5692                state.set_value(text, window, cx);
5693                state.set_search_query("match", true, cx);
5694            });
5695        });
5696        cx.run_until_parked();
5697        cx.update(|_, cx| {
5698            input.update(cx, |state, cx| {
5699                state.next_search_match(cx).unwrap();
5700            });
5701        });
5702        cx.run_until_parked();
5703        input.read_with(&cx, |state, _| {
5704            let range = state.search_session.matcher.matched_ranges()[1].clone();
5705            let layout = state.last_layout.as_ref().unwrap();
5706            let (_, _, position) = state.line_and_position_for_offset(range.end);
5707            let y = position.expect("wrapped match must be laid out").y
5708                + state.scroll_handle.offset().y;
5709            assert!(y >= layout.line_height * 2. - px(0.1));
5710            assert!(
5711                y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
5712                "wrapped match must retain surrounding display rows"
5713            );
5714        });
5715    }
5716
5717    #[gpui::test]
5718    fn test_number_step(cx: &mut TestAppContext) {
5719        let input = InputView::build(cx, |state| state).input;
5720
5721        cx.update(|cx| {
5722            input.update(cx, |_state, cx| {
5723                assert_eq!(
5724                    NumberStep::from(5.).value(123., StepAction::Increment, cx),
5725                    5.
5726                );
5727
5728                // The step can differ by direction at a boundary: at 1.0 it
5729                // is 0.1 going down and 0.5 going up.
5730                let step = NumberStep::by_value(|value, action, _cx| {
5731                    let below = match action {
5732                        StepAction::Increment => value < 1.0,
5733                        StepAction::Decrement => value <= 1.0,
5734                    };
5735                    if below { 0.1 } else { 0.5 }
5736                });
5737                assert_eq!(step.value(0.5, StepAction::Increment, cx), 0.1);
5738                assert_eq!(step.value(1.0, StepAction::Increment, cx), 0.5);
5739                assert_eq!(step.value(1.0, StepAction::Decrement, cx), 0.1);
5740                assert_eq!(step.value(2.0, StepAction::Decrement, cx), 0.5);
5741            });
5742        });
5743    }
5744
5745    #[gpui::test]
5746    fn test_number_input_normalization(cx: &mut TestAppContext) {
5747        let input_view = InputView::build(cx, |state| {
5748            state.mask_pattern(MaskPattern::Number {
5749                separator: None,
5750                fraction: None,
5751            })
5752        });
5753        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5754        let input = input_view.input;
5755
5756        // Full-width digits and the ideographic full stop are normalized,
5757        // and the cursor is at the end (in normalized bytes, not the
5758        // original 12 bytes).
5759        cx.update(|window, cx| {
5760            input.update(cx, |state, cx| {
5761                state.replace_text_in_range(None, "12。5", window, cx);
5762            });
5763        });
5764        cx.run_until_parked();
5765        cx.update(|_, cx| {
5766            input.read_with(cx, |state, _| {
5767                assert_eq!(state.value(), "12.5");
5768                let cursor: Range<usize> = state.selected_range();
5769                assert_eq!(cursor, 4..4);
5770            });
5771        });
5772
5773        // Non-numeric input is rejected.
5774        cx.update(|window, cx| {
5775            input.update(cx, |state, cx| {
5776                state.replace_text_in_range(None, "abc", window, cx);
5777            });
5778        });
5779        cx.run_until_parked();
5780        cx.update(|_, cx| {
5781            input.read_with(cx, |state, _| {
5782                assert_eq!(state.value(), "12.5");
5783            });
5784        });
5785
5786        // A bare leading dot is kept as-is (normalized from the ideographic
5787        // full stop), not completed to "0.", so it stays editable.
5788        cx.update(|window, cx| {
5789            input.update(cx, |state, cx| {
5790                let range = state.range_to_utf16(&(0..state.text.len()));
5791                state.replace_text_in_range(Some(range), "。", window, cx);
5792            });
5793        });
5794        cx.run_until_parked();
5795        cx.update(|_, cx| {
5796            input.read_with(cx, |state, _| {
5797                assert_eq!(state.value(), ".");
5798                let cursor: Range<usize> = state.selected_range();
5799                assert_eq!(cursor, 1..1);
5800            });
5801        });
5802    }
5803
5804    #[gpui::test]
5805    fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
5806        let input_view = InputView::build(cx, |state| {
5807            state.mask_pattern(MaskPattern::Number {
5808                separator: Some(','),
5809                fraction: Some(2),
5810            })
5811        });
5812        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5813        let input = input_view.input;
5814
5815        cx.update(|window, cx| {
5816            input.update(cx, |state, cx| {
5817                state.replace_text_in_range(None, "1234", window, cx);
5818            });
5819        });
5820        cx.run_until_parked();
5821        cx.update(|_, cx| {
5822            input.read_with(cx, |state, _| {
5823                assert_eq!(state.value(), "1,234");
5824                assert_eq!(state.unmask_value(), "1234");
5825            });
5826        });
5827    }
5828
5829    #[gpui::test]
5830    fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
5831        let input_view = InputView::build(cx, |state| {
5832            state
5833                .mask_pattern(MaskPattern::Number {
5834                    separator: None,
5835                    fraction: None,
5836                })
5837                .min(10.)
5838                .max(100.)
5839        });
5840        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5841        let input = input_view.input;
5842
5843        // Out-of-range values are allowed while typing, and clamped on blur.
5844        cx.update(|window, cx| {
5845            input.update(cx, |state, cx| {
5846                state.replace_text_in_range(None, "1000", window, cx);
5847                assert_eq!(state.value(), "1000");
5848                state.clamp_number_value(window, cx);
5849                assert_eq!(state.value(), "100");
5850
5851                let range = state.range_to_utf16(&(0..state.text.len()));
5852                state.replace_text_in_range(Some(range), "1", window, cx);
5853                assert_eq!(state.value(), "1");
5854                state.clamp_number_value(window, cx);
5855                assert_eq!(state.value(), "10");
5856            });
5857        });
5858    }
5859
5860    #[gpui::test]
5861    fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
5862        let input_view = InputView::build(cx, |state| {
5863            state.mask_pattern(MaskPattern::Number {
5864                separator: Some(','),
5865                fraction: None,
5866            })
5867        });
5868        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5869        let input = input_view.input;
5870
5871        // When the mask changes the text (regrouping separators), a
5872        // whole-document change is recorded, so undo/redo can restore it.
5873        cx.update(|window, cx| {
5874            input.update(cx, |state, cx| {
5875                state.replace_text_in_range(None, "1234", window, cx);
5876                assert_eq!(state.value(), "1,234");
5877                state.replace_text_in_range(None, "5", window, cx);
5878                assert_eq!(state.value(), "12,345");
5879
5880                // Each whole-document mask rewrite is an atomic undo step.
5881                // Before the whole-document history fix, undo produced a
5882                // corrupted value like "1,2344".
5883                state.undo(&Undo, window, cx);
5884                assert_eq!(state.value(), "1,234");
5885                state.undo(&Undo, window, cx);
5886                assert_eq!(state.value(), "");
5887                state.redo(&Redo, window, cx);
5888                assert_eq!(state.value(), "1,234");
5889                state.redo(&Redo, window, cx);
5890                assert_eq!(state.value(), "12,345");
5891            });
5892        });
5893    }
5894
5895    #[gpui::test]
5896    fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
5897        let input_view = InputView::build(cx, |state| state);
5898        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5899        let input = input_view.input;
5900
5901        cx.update(|window, cx| {
5902            input.update(cx, |state, cx| {
5903                state.replace_text_in_range(None, "a", window, cx);
5904                state.replace_text_in_range(None, "b", window, cx);
5905                assert_eq!(state.value(), "ab");
5906
5907                state.undo(&Undo, window, cx);
5908                assert_eq!(state.value(), "");
5909            });
5910        });
5911    }
5912
5913    #[gpui::test]
5914    fn test_undo_manager_cursor_movement_splits_typing(cx: &mut TestAppContext) {
5915        let input_view = InputView::build(cx, |state| state);
5916        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5917        let input = input_view.input;
5918
5919        cx.update(|window, cx| {
5920            input.update(cx, |state, cx| {
5921                state.replace_text_in_range(None, "a", window, cx);
5922                state.replace_text_in_range(None, "b", window, cx);
5923                state.left(&MoveLeft, window, cx);
5924                state.replace_text_in_range(None, "x", window, cx);
5925                assert_eq!(state.value(), "axb");
5926
5927                state.undo(&Undo, window, cx);
5928                assert_eq!(state.value(), "ab");
5929                state.undo(&Undo, window, cx);
5930                assert_eq!(state.value(), "");
5931            });
5932        });
5933    }
5934
5935    #[gpui::test]
5936    fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
5937        let input_view = InputView::build(cx, |state| state);
5938        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5939        let input = input_view.input;
5940
5941        cx.update(|window, cx| {
5942            input.update(cx, |state, cx| {
5943                state.set_value("abcd", window, cx);
5944                state.set_selected_range(2..2, cx);
5945                state.backspace(&Backspace, window, cx);
5946                state.delete(&Delete, window, cx);
5947                assert_eq!(state.value(), "ad");
5948
5949                state.undo(&Undo, window, cx);
5950                assert_eq!(state.value(), "acd");
5951                state.undo(&Undo, window, cx);
5952                assert_eq!(state.value(), "abcd");
5953            });
5954        });
5955    }
5956
5957    #[gpui::test]
5958    fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
5959        let input_view = InputView::build(cx, |state| state);
5960        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5961        let input = input_view.input;
5962
5963        cx.update(|window, cx| {
5964            input.update(cx, |state, cx| {
5965                state.set_value("abcd", window, cx);
5966                state.backspace(&Backspace, window, cx);
5967                state.backspace(&Backspace, window, cx);
5968                assert_eq!(state.value(), "ab");
5969                state.undo(&Undo, window, cx);
5970                assert_eq!(state.value(), "abcd");
5971                assert_eq!(state.selected_range(), 4..4);
5972
5973                state.set_value("abcd", window, cx);
5974                state.set_selected_range(1..1, cx);
5975                state.delete(&Delete, window, cx);
5976                state.delete(&Delete, window, cx);
5977                assert_eq!(state.value(), "ad");
5978                state.undo(&Undo, window, cx);
5979                assert_eq!(state.value(), "abcd");
5980                assert_eq!(state.selected_range(), 1..1);
5981            });
5982        });
5983    }
5984
5985    #[gpui::test]
5986    fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
5987        let input_view = InputView::build(cx, |state| state);
5988        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
5989        let input = input_view.input;
5990
5991        cx.update(|window, cx| {
5992            cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
5993            input.update(cx, |state, cx| {
5994                state.replace_text_in_range(None, "a", window, cx);
5995                state.paste(&Paste, window, cx);
5996                state.replace_text_in_range(None, "b", window, cx);
5997                assert_eq!(state.value(), "aPb");
5998
5999                state.undo(&Undo, window, cx);
6000                assert_eq!(state.value(), "aP");
6001                state.undo(&Undo, window, cx);
6002                assert_eq!(state.value(), "a");
6003                state.undo(&Undo, window, cx);
6004                assert_eq!(state.value(), "");
6005            });
6006        });
6007    }
6008
6009    #[gpui::test]
6010    fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
6011        let input_view = InputView::build(cx, |state| state);
6012        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6013        let input = input_view.input;
6014
6015        cx.update(|window, cx| {
6016            input.update(cx, |state, cx| {
6017                state.replace_text_in_range(None, "a", window, cx);
6018                state.insert("P", window, cx);
6019                state.replace_text_in_range(None, "b", window, cx);
6020                assert_eq!(state.value(), "aPb");
6021
6022                state.undo(&Undo, window, cx);
6023                assert_eq!(state.value(), "aP");
6024                state.undo(&Undo, window, cx);
6025                assert_eq!(state.value(), "a");
6026            });
6027        });
6028    }
6029
6030    #[gpui::test]
6031    fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
6032        let input_view = InputView::build(cx, |state| state);
6033        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6034        let input = input_view.input;
6035
6036        cx.update(|window, cx| {
6037            input.update(cx, |state, cx| {
6038                state.replace_text_in_range(None, "a", window, cx);
6039                state.replace_text_in_range(None, "b", window, cx);
6040                state.select_all(window, cx);
6041                state.unselect(window, cx);
6042                state.replace_text_in_range(None, "c", window, cx);
6043
6044                state.undo(&Undo, window, cx);
6045                assert_eq!(state.value(), "ab");
6046                state.undo(&Undo, window, cx);
6047                assert_eq!(state.value(), "");
6048            });
6049        });
6050    }
6051
6052    #[gpui::test]
6053    fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
6054        let input_view = InputView::build_textarea(cx, |state| state);
6055        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6056        let input = input_view.input;
6057
6058        cx.update(|window, cx| {
6059            input.update(cx, |state, cx| {
6060                state.replace_text_in_range(None, "a", window, cx);
6061                state.enter(
6062                    &Enter {
6063                        secondary: false,
6064                        shift: false,
6065                    },
6066                    window,
6067                    cx,
6068                );
6069                state.replace_text_in_range(None, "b", window, cx);
6070
6071                state.undo(&Undo, window, cx);
6072                assert_eq!(state.value(), "a\n");
6073                state.undo(&Undo, window, cx);
6074                assert_eq!(state.value(), "a");
6075                state.undo(&Undo, window, cx);
6076                assert_eq!(state.value(), "");
6077            });
6078        });
6079    }
6080
6081    #[gpui::test]
6082    fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
6083        let input_view = InputView::build(cx, |state| state);
6084        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6085        let input = input_view.input;
6086
6087        cx.update(|window, cx| {
6088            input.update(cx, |state, cx| {
6089                for part in ["a", "b", "c"] {
6090                    state.replace_text_in_range(None, part, window, cx);
6091                }
6092                state.enter(
6093                    &Enter {
6094                        secondary: false,
6095                        shift: false,
6096                    },
6097                    window,
6098                    cx,
6099                );
6100                for part in ["d", "e", "f"] {
6101                    state.replace_text_in_range(None, part, window, cx);
6102                }
6103                assert_eq!(state.value(), "abcdef");
6104
6105                state.undo(&Undo, window, cx);
6106                assert_eq!(state.value(), "abc");
6107                state.undo(&Undo, window, cx);
6108                assert_eq!(state.value(), "");
6109            });
6110        });
6111    }
6112
6113    #[gpui::test]
6114    fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
6115        let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
6116        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6117        let input = input_view.input;
6118
6119        cx.update(|window, cx| {
6120            input.update(cx, |state, cx| {
6121                state.replace_text_in_range(None, "before submit", window, cx);
6122                state.enter(
6123                    &Enter {
6124                        secondary: false,
6125                        shift: false,
6126                    },
6127                    window,
6128                    cx,
6129                );
6130                state.replace_text_in_range(None, " after submit", window, cx);
6131                assert_eq!(state.value(), "before submit after submit");
6132
6133                state.undo(&Undo, window, cx);
6134                assert_eq!(state.value(), "before submit");
6135                state.undo(&Undo, window, cx);
6136                assert_eq!(state.value(), "");
6137            });
6138        });
6139    }
6140
6141    #[gpui::test]
6142    fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
6143        let input_view = InputView::build(cx, |state| state);
6144        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6145        let input = input_view.input;
6146
6147        cx.update(|window, cx| {
6148            input.update(cx, |state, cx| {
6149                state.replace_text_in_range(None, "before blur", window, cx);
6150                state.on_blur(window, cx);
6151                state.on_focus(window, cx);
6152                state.replace_text_in_range(None, " after focus", window, cx);
6153                assert_eq!(state.value(), "before blur after focus");
6154
6155                state.undo(&Undo, window, cx);
6156                assert_eq!(state.value(), "before blur");
6157                state.undo(&Undo, window, cx);
6158                assert_eq!(state.value(), "");
6159            });
6160        });
6161    }
6162
6163    #[gpui::test]
6164    fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
6165        let input_view = InputView::build_textarea(cx, |state| state);
6166        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6167        let input = input_view.input;
6168
6169        cx.update(|window, cx| {
6170            input.update(cx, |state, cx| {
6171                let enter = Enter {
6172                    secondary: false,
6173                    shift: false,
6174                };
6175                state.replace_text_in_range(None, "a", window, cx);
6176                state.enter(&enter, window, cx);
6177                state.replace_text_in_range(None, "b", window, cx);
6178                state.enter(&enter, window, cx);
6179                state.replace_text_in_range(None, "c", window, cx);
6180                assert_eq!(state.value(), "a\nb\nc");
6181
6182                for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
6183                    state.undo(&Undo, window, cx);
6184                    assert_eq!(state.value(), expected);
6185                }
6186            });
6187        });
6188    }
6189
6190    #[gpui::test]
6191    fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
6192        let input_view = InputView::build_textarea(cx, |state| state);
6193        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6194        let input = input_view.input;
6195        let parts = [
6196            "The ",
6197            "quick ",
6198            "brown fox, ",
6199            "你好,世界 ",
6200            "🦀 jumps over 13 lazy dogs.",
6201        ];
6202        let expected = parts.concat();
6203
6204        cx.update(|window, cx| {
6205            input.update(cx, |state, cx| {
6206                for part in parts {
6207                    state.replace_text_in_range(None, part, window, cx);
6208                }
6209                assert_eq!(state.value(), expected);
6210
6211                state.undo(&Undo, window, cx);
6212                assert_eq!(state.value(), "");
6213                state.redo(&Redo, window, cx);
6214                assert_eq!(state.value(), expected);
6215            });
6216        });
6217    }
6218
6219    #[gpui::test]
6220    fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
6221        cx: &mut TestAppContext,
6222    ) {
6223        let input_view = InputView::build_textarea(cx, |state| state);
6224        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6225        let input = input_view.input;
6226        let enter = Enter {
6227            secondary: false,
6228            shift: false,
6229        };
6230
6231        cx.update(|window, cx| {
6232            input.update(cx, |state, cx| {
6233                for (index, line) in [
6234                    "first line with punctuation!",
6235                    "第二行包含 Unicode 🦀",
6236                    "third line has several words",
6237                ]
6238                .into_iter()
6239                .enumerate()
6240                {
6241                    for chunk in line.split_inclusive(' ') {
6242                        state.replace_text_in_range(None, chunk, window, cx);
6243                    }
6244                    if index < 2 {
6245                        state.enter(&enter, window, cx);
6246                    }
6247                }
6248
6249                assert_eq!(
6250                    state.value(),
6251                    "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
6252                );
6253                state.undo(&Undo, window, cx);
6254                assert_eq!(
6255                    state.value(),
6256                    "first line with punctuation!\n第二行包含 Unicode 🦀\n"
6257                );
6258                state.undo(&Undo, window, cx);
6259                assert_eq!(
6260                    state.value(),
6261                    "first line with punctuation!\n第二行包含 Unicode 🦀"
6262                );
6263                state.undo(&Undo, window, cx);
6264                assert_eq!(state.value(), "first line with punctuation!\n");
6265            });
6266        });
6267    }
6268
6269    #[gpui::test]
6270    fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
6271        let input_view = InputView::build(cx, |state| state);
6272        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6273        let input = input_view.input;
6274
6275        cx.update(|window, cx| {
6276            input.update(cx, |state, cx| {
6277                state.set_value("hunter2", window, cx);
6278                state.set_masked(true, window, cx);
6279                state.select_all(window, cx);
6280                cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
6281
6282                state.copy(&Copy, window, cx);
6283                assert_eq!(
6284                    cx.read_from_clipboard().and_then(|item| item.text()),
6285                    Some("sentinel".to_string())
6286                );
6287
6288                // Cut neither copies nor deletes.
6289                state.cut(&Cut, window, cx);
6290                assert_eq!(state.value(), "hunter2");
6291                assert_eq!(
6292                    cx.read_from_clipboard().and_then(|item| item.text()),
6293                    Some("sentinel".to_string())
6294                );
6295
6296                // Revealing the value restores both.
6297                state.set_masked(false, window, cx);
6298                state.copy(&Copy, window, cx);
6299                assert_eq!(
6300                    cx.read_from_clipboard().and_then(|item| item.text()),
6301                    Some("hunter2".to_string())
6302                );
6303            });
6304        });
6305    }
6306
6307    #[gpui::test]
6308    fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
6309        let input_view = InputView::build(cx, |state| state);
6310        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6311        let input = input_view.input;
6312
6313        cx.update(|window, cx| {
6314            input.update(cx, |state, cx| {
6315                state.set_value("aaa bbb ccc", window, cx);
6316                state.set_masked(true, window, cx);
6317                state.set_selected_range(7..7, cx);
6318
6319                // The mask hides word boundaries, so a word delete takes
6320                // everything before the caret and leaves the rest.
6321                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
6322                assert_eq!(state.value(), " ccc");
6323                assert_eq!(state.selected_range(), 0..0);
6324
6325                state.delete_next_word(&DeleteToNextWordEnd, window, cx);
6326                assert_eq!(state.value(), "");
6327
6328                // A double click takes the whole value, not one word.
6329                state.set_value("aaa bbb ccc", window, cx);
6330                state.select_word(9, window, cx);
6331                assert_eq!(state.selected_range(), 0..11);
6332
6333                // Unmasked, the same delete only takes one word.
6334                state.set_masked(false, window, cx);
6335                state.set_value("aaa bbb ccc", window, cx);
6336                state.set_selected_range(11..11, cx);
6337                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
6338                assert_eq!(state.value(), "aaa bbb ");
6339
6340                state.set_value("aaa bbb ccc", window, cx);
6341                state.select_word(9, window, cx);
6342                assert_eq!(state.selected_range(), 8..11);
6343            });
6344        });
6345    }
6346
6347    #[gpui::test]
6348    fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
6349        let input_view = InputView::build(cx, |state| state);
6350        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6351        let input = input_view.input;
6352
6353        cx.update(|window, cx| {
6354            input.update(cx, |state, cx| {
6355                state.set_value("hunter2", window, cx);
6356                state.select_all(window, cx);
6357                assert!(state.context_menu_capabilities().is_copyable());
6358
6359                state.set_masked(true, window, cx);
6360                let capabilities = state.context_menu_capabilities();
6361                assert!(capabilities.is_masked());
6362                assert!(capabilities.has_selection());
6363                assert!(!capabilities.is_copyable());
6364            });
6365        });
6366    }
6367
6368    #[gpui::test]
6369    fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
6370        cx: &mut TestAppContext,
6371    ) {
6372        let input_view = InputView::build(cx, |state| state);
6373        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6374        let input = input_view.input;
6375
6376        cx.update(|window, cx| {
6377            input.update(cx, |state, cx| {
6378                state.replace_text_in_range(None, "alpha beta gamma", window, cx);
6379                state.set_selected_range(6..10, cx);
6380                state.cut(&Cut, window, cx);
6381                assert_eq!(state.value(), "alpha  gamma");
6382
6383                state.paste(&Paste, window, cx);
6384                state.paste(&Paste, window, cx);
6385                assert_eq!(state.value(), "alpha betabeta gamma");
6386
6387                state.undo(&Undo, window, cx);
6388                assert_eq!(state.value(), "alpha beta gamma");
6389                state.undo(&Undo, window, cx);
6390                assert_eq!(state.value(), "alpha  gamma");
6391                state.undo(&Undo, window, cx);
6392                assert_eq!(state.value(), "alpha beta gamma");
6393            });
6394        });
6395    }
6396
6397    #[gpui::test]
6398    fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
6399        let input_view = InputView::build_textarea(cx, |state| state);
6400        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6401        let input = input_view.input;
6402
6403        cx.update(|window, cx| {
6404            input.update(cx, |state, cx| {
6405                state.set_value("one two three\nfour five", window, cx);
6406                state.set_selected_range(13..13, cx);
6407                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
6408                assert_eq!(state.value(), "one two \nfour five");
6409                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
6410                assert_eq!(state.value(), "one two four five");
6411
6412                state.undo(&Undo, window, cx);
6413                assert_eq!(state.value(), "one two \nfour five");
6414                state.undo(&Undo, window, cx);
6415                assert_eq!(state.value(), "one two three\nfour five");
6416            });
6417        });
6418    }
6419
6420    #[gpui::test]
6421    fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
6422        let input_view = InputView::build_textarea(cx, |state| state);
6423        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6424        let input = input_view.input;
6425
6426        cx.update(|window, cx| {
6427            input.update(cx, |state, cx| {
6428                state.replace_text_in_range(None, "before", window, cx);
6429                state.set_selected_range(0..6, cx);
6430                state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
6431                assert_eq!(state.value(), "line one\nline two\n第三行");
6432
6433                state.undo(&Undo, window, cx);
6434                assert_eq!(state.value(), "before");
6435                assert_eq!(state.selected_range(), 0..6);
6436                state.redo(&Redo, window, cx);
6437                assert_eq!(state.value(), "line one\nline two\n第三行");
6438            });
6439        });
6440    }
6441
6442    #[gpui::test]
6443    fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
6444        let input_view = InputView::build(cx, |state| state);
6445        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6446        let input = input_view.input;
6447
6448        cx.update(|window, cx| {
6449            input.update(cx, |state, cx| {
6450                state.replace_text_in_range(None, "prefix ", window, cx);
6451                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
6452                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
6453                state.replace_and_mark_text_in_range(None, "你", None, window, cx);
6454                state.unmark_text(window, cx);
6455                state.replace_text_in_range(None, " suffix", window, cx);
6456                assert_eq!(state.value(), "prefix 你 suffix");
6457
6458                state.undo(&Undo, window, cx);
6459                assert_eq!(state.value(), "prefix 你");
6460                state.undo(&Undo, window, cx);
6461                assert_eq!(state.value(), "prefix ");
6462                state.undo(&Undo, window, cx);
6463                assert_eq!(state.value(), "");
6464            });
6465        });
6466    }
6467
6468    #[gpui::test]
6469    fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
6470        let input_view = InputView::build(cx, |state| state);
6471        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6472        let input = input_view.input;
6473
6474        cx.update(|window, cx| {
6475            input.update(cx, |state, cx| {
6476                state.replace_text_in_range(None, "abc", window, cx);
6477                state.set_selected_range(1..2, cx);
6478                state.replace_text_in_range(None, "X", window, cx);
6479                state.replace_text_in_range(None, "z", window, cx);
6480                assert_eq!(state.value(), "aXzc");
6481
6482                state.undo(&Undo, window, cx);
6483                assert_eq!(state.value(), "aXc");
6484                state.undo(&Undo, window, cx);
6485                assert_eq!(state.value(), "abc");
6486                state.undo(&Undo, window, cx);
6487                assert_eq!(state.value(), "");
6488            });
6489        });
6490    }
6491
6492    #[gpui::test]
6493    fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
6494        let input_view = InputView::build(cx, |state| {
6495            state.mask_pattern(MaskPattern::Number {
6496                separator: None,
6497                fraction: None,
6498            })
6499        });
6500        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6501        let input = input_view.input;
6502
6503        cx.update(|window, cx| {
6504            input.update(cx, |state, cx| {
6505                state.replace_text_in_range(None, "1.2", window, cx);
6506
6507                // Delete the integer part "1": the value keeps the leading dot
6508                // (".2"), not completed to "0.2", so the digits before the dot
6509                // stay editable.
6510                let range = state.range_to_utf16(&(0..1));
6511                state.replace_text_in_range(Some(range), "", window, cx);
6512                assert_eq!(state.value(), ".2");
6513                let cursor: Range<usize> = state.selected_range();
6514                assert_eq!(cursor, 0..0);
6515
6516                // The user can type a new integer part.
6517                state.replace_text_in_range(Some(0..0), "3", window, cx);
6518                assert_eq!(state.value(), "3.2");
6519            });
6520        });
6521    }
6522
6523    #[gpui::test]
6524    fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
6525        // A pre-existing invalid text (e.g. a `default_value` that does not
6526        // conform) must not trap the user, the edit is allowed to fix it.
6527        let input_view = InputView::build(cx, |state| {
6528            state
6529                .mask_pattern(MaskPattern::Number {
6530                    separator: None,
6531                    fraction: None,
6532                })
6533                .default_value("1,234")
6534        });
6535        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6536        let input = input_view.input;
6537
6538        cx.update(|window, cx| {
6539            input.update(cx, |state, cx| {
6540                // Delete the last char, the pending text "1,23" is still
6541                // invalid, but the edit is allowed since the old text was
6542                // already invalid.
6543                let range = state.range_to_utf16(&(4..5));
6544                state.replace_text_in_range(Some(range), "", window, cx);
6545                assert_eq!(state.value(), "1,23");
6546
6547                // Once the text becomes valid, the validation works as usual.
6548                let range = state.range_to_utf16(&(1..2));
6549                state.replace_text_in_range(Some(range), "", window, cx);
6550                assert_eq!(state.value(), "123");
6551                state.replace_text_in_range(None, "a", window, cx);
6552                assert_eq!(state.value(), "123");
6553            });
6554        });
6555    }
6556
6557    /// After `set_value` on a single-line input the caret sits at the end (like
6558    /// HTML `<input>`), yet the view is scrolled back to the start so a long
6559    /// value shows its beginning instead of its tail.
6560    #[gpui::test]
6561    fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
6562        let input_view = InputView::build(cx, |state| state);
6563        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6564        let input = input_view.input;
6565
6566        // Long enough to overflow any reasonable single-line input width.
6567        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
6568        let len = value.len();
6569
6570        // Right after `set_value`, before the next paint consumes the deferred
6571        // offset: caret is at the end, and the view is forced back to the start.
6572        cx.update(|window, cx| {
6573            input.update(cx, |state, cx| {
6574                state.set_value(value.clone(), window, cx);
6575
6576                assert_eq!(
6577                    state.selected_range(),
6578                    len..len,
6579                    "single-line caret should be at the end after set_value"
6580                );
6581                assert_eq!(
6582                    state.deferred_scroll_offset,
6583                    Some(point(px(0.), px(0.))),
6584                    "the view should be forced back to the start"
6585                );
6586            });
6587        });
6588
6589        // After a paint, the steady-state view stays at the start (x == 0) even
6590        // though the caret is at the far end.
6591        cx.run_until_parked();
6592        cx.update(|_, cx| {
6593            input.read_with(cx, |state, _| {
6594                assert!(
6595                    state.scroll_size.width > state.input_bounds.size.width,
6596                    "value must overflow the input width or this test is vacuous"
6597                );
6598                assert_eq!(
6599                    state.scroll_handle.offset().x,
6600                    px(0.),
6601                    "long value should display from its start, not its tail"
6602                );
6603            });
6604        });
6605    }
6606
6607    /// `replace_all` on a single-line input replaces the text, puts the
6608    /// caret at the end, and — like `set_value` — snaps the view back to the
6609    /// start so a long value shows its beginning instead of its tail.
6610    #[gpui::test]
6611    fn test_replace_all_single_line(cx: &mut TestAppContext) {
6612        let input_view = InputView::build(cx, |state| state);
6613        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6614        let input = input_view.input;
6615
6616        // Long enough to overflow any reasonable single-line input width.
6617        let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
6618        let len = value.len();
6619
6620        // Right after `replace_all`, before the next paint consumes the
6621        // deferred offset: caret is at the end, and the view is forced back
6622        // to the start.
6623        cx.update(|window, cx| {
6624            input.update(cx, |state, cx| {
6625                state.set_value("hello", window, cx);
6626                state.replace_all(value.clone(), window, cx);
6627                assert_eq!(state.value(), value);
6628                assert_eq!(
6629                    state.selected_range(),
6630                    len..len,
6631                    "single-line caret should be at the end after replace_all"
6632                );
6633                assert_eq!(
6634                    state.scroll_handle.offset(),
6635                    point(px(0.), px(0.)),
6636                    "the scroll offset should be reset to the start"
6637                );
6638                assert_eq!(
6639                    state.deferred_scroll_offset,
6640                    Some(point(px(0.), px(0.))),
6641                    "single-line should set a deferred scroll offset to keep the start visible"
6642                );
6643            });
6644        });
6645
6646        // After a paint, the steady-state view stays at the start (x == 0)
6647        // even though the caret is at the far end.
6648        cx.run_until_parked();
6649        cx.update(|_, cx| {
6650            input.read_with(cx, |state, _| {
6651                assert!(
6652                    state.scroll_size.width > state.input_bounds.size.width,
6653                    "value must overflow the input width or this test is vacuous"
6654                );
6655                assert_eq!(
6656                    state.scroll_handle.offset().x,
6657                    px(0.),
6658                    "long value should display from its start, not its tail"
6659                );
6660            });
6661        });
6662    }
6663
6664    #[gpui::test]
6665    fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
6666        let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
6667        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6668        let input = input_view.input;
6669
6670        cx.update(|window, cx| {
6671            input.update(cx, |state, cx| {
6672                assert_eq!(state.value(), "defaultvalue");
6673
6674                state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
6675                assert_eq!(state.value(), "firstsecondthirdfourth");
6676
6677                state.set_value("", window, cx);
6678                state.insert("a\nb", window, cx);
6679                assert_eq!(state.value(), "ab");
6680            });
6681
6682            cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
6683            input.update(cx, |state, cx| {
6684                state.set_value("", window, cx);
6685                state.paste(&Paste, window, cx);
6686                assert_eq!(state.value(), "abcd");
6687            });
6688        });
6689
6690        cx.run_until_parked();
6691    }
6692
6693    /// `replace_all` on a multi-line (non-code-editor) input clears the
6694    /// selection to `0..0` and resets the scroll offset, but does not set a
6695    /// deferred scroll offset (single-line only).
6696    #[gpui::test]
6697    fn test_replace_all_multi_line(cx: &mut TestAppContext) {
6698        let input_view = InputView::build_textarea(cx, |state| state);
6699        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6700        let input = input_view.input;
6701
6702        cx.update(|window, cx| {
6703            input.update(cx, |state, cx| {
6704                state.set_value("foo\nbar", window, cx);
6705                state.replace_all("baz\nqux", window, cx);
6706                assert_eq!(state.value(), "baz\nqux");
6707                assert_eq!(
6708                    state.selected_range(),
6709                    0..0,
6710                    "multi-line selection should be cleared after replace_all"
6711                );
6712                assert_eq!(
6713                    state.scroll_handle.offset(),
6714                    point(px(0.), px(0.)),
6715                    "the scroll offset should be reset to the start"
6716                );
6717                assert!(
6718                    state.deferred_scroll_offset.is_none(),
6719                    "multi-line should not set a deferred scroll offset"
6720                );
6721            });
6722        });
6723    }
6724
6725    /// Unlike `set_value`, `replace_all` records the change so the user can
6726    /// undo it back to the previous text and redo to the new text.
6727    #[gpui::test]
6728    fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
6729        let input_view = InputView::build(cx, |state| state);
6730        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6731        let input = input_view.input;
6732
6733        cx.update(|window, cx| {
6734            input.update(cx, |state, cx| {
6735                // Seed with a value and clear history so the baseline is clean.
6736                state.set_value("first", window, cx);
6737                assert!(
6738                    !state.undo_manager.has_undos(),
6739                    "history should be empty after set_value"
6740                );
6741
6742                // replace_all records a single undoable change.
6743                state.replace_all("second", window, cx);
6744                assert_eq!(state.value(), "second");
6745                assert!(
6746                    state.undo_manager.has_undos(),
6747                    "replace_all should record an undo step"
6748                );
6749
6750                // Undo restores the previous text.
6751                state.undo(&Undo, window, cx);
6752                assert_eq!(state.value(), "first");
6753
6754                // Redo reapplies the replacement.
6755                state.redo(&Redo, window, cx);
6756                assert_eq!(state.value(), "second");
6757            });
6758        });
6759    }
6760
6761    /// `replace_all` on a code editor marks a pending update and resets LSP
6762    /// state, so diagnostics/completions refresh against the new text.
6763    #[gpui::test]
6764    fn test_replace_all_code_editor(cx: &mut TestAppContext) {
6765        let input_view = InputView::new(cx);
6766        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6767        let input = input_view.input;
6768
6769        cx.update(|window, cx| {
6770            input.update(cx, |state, cx| {
6771                // Plant a pending-update flag and some LSP state to verify reset.
6772                state.set_value("select 1", window, cx);
6773                state._pending_update = false;
6774
6775                state.replace_all("select 2", window, cx);
6776                assert_eq!(state.value(), "select 2");
6777                assert!(
6778                    state._pending_update,
6779                    "replace_all on a code editor should request a pending update"
6780                );
6781            });
6782        });
6783    }
6784
6785    #[gpui::test]
6786    fn test_set_selected_range(cx: &mut TestAppContext) {
6787        let input_view = InputView::build(cx, |state| state.default_value("hello world"));
6788        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6789        let input = input_view.input;
6790
6791        cx.update(|_, cx| {
6792            input.update(cx, |s, cx| {
6793                s.set_selected_range(0..5, cx);
6794                assert_eq!(s.selected_range(), 0..5);
6795                assert_eq!(s.selected_text().to_string(), "hello");
6796
6797                s.set_selected_range(6..11, cx);
6798                assert_eq!(s.selected_text().to_string(), "world");
6799
6800                // clamped + collapsed
6801                s.set_selected_range(100..100, cx);
6802                assert_eq!(s.selected_range(), 11..11);
6803            });
6804        });
6805    }
6806
6807    /// A single-edit batch round-trips through undo/redo.
6808    #[gpui::test]
6809    fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
6810        let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
6811        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6812        let input = input_view.input;
6813
6814        cx.update(|window, cx| {
6815            input.update(cx, |s, cx| {
6816                s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
6817                assert_eq!(s.value(), "HELLO world");
6818
6819                s.undo(&Undo, window, cx);
6820                assert_eq!(s.value(), "hello world");
6821
6822                s.redo(&Redo, window, cx);
6823                assert_eq!(s.value(), "HELLO world");
6824            });
6825        });
6826    }
6827
6828    /// A single undo restores the exact original text and a single redo
6829    /// re-applies all edits, verifying the back-to-front application ordering.
6830    #[gpui::test]
6831    fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
6832        let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
6833        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6834        let input = input_view.input;
6835
6836        cx.update(|window, cx| {
6837            input.update(cx, |s, cx| {
6838                // Two edits at different positions, given in pre-edit
6839                // coordinates and in arbitrary (non-sorted) order.
6840                s.replace_text_in_ranges(
6841                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
6842                    window,
6843                    cx,
6844                );
6845                assert_eq!(s.value(), "X bbb Y");
6846
6847                // One collapsed cursor per edit, at the end of each inserted text.
6848                let cursors: Vec<usize> =
6849                    s.selections.iter().map(|sel| sel.cursor_offset()).collect();
6850                assert_eq!(cursors, vec![1, 7]);
6851
6852                // The whole batch is a single undo transaction.
6853                assert_eq!(s.undo_manager.undo_count(), 1);
6854
6855                // One undo restores the exact original text.
6856                s.undo(&Undo, window, cx);
6857                assert_eq!(s.value(), "aaa bbb ccc");
6858
6859                // One redo re-applies all edits.
6860                s.redo(&Redo, window, cx);
6861                assert_eq!(s.value(), "X bbb Y");
6862            });
6863        });
6864    }
6865
6866    /// A multi-edit change reaches the highlighter once, with every edit in
6867    /// application order and the text right after each, which is what the
6868    /// default `update_batch` replays through `update` one edit at a time.
6869    #[gpui::test]
6870    fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
6871        use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
6872        use gpui::HighlightStyle;
6873        use std::cell::RefCell;
6874
6875        struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
6876
6877        impl InputHighlighter for RecordingHighlighter {
6878            fn language(&self) -> SharedString {
6879                "recording".into()
6880            }
6881
6882            fn update(
6883                &mut self,
6884                _: Option<InputEdit>,
6885                text: &Rope,
6886                _: bool,
6887                _: &mut Window,
6888                _: &mut Context<EditorState>,
6889            ) {
6890                self.0.borrow_mut().push(vec![text.to_string()]);
6891            }
6892
6893            fn update_batch(
6894                &mut self,
6895                edits: &[(InputEdit, Rope)],
6896                _: bool,
6897                _: &mut Window,
6898                _: &mut Context<EditorState>,
6899            ) {
6900                let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
6901                self.0.borrow_mut().push(texts);
6902            }
6903
6904            fn styles(
6905                &self,
6906                range: &Range<usize>,
6907                _: &dyn HighlightStyleResolver,
6908            ) -> Vec<(Range<usize>, HighlightStyle)> {
6909                vec![(range.clone(), HighlightStyle::default())]
6910            }
6911
6912            fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
6913                Vec::new()
6914            }
6915        }
6916
6917        let updates = Rc::new(RefCell::new(Vec::new()));
6918        let input_view = InputView::new(cx);
6919        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6920        let input = input_view.input;
6921
6922        cx.update(|window, cx| {
6923            input.update(cx, |s, cx| {
6924                s.set_value("aaa bbb ccc", window, cx);
6925                let recorded = updates.clone();
6926                s.set_highlighter_factory(
6927                    Rc::new(move |_: &str| {
6928                        let highlighter: Box<dyn InputHighlighter> =
6929                            Box::new(RecordingHighlighter(recorded.clone()));
6930                        Some(highlighter)
6931                    }),
6932                    cx,
6933                );
6934                s.replace_text_in_ranges(
6935                    &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
6936                    window,
6937                    cx,
6938                );
6939            });
6940        });
6941
6942        assert_eq!(
6943            *updates.borrow(),
6944            vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
6945        );
6946    }
6947
6948    /// An IME composition (marking then commit) undoes as a single unit.
6949    #[gpui::test]
6950    fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
6951        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
6952        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6953        let input = input_view.input;
6954
6955        cx.update(|window, cx| {
6956            input.update(cx, |s, cx| {
6957                // Simulate an IME composition: mark, refine, then commit.
6958                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
6959                s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
6960                s.replace_text_in_range(None, "你", window, cx);
6961                assert_eq!(s.value(), "你");
6962
6963                // The entire composition is one undo transaction.
6964                assert_eq!(s.undo_manager.undo_count(), 1);
6965
6966                s.undo(&Undo, window, cx);
6967                assert_eq!(s.value(), "");
6968
6969                s.redo(&Redo, window, cx);
6970                assert_eq!(s.value(), "你");
6971            });
6972        });
6973    }
6974
6975    /// A keystroke right after a committed composition must be its own undo
6976    /// entry, not merged into the (finalized) composition transaction.
6977    #[gpui::test]
6978    fn test_edit_after_composition_is_separate_undo(cx: &mut TestAppContext) {
6979        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
6980        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
6981        let input = input_view.input;
6982
6983        cx.update(|window, cx| {
6984            input.update(cx, |s, cx| {
6985                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
6986                s.replace_text_in_range(None, "你", window, cx);
6987                assert_eq!(s.value(), "你");
6988                assert_eq!(s.undo_manager.undo_count(), 1);
6989
6990                // Typing after the commit is a distinct transaction.
6991                s.replace_text_in_range(None, "x", window, cx);
6992                assert_eq!(s.value(), "你x");
6993                assert_eq!(s.undo_manager.undo_count(), 2);
6994
6995                s.undo(&Undo, window, cx);
6996                assert_eq!(s.value(), "你");
6997                s.undo(&Undo, window, cx);
6998                assert_eq!(s.value(), "");
6999            });
7000        });
7001    }
7002
7003    /// Canceling a composition via `unmark_text` closes its transaction so it
7004    /// does not leak and swallow a later edit.
7005    #[gpui::test]
7006    fn test_composition_cancel_via_unmark_does_not_leak(cx: &mut TestAppContext) {
7007        let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
7008        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7009        let input = input_view.input;
7010
7011        cx.update(|window, cx| {
7012            input.update(cx, |s, cx| {
7013                // Start a composition, then cancel it via unmark.
7014                s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
7015                s.unmark_text(window, cx);
7016                let after_cancel = s.undo_manager.undo_count();
7017
7018                // A later edit is recorded independently.
7019                s.replace_text_in_range(None, "x", window, cx);
7020                assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
7021            });
7022        });
7023    }
7024
7025    #[gpui::test]
7026    fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
7027        let input_view = InputView::build(cx, |state| state.default_value("éx"));
7028        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7029        let input = input_view.input;
7030
7031        cx.update(|window, cx| {
7032            input.update(cx, |state, cx| {
7033                state.set_selected_range(0..1, cx);
7034                assert_eq!(state.selected_range(), 0..2);
7035                state.copy(&Copy, window, cx);
7036
7037                state.set_selected_range(1..1, cx);
7038                assert_eq!(state.selected_range(), 0..0);
7039            });
7040        });
7041    }
7042
7043    #[gpui::test]
7044    fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
7045        let input_view = InputView::build(cx, |state| state.default_value("你好 "));
7046        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7047        let input = input_view.input;
7048
7049        cx.update(|window, cx| {
7050            input.update(cx, |state, cx| {
7051                state.set_selected_range(7..7, cx);
7052                state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
7053                state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
7054
7055                assert_eq!(state.value(), "你好 sh");
7056                assert_eq!(state.selected_range(), 9..9);
7057                assert_eq!(state.ime_marked_range, Some((7..9).into()));
7058            });
7059        });
7060    }
7061
7062    #[gpui::test]
7063    fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
7064        let input_view = InputView::build(cx, |state| state);
7065        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7066        let input = input_view.input;
7067
7068        cx.update(|window, cx| {
7069            input.update(cx, |state, cx| {
7070                state.set_value("a", window, cx);
7071                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
7072                state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
7073                state.replace_text_in_range(None, "是", window, cx);
7074                assert_eq!(state.value(), "a是");
7075
7076                state.undo(&Undo, window, cx);
7077                assert_eq!(state.value(), "a");
7078                state.redo(&Redo, window, cx);
7079                assert_eq!(state.value(), "a是");
7080            });
7081        });
7082    }
7083
7084    #[gpui::test]
7085    fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
7086        let input_view = InputView::build(cx, |state| state);
7087        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7088        let input = input_view.input;
7089
7090        cx.update(|window, cx| {
7091            input.update(cx, |state, cx| {
7092                // First composition: "jin" -> "今天"
7093                state.replace_and_mark_text_in_range(None, "j", None, window, cx);
7094                state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
7095                state.replace_text_in_range(None, "今天", window, cx);
7096                // Second composition: "wo" -> "我们"
7097                state.replace_and_mark_text_in_range(None, "w", None, window, cx);
7098                state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
7099                state.replace_text_in_range(None, "我们", window, cx);
7100                assert_eq!(state.value(), "今天我们");
7101                assert_eq!(state.selected_range(), 12..12);
7102
7103                state.undo(&Undo, window, cx);
7104                assert_eq!(state.value(), "今天");
7105                assert_eq!(state.selected_range(), 6..6);
7106
7107                state.undo(&Undo, window, cx);
7108                assert_eq!(state.value(), "");
7109                assert_eq!(state.selected_range(), 0..0);
7110
7111                state.redo(&Redo, window, cx);
7112                assert_eq!(state.value(), "今天");
7113                assert_eq!(state.selected_range(), 6..6);
7114
7115                state.redo(&Redo, window, cx);
7116                assert_eq!(state.value(), "今天我们");
7117                assert_eq!(state.selected_range(), 12..12);
7118            });
7119        });
7120    }
7121
7122    #[gpui::test]
7123    fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
7124        let input_view = InputView::build(cx, |state| state);
7125        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7126        let input = input_view.input;
7127
7128        cx.update(|window, cx| {
7129            input.update(cx, |state, cx| {
7130                state.replace_and_mark_text_in_range(None, "n", None, window, cx);
7131                state.replace_text_in_range(None, "你", window, cx);
7132                state.undo_manager.set_pending_intent(EditIntent::Typing);
7133                state.replace_text_in_range(None, "a", window, cx);
7134                state.undo_manager.set_pending_intent(EditIntent::Typing);
7135                state.replace_text_in_range(None, "b", window, cx);
7136                assert_eq!(state.value(), "你ab");
7137
7138                state.undo(&Undo, window, cx);
7139                assert_eq!(state.value(), "你");
7140
7141                state.undo(&Undo, window, cx);
7142                assert_eq!(state.value(), "");
7143            });
7144        });
7145    }
7146
7147    #[gpui::test]
7148    fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
7149        let input_view = InputView::build(cx, |state| state);
7150        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7151        let input = input_view.input;
7152
7153        cx.update(|window, cx| {
7154            input.update(cx, |state, cx| {
7155                state.set_value("a", window, cx);
7156                state.replace_and_mark_text_in_range(None, "s", None, window, cx);
7157                state.replace_and_mark_text_in_range(None, "", None, window, cx);
7158
7159                assert_eq!(state.value(), "a");
7160                assert!(!state.undo_manager.has_undos());
7161            });
7162        });
7163    }
7164
7165    #[gpui::test]
7166    fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
7167        let input_view = InputView::build(cx, |state| state);
7168        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7169        let input = input_view.input;
7170
7171        cx.update(|window, cx| {
7172            input.update(cx, |state, cx| {
7173                state.set_value("abc", window, cx);
7174                state.set_selected_range(1..2, cx);
7175                state.replace_text_in_range(None, "X", window, cx);
7176
7177                state.undo(&Undo, window, cx);
7178                assert_eq!(state.value(), "abc");
7179                assert_eq!(state.selected_range(), 1..2);
7180
7181                state.redo(&Redo, window, cx);
7182                assert_eq!(state.value(), "aXc");
7183                assert_eq!(state.selected_range(), 2..2);
7184            });
7185        });
7186    }
7187
7188    #[gpui::test]
7189    fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
7190        let input_view = InputView::build(cx, |state| state);
7191        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7192        let input = input_view.input;
7193
7194        cx.update(|window, cx| {
7195            input.update(cx, |state, cx| {
7196                state.set_value("abc", window, cx);
7197                state.set_selected_range(1..1, cx);
7198                state.delete(&Delete, window, cx);
7199
7200                state.undo(&Undo, window, cx);
7201                assert_eq!(state.value(), "abc");
7202                assert_eq!(state.selected_range(), 1..1);
7203            });
7204        });
7205    }
7206
7207    #[gpui::test]
7208    fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
7209        let input_view = InputView::build(cx, |state| state);
7210        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7211        let input = input_view.input;
7212
7213        cx.update(|window, cx| {
7214            input.update(cx, |state, cx| {
7215                state.replace_text_in_range(None, "ab", window, cx);
7216                state.undo(&Undo, window, cx);
7217                state.set_selected_range(0..0, cx);
7218                state.redo(&Redo, window, cx);
7219                assert_eq!(state.value(), "ab");
7220
7221                state.undo(&Undo, window, cx);
7222                state.replace_text_in_range(None, "x", window, cx);
7223                state.redo(&Redo, window, cx);
7224                assert_eq!(state.value(), "x");
7225            });
7226        });
7227    }
7228
7229    #[gpui::test]
7230    fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
7231        let input_view = InputView::build(cx, |state| state);
7232        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7233        let input = input_view.input;
7234
7235        cx.update(|window, cx| {
7236            input.update(cx, |state, cx| {
7237                state.replace_text_in_range(None, "a", window, cx);
7238                state.move_to(0, None, cx);
7239                state.replace_text_in_range(None, "", window, cx);
7240                state.undo(&Undo, window, cx);
7241                assert_eq!(state.value(), "");
7242                state.redo(&Redo, window, cx);
7243                assert_eq!(state.value(), "a");
7244                assert_eq!(state.cursor(), 1);
7245            });
7246        });
7247    }
7248
7249    #[gpui::test]
7250    fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
7251        let input_view = InputView::build(cx, |state| state);
7252        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7253        let input = input_view.input;
7254
7255        cx.update(|window, cx| {
7256            input.update(cx, |state, cx| {
7257                state.replace_text_in_range(None, "a", window, cx);
7258                state.left(&MoveLeft, window, cx);
7259                state.right(&MoveRight, window, cx);
7260                state.replace_text_in_range(None, "b", window, cx);
7261
7262                state.undo(&Undo, window, cx);
7263                assert_eq!(state.value(), "a");
7264                state.undo(&Undo, window, cx);
7265                assert_eq!(state.value(), "");
7266            });
7267        });
7268    }
7269
7270    #[gpui::test]
7271    fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
7272        cx: &mut TestAppContext,
7273    ) {
7274        let input_view = InputView::build(cx, |state| state);
7275        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7276        let input = input_view.input;
7277
7278        cx.update(|window, cx| {
7279            input.update(cx, |state, cx| {
7280                state.replace_text_in_range(None, "alpha", window, cx);
7281                state.replace_text_in_range(None, "", window, cx);
7282                state.replace_text_in_range(None, "beta", window, cx);
7283                assert_eq!(state.value(), "alphabeta");
7284
7285                state.undo(&Undo, window, cx);
7286                assert_eq!(state.value(), "alpha");
7287                state.undo(&Undo, window, cx);
7288                assert_eq!(state.value(), "");
7289            });
7290        });
7291    }
7292
7293    #[gpui::test]
7294    fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
7295        let input_view = InputView::build(cx, |state| {
7296            state.mask_pattern(MaskPattern::Number {
7297                separator: Some(','),
7298                fraction: None,
7299            })
7300        });
7301        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7302        let input = input_view.input;
7303
7304        cx.update(|window, cx| {
7305            input.update(cx, |state, cx| {
7306                state.set_value("12345", window, cx);
7307                state.set_selected_range(2..2, cx);
7308                state.replace_text_in_range(None, "9", window, cx);
7309                let selection_after_edit = state.selected_range();
7310                assert_ne!(selection_after_edit.end, state.value().len());
7311
7312                state.undo(&Undo, window, cx);
7313                state.redo(&Redo, window, cx);
7314                assert_eq!(state.selected_range(), selection_after_edit);
7315            });
7316        });
7317    }
7318
7319    /// Unfolding at a position opens exactly the folds hiding it.
7320    ///
7321    /// A fold keeps its own first and last line visible, so a position on
7322    /// either of them opens nothing. Nested folds all open at once, sibling
7323    /// folds stay closed, and the opened ranges stay fold candidates.
7324    #[gpui::test]
7325    fn test_unfold_at(cx: &mut TestAppContext) {
7326        use crate::input::{FoldRange, Position};
7327
7328        let view = InputView::<EditorMode>::new(cx);
7329        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7330        let input = view.input;
7331
7332        // An outer fold over lines 0..=5, a fold nested inside it, and a
7333        // sibling fold that must never be touched.
7334        cx.update(|window, cx| {
7335            input.update(cx, |state, cx| {
7336                state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
7337                state.apply_highlighter_fold_candidates(
7338                    vec![
7339                        FoldRange::new(0, 5),
7340                        FoldRange::new(2, 4),
7341                        FoldRange::new(7, 10),
7342                    ],
7343                    cx,
7344                );
7345                state.display_map.set_folded(0, true);
7346                state.display_map.set_folded(2, true);
7347                state.display_map.set_folded(7, true);
7348            });
7349        });
7350
7351        // The outer fold's own first and last line stay visible, so neither
7352        // position opens anything.
7353        for line in [0, 5] {
7354            cx.update(|_, cx| {
7355                input.update(cx, |state, cx| {
7356                    assert!(!state.display_map.is_buffer_line_hidden(line));
7357                    assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
7358                });
7359                input.read_with(cx, |state, _| {
7360                    assert!(state.display_map.is_folded_at(0));
7361                    assert!(state.display_map.is_folded_at(2));
7362                    assert!(state.display_map.is_folded_at(7));
7363                });
7364            });
7365        }
7366
7367        // Line 3 is hidden by both the outer and the nested fold, so both
7368        // open; the sibling fold does not.
7369        cx.update(|_, cx| {
7370            input.update(cx, |state, cx| {
7371                assert!(state.unfold_at(Position::new(3, 0), cx));
7372            });
7373            input.read_with(cx, |state, _| {
7374                assert!(!state.display_map.is_buffer_line_hidden(3));
7375                assert!(!state.display_map.is_folded_at(0));
7376                assert!(!state.display_map.is_folded_at(2));
7377                assert!(state.display_map.is_folded_at(7));
7378                // The opened ranges are still candidates for refolding.
7379                assert!(state.display_map.is_fold_candidate(0));
7380                assert!(state.display_map.is_fold_candidate(2));
7381            });
7382        });
7383
7384        // Nothing is hidden there any more, so a second call is a no-op.
7385        cx.update(|_, cx| {
7386            input.update(cx, |state, cx| {
7387                assert!(!state.unfold_at(Position::new(3, 0), cx));
7388            });
7389        });
7390    }
7391
7392    /// Losing focus hides the hover popover but keeps the decorations.
7393    ///
7394    /// Both used to be dropped by one call, so clicking away threw away
7395    /// decorations the application had installed and never asked to remove.
7396    #[gpui::test]
7397    fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
7398        let view = InputView::<EditorMode>::new(cx);
7399        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7400        let input = view.input;
7401
7402        cx.update(|window, cx| {
7403            input.update(cx, |state, cx| {
7404                state.set_value("select 1", window, cx);
7405                let _collection = state.create_decorations_collection(
7406                    vec![crate::input::TextDecoration::new(
7407                        0..6,
7408                        gpui::HighlightStyle {
7409                            font_weight: Some(gpui::FontWeight::BOLD),
7410                            ..Default::default()
7411                        },
7412                    )],
7413                    cx,
7414                );
7415                state.present_hover(
7416                    0..6,
7417                    lsp_types::Hover {
7418                        contents: lsp_types::HoverContents::Scalar(
7419                            lsp_types::MarkedString::String("docs".into()),
7420                        ),
7421                        range: None,
7422                    },
7423                    cx,
7424                );
7425                assert!(state.hover_popover().is_some());
7426
7427                state.on_blur(window, cx);
7428
7429                assert!(
7430                    state.hover_popover().is_none(),
7431                    "blur should hide the hover popover"
7432                );
7433                let decorations = state.extras.decoration_layers();
7434                assert!(
7435                    decorations.iter().any(|layer| !layer.is_empty()),
7436                    "blur must not discard decorations"
7437                );
7438            });
7439        });
7440    }
7441
7442    /// The mode marker is the only source of truth for the kind of input.
7443    ///
7444    /// An auto-growing textarea capped at one row used to report itself as
7445    /// single-line, because the answer was derived from the row counts.
7446    #[gpui::test]
7447    fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
7448        let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
7449        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7450        view.input.read_with(&mut cx, |state, _| {
7451            assert!(state.is_multi_line());
7452            assert!(!state.is_single_line());
7453            assert!(!state.is_code_editor());
7454        });
7455    }
7456
7457    /// Soft wrap is on by default, for every mode that can wrap.
7458    ///
7459    /// The default lives in the shared constructor, where a mode-specific
7460    /// `new` can silently fail to restore it; this pins it down.
7461    #[gpui::test]
7462    fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
7463        let textarea = InputView::build_textarea(cx, |state| state);
7464        let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
7465        textarea
7466            .input
7467            .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
7468
7469        let editor = InputView::<EditorMode>::new(cx);
7470        let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
7471        editor
7472            .input
7473            .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
7474    }
7475
7476    /// Parse a cursor spec into `(text, cursor_offsets)`. Non-empty lines are
7477    /// joined with `\n` plus a trailing `\n`. `|` marks a cursor. Leading
7478    /// whitespace is kept, so a spec can express indentation.
7479    fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
7480        let mut full_text = String::new();
7481        let mut cursor_offsets = Vec::new();
7482        let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
7483
7484        for (line_idx, line) in non_empty_lines.iter().enumerate() {
7485            let mut positions = Vec::new();
7486            let mut text = String::new();
7487            for ch in line.chars() {
7488                if ch == '|' {
7489                    positions.push(text.len());
7490                } else {
7491                    text.push(ch);
7492                }
7493            }
7494
7495            if line_idx > 0 {
7496                full_text.push('\n');
7497            }
7498            let line_start = full_text.len();
7499            for pos in positions {
7500                cursor_offsets.push(line_start + pos);
7501            }
7502            full_text.push_str(&text);
7503        }
7504        full_text.push('\n');
7505
7506        (full_text, cursor_offsets)
7507    }
7508
7509    /// Build a multi-line input for multi-cursor tests.
7510    fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
7511        InputView::build_textarea(cx, |state| state)
7512    }
7513
7514    /// Set the text and cursor positions from a spec (see [`parse_cursor_spec`]).
7515    fn setup_cursors<M: InputModeKind>(
7516        cx: &mut VisualTestContext,
7517        input: &Entity<InputBaseState<M>>,
7518        spec: &str,
7519    ) {
7520        let (full_text, offsets) = parse_cursor_spec(spec);
7521        cx.update(|window, cx| {
7522            input.update(cx, |state, cx| {
7523                state.set_value(&full_text, window, cx);
7524                let selections = offsets
7525                    .into_iter()
7526                    .map(|offset| {
7527                        CursorSelection::new(state.selections.generate_id(), offset, offset)
7528                    })
7529                    .collect();
7530                state.selections.replace_all(selections);
7531                cx.notify();
7532            });
7533        });
7534    }
7535
7536    /// Assert the text and cursor positions match a spec.
7537    #[track_caller]
7538    fn assert_cursors<M: InputModeKind>(
7539        cx: &mut VisualTestContext,
7540        input: &Entity<InputBaseState<M>>,
7541        spec: &str,
7542    ) {
7543        let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
7544        expected_cursors.sort();
7545
7546        let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
7547            (
7548                state.text.to_string(),
7549                state
7550                    .selections
7551                    .iter()
7552                    .map(|s| s.cursor_offset())
7553                    .collect::<Vec<_>>(),
7554            )
7555        });
7556        actual_cursors.sort();
7557
7558        assert_eq!(
7559            actual_text, expected_text,
7560            "Text mismatch:\nExpected: {expected_text:?}\nActual:   {actual_text:?}"
7561        );
7562        assert_eq!(
7563            actual_cursors, expected_cursors,
7564            "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual:   {actual_cursors:?}"
7565        );
7566    }
7567
7568    #[gpui::test]
7569    fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
7570        cx.update(crate::init);
7571        let view = InputView::<EditorMode>::new(cx);
7572        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7573        for modifiers in [
7574            gpui::Modifiers {
7575                alt: true,
7576                ..Default::default()
7577            },
7578            gpui::Modifiers {
7579                alt: true,
7580                shift: true,
7581                ..Default::default()
7582            },
7583            #[cfg(target_os = "linux")]
7584            gpui::Modifiers {
7585                alt: true,
7586                control: true,
7587                ..Default::default()
7588            },
7589        ] {
7590            setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
7591            cx.update(|window, cx| {
7592                view.input.update(cx, |state, cx| state.focus(window, cx));
7593            });
7594            let (start, end) = view.input.read_with(&cx, |state, _| {
7595                let layout = state.last_layout.as_ref().unwrap();
7596                let origin = state.last_bounds.unwrap().origin;
7597                let position = |row: usize, col| {
7598                    let local = layout.lines[row]
7599                        .position_for_index(col, layout, false)
7600                        .unwrap();
7601                    origin
7602                        + point(
7603                            layout.line_number_width + local.x,
7604                            layout.line_height * (row as f32 + 0.5),
7605                        )
7606                };
7607                (position(0, 1), position(2, 3))
7608            });
7609            // Land inside the third column instead of exactly on its trailing
7610            // glyph boundary, where pixel rounding can select the next column.
7611            let end = point(end.x - px(0.5), end.y);
7612            // A cached Ctrl-hover definition must not steal a column gesture.
7613            cx.update(|_, cx| {
7614                view.input.update(cx, |state, _| {
7615                    state.extras.hover_definition.update(
7616                        0..4,
7617                        vec![lsp_types::LocationLink {
7618                            origin_selection_range: None,
7619                            target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
7620                            target_range: Default::default(),
7621                            target_selection_range: Default::default(),
7622                        }],
7623                    );
7624                });
7625            });
7626            cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
7627            cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
7628            cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
7629            view.input.read_with(&cx, |state, _| {
7630                let ranges: Vec<_> = state
7631                    .selections
7632                    .iter()
7633                    .map(|sel| sel.start..sel.end)
7634                    .collect();
7635                assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
7636            });
7637            // Moving after release must leave the block intact.
7638            cx.simulate_mouse_move(start, None, modifiers);
7639            cx.simulate_keystrokes("x");
7640            assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
7641        }
7642    }
7643
7644    #[gpui::test]
7645    fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
7646        cx.update(crate::init);
7647        let view = InputView::<EditorMode>::new(cx);
7648        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7649        setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
7650        cx.update(|window, cx| {
7651            view.input.update(cx, |state, cx| state.focus(window, cx));
7652        });
7653        let (start, end) = view.input.read_with(&cx, |state, _| {
7654            let layout = state.last_layout.as_ref().unwrap();
7655            let origin = state.last_bounds.unwrap().origin;
7656            let local = layout.lines[0]
7657                .position_for_index(1, layout, false)
7658                .unwrap();
7659            let x = layout.line_number_width + local.x;
7660            (
7661                origin + point(x, layout.line_height * 2.5),
7662                origin + point(x, layout.line_height * 0.5),
7663            )
7664        });
7665        let modifiers = gpui::Modifiers {
7666            alt: true,
7667            ..Default::default()
7668        };
7669        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
7670        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
7671        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
7672        assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
7673    }
7674
7675    #[gpui::test]
7676    fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
7677        cx.update(crate::init);
7678        let view = InputView::<EditorMode>::new(cx);
7679        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7680        setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
7681        cx.update(|window, cx| {
7682            view.input.update(cx, |state, cx| state.focus(window, cx));
7683        });
7684        // Drag from row 0 column 1 down to row 1, at the x of row 0's column 5. Row 1
7685        // only has two characters, so the pointer ends past its end.
7686        let (start, end) = view.input.read_with(&cx, |state, _| {
7687            let layout = state.last_layout.as_ref().unwrap();
7688            let origin = state.last_bounds.unwrap().origin;
7689            let x_of = |index| {
7690                layout.line_number_width
7691                    + layout.lines[0]
7692                        .position_for_index(index, layout, false)
7693                        .unwrap()
7694                        .x
7695            };
7696            (
7697                origin + point(x_of(1), layout.line_height * 0.5),
7698                origin + point(x_of(5), layout.line_height * 1.5),
7699            )
7700        });
7701        let modifiers = gpui::Modifiers {
7702            alt: true,
7703            shift: true,
7704            ..Default::default()
7705        };
7706        cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
7707        cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
7708        cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
7709
7710        // The short row is clipped to its own end; the long row keeps the full span.
7711        view.input.read_with(&cx, |state, _| {
7712            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
7713            assert_eq!(ranges, vec![(1, 5), (8, 9)]);
7714        });
7715    }
7716
7717    #[gpui::test]
7718    fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
7719        cx.update(crate::init);
7720        let view = InputView::<EditorMode>::new(cx);
7721        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7722        setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
7723        let position = view.input.read_with(&cx, |state, _| {
7724            let layout = state.last_layout.as_ref().unwrap();
7725            state.last_bounds.unwrap().origin
7726                + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
7727        });
7728        let modifiers = gpui::Modifiers {
7729            alt: true,
7730            ..Default::default()
7731        };
7732        cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
7733        cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
7734        view.input.read_with(&cx, |state, _| {
7735            assert!(!state.selecting);
7736            assert!(state.column_select_start.is_none());
7737        });
7738    }
7739
7740    #[gpui::test]
7741    fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
7742        let view = InputView::<EditorMode>::new(cx);
7743        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7744        setup_cursors(&mut cx, &view.input, "a|b");
7745        cx.update(|window, cx| {
7746            view.input.update(cx, |state, cx| {
7747                state.focus(window, cx);
7748                state.pause_blink_cursor(cx);
7749            });
7750        });
7751        cx.run_until_parked();
7752        cx.executor()
7753            .advance_clock(std::time::Duration::from_millis(300));
7754        cx.run_until_parked();
7755        view.input.read_with(&cx, |state, cx| {
7756            assert!(!state.blink_cursor.read(cx).visible());
7757        });
7758        // Copy consumes its shortcut without editing text or moving selections.
7759        for _ in 0..5 {
7760            #[cfg(target_os = "macos")]
7761            cx.simulate_keystrokes("cmd-c");
7762            #[cfg(not(target_os = "macos"))]
7763            cx.simulate_keystrokes("ctrl-c");
7764            cx.run_until_parked();
7765            cx.executor()
7766                .advance_clock(std::time::Duration::from_millis(200));
7767            cx.run_until_parked();
7768            view.input.read_with(&cx, |state, cx| {
7769                assert!(state.blink_cursor.read(cx).visible());
7770            });
7771        }
7772    }
7773
7774    #[gpui::test]
7775    fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
7776        let view = InputView::<EditorMode>::new(cx);
7777        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7778        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
7779        // Start each action in the hidden phase without depending on a
7780        // key-down listener: actions and text input also arrive directly.
7781        for action in 0..6 {
7782            cx.update(|_, cx| {
7783                view.input.update(cx, |state, cx| {
7784                    state.blink_cursor = cx.new(|_| BlinkCursor::new());
7785                    state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
7786                });
7787            });
7788            cx.run_until_parked();
7789            cx.executor()
7790                .advance_clock(std::time::Duration::from_millis(500));
7791            cx.run_until_parked();
7792            view.input.read_with(&cx, |state, cx| {
7793                assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
7794            });
7795
7796            cx.update(|window, cx| {
7797                view.input.update(cx, |state, cx| {
7798                    match action {
7799                        0 => state.add_cursor_above(&AddCursorAbove, window, cx),
7800                        1 => state.add_cursor_below(&AddCursorBelow, window, cx),
7801                        2 => state.select_up(&SelectUp, window, cx),
7802                        3 => state.select_down(&SelectDown, window, cx),
7803                        4 => state.replace_text_in_range(None, "x", window, cx),
7804                        _ => state.backspace(&Backspace, window, cx),
7805                    }
7806                    assert!(state.blink_cursor.read(cx).visible(), "action {action}");
7807                });
7808            });
7809        }
7810    }
7811
7812    #[gpui::test]
7813    fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
7814        let view = InputView::<EditorMode>::new(cx);
7815        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7816        setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
7817        cx.update(|window, cx| {
7818            view.input.update(cx, |state, cx| state.focus(window, cx));
7819        });
7820        #[cfg(target_os = "macos")]
7821        cx.simulate_keystrokes("cmd-alt-up");
7822        #[cfg(target_os = "windows")]
7823        cx.simulate_keystrokes("ctrl-alt-up");
7824        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
7825        cx.simulate_keystrokes("alt-shift-up");
7826        view.input
7827            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
7828        #[cfg(target_os = "macos")]
7829        cx.simulate_keystrokes("cmd-alt-down");
7830        #[cfg(target_os = "windows")]
7831        cx.simulate_keystrokes("ctrl-alt-down");
7832        #[cfg(not(any(target_os = "macos", target_os = "windows")))]
7833        cx.simulate_keystrokes("alt-shift-down");
7834        view.input
7835            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
7836        cx.simulate_keystrokes("x");
7837        assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
7838    }
7839
7840    #[gpui::test]
7841    fn test_multi_cursor_platform_word_selection_dispatch(cx: &mut TestAppContext) {
7842        let view = InputView::<EditorMode>::new(cx);
7843        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7844        setup_cursors(&mut cx, &view.input, "one |two\none |two");
7845        cx.update(|window, cx| {
7846            view.input.update(cx, |state, cx| state.focus(window, cx));
7847        });
7848        #[cfg(any(target_os = "macos", target_os = "linux"))]
7849        cx.simulate_keystrokes("alt-shift-right");
7850        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
7851        cx.simulate_keystrokes("ctrl-shift-right");
7852        cx.simulate_keystrokes("x");
7853        assert_cursors(&mut cx, &view.input, "one x|\none x|");
7854        setup_cursors(&mut cx, &view.input, "one two|\none two|");
7855        #[cfg(any(target_os = "macos", target_os = "linux"))]
7856        cx.simulate_keystrokes("alt-shift-left");
7857        #[cfg(not(any(target_os = "macos", target_os = "linux")))]
7858        cx.simulate_keystrokes("ctrl-shift-left");
7859        cx.simulate_keystrokes("x");
7860        assert_cursors(&mut cx, &view.input, "one x|\none x|");
7861    }
7862
7863    #[cfg(not(target_os = "macos"))]
7864    #[gpui::test]
7865    fn test_multi_cursor_horizontal_selection_dispatch(cx: &mut TestAppContext) {
7866        let view = InputView::<EditorMode>::new(cx);
7867        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7868        setup_cursors(&mut cx, &view.input, "ab\na|b");
7869        cx.update(|window, cx| {
7870            view.input.update(cx, |state, cx| state.focus(window, cx));
7871        });
7872        #[cfg(target_os = "windows")]
7873        cx.simulate_keystrokes("ctrl-alt-up");
7874        #[cfg(not(target_os = "windows"))]
7875        cx.simulate_keystrokes("alt-shift-up");
7876        #[cfg(target_os = "linux")]
7877        cx.simulate_keystrokes("shift-right");
7878        #[cfg(not(target_os = "linux"))]
7879        cx.simulate_keystrokes("alt-shift-right");
7880        view.input.read_with(&cx, |state, _| {
7881            assert_eq!(
7882                state
7883                    .selections
7884                    .iter()
7885                    .map(|s| s.start..s.end)
7886                    .collect::<Vec<_>>(),
7887                vec![4..5, 1..2]
7888            );
7889        });
7890        #[cfg(target_os = "linux")]
7891        cx.simulate_keystrokes("shift-left shift-left");
7892        #[cfg(not(target_os = "linux"))]
7893        cx.simulate_keystrokes("alt-shift-left alt-shift-left");
7894        view.input.read_with(&cx, |state, _| {
7895            assert_eq!(
7896                state
7897                    .selections
7898                    .iter()
7899                    .map(|s| s.start..s.end)
7900                    .collect::<Vec<_>>(),
7901                vec![3..4, 0..1]
7902            );
7903        });
7904        cx.simulate_keystrokes("x");
7905        assert_cursors(&mut cx, &view.input, "x|b\nx|b");
7906    }
7907
7908    #[gpui::test]
7909    fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
7910        cx.update(crate::init);
7911        let view = InputView::<EditorMode>::new(cx);
7912        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7913        setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
7914        cx.update(|window, cx| {
7915            view.input.update(cx, |state, cx| state.focus(window, cx));
7916        });
7917        let position = view.input.read_with(&cx, |state, _| {
7918            let bounds = state.last_bounds.unwrap();
7919            let layout = state.last_layout.as_ref().unwrap();
7920            bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
7921        });
7922        cx.simulate_click(
7923            position,
7924            gpui::Modifiers {
7925                alt: true,
7926                ..Default::default()
7927            },
7928        );
7929        view.input
7930            .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
7931    }
7932
7933    #[gpui::test]
7934    fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
7935        let view = multi_line(cx);
7936        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7937        setup_cursors(&mut cx, &view.input, "hello|");
7938        cx.update(|window, cx| {
7939            view.input.update(cx, |state, cx| {
7940                state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
7941                state.undo(&Undo, window, cx);
7942                assert_eq!(state.selected_range(), 5..5);
7943            });
7944        });
7945    }
7946
7947    #[gpui::test]
7948    fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
7949        let view = multi_line(cx);
7950        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7951        setup_cursors(&mut cx, &view.input, "a|b|c");
7952        cx.update(|window, cx| {
7953            view.input.update(cx, |state, cx| {
7954                state.backspace(&Backspace, window, cx);
7955                state.undo(&Undo, window, cx);
7956            });
7957        });
7958        assert_cursors(&mut cx, &view.input, "a|b|c");
7959    }
7960
7961    #[gpui::test]
7962    fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
7963        let view = InputView::<EditorMode>::new(cx);
7964        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7965        cx.update(|window, cx| {
7966            view.input.update(cx, |state, cx| {
7967                state.set_value("abcdef ".repeat(30), window, cx);
7968                state.display_map.on_layout_changed(Some(px(60.)), cx);
7969                let line = state.display_map.line(0).unwrap();
7970                assert!(line.wrapped_lines.len() > 1);
7971                let boundary = line.wrapped_lines[0].end;
7972                state.move_to_with_affinity(boundary, None, true, cx);
7973                state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
7974                assert_eq!(state.selected_range(), boundary..state.text.len());
7975            });
7976        });
7977    }
7978
7979    #[gpui::test]
7980    fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
7981        let view = multi_line(cx);
7982        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7983        setup_cursors(&mut cx, &view.input, "|你好\n|世界");
7984        cx.update(|window, cx| {
7985            view.input.update(cx, |state, cx| {
7986                state.outdent(false, window, cx);
7987                state.outdent(true, window, cx);
7988            });
7989        });
7990        assert_cursors(&mut cx, &view.input, "|你好\n|世界");
7991    }
7992
7993    #[gpui::test]
7994    fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
7995        let view = multi_line(cx);
7996        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7997        setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
7998        cx.update(|window, cx| {
7999            view.input.update(cx, |state, cx| {
8000                state.build_columnar_selection(
8001                    ColumnarPoint::new(1, 0),
8002                    ColumnarPoint::new(11, 0),
8003                    cx,
8004                );
8005                let text = state.value();
8006                for sel in state.selections.iter() {
8007                    assert!(text.is_char_boundary(sel.start));
8008                    assert!(text.is_char_boundary(sel.end));
8009                }
8010                state.replace_text_in_range(None, "X", window, cx);
8011            });
8012        });
8013    }
8014
8015    #[gpui::test]
8016    fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
8017        let view = InputView::<EditorMode>::new(cx);
8018        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8019        cx.update(|window, cx| {
8020            view.input.update(cx, |state, cx| {
8021                state.set_value("abc def", window, cx);
8022                state.create_decorations_collection(
8023                    vec![crate::input::TextDecoration::new(
8024                        4..7,
8025                        gpui::HighlightStyle::default(),
8026                    )],
8027                    cx,
8028                );
8029                state.set_selected_range(0..0, cx);
8030                state.replace_text_in_range(None, "X", window, cx);
8031                let layers = state.extras.decoration_layers();
8032                assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
8033            });
8034        });
8035    }
8036
8037    #[gpui::test]
8038    fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
8039        let view = InputView::<EditorMode>::new(cx);
8040        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8041        setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
8042        cx.update(|window, cx| {
8043            view.input.update(cx, |state, cx| {
8044                set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
8045                state.backspace(&Backspace, window, cx);
8046            });
8047        });
8048        assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
8049    }
8050
8051    #[gpui::test]
8052    fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
8053        struct UnexpectedQuery;
8054        impl crate::input::SyntaxContextProvider for UnexpectedQuery {
8055            fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
8056                panic!("ordinary typing must not query syntax");
8057            }
8058        }
8059        let view = InputView::<EditorMode>::new(cx);
8060        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8061        setup_cursors(&mut cx, &view.input, "|");
8062        cx.update(|window, cx| {
8063            view.input.update(cx, |state, cx| {
8064                set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
8065                for c in ["a", "b", "c"] {
8066                    state.replace_text_in_range(None, c, window, cx);
8067                }
8068            });
8069        });
8070        assert_cursors(&mut cx, &view.input, "abc|");
8071    }
8072
8073    #[gpui::test]
8074    fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
8075        let view = InputView::<EditorMode>::new(cx);
8076        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8077        setup_cursors(&mut cx, &view.input, "|");
8078        cx.update(|window, cx| {
8079            view.input.update(cx, |state, cx| {
8080                for _ in 0..999 {
8081                    state.replace_text_in_range(None, "a", window, cx);
8082                }
8083                state.replace_text_in_range(None, "(", window, cx);
8084                state.undo(&Undo, window, cx);
8085                assert!(!state.text.to_string().contains('('));
8086                assert!(!state.text.to_string().contains(')'));
8087                state.redo(&Redo, window, cx);
8088            });
8089        });
8090        assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
8091    }
8092
8093    #[gpui::test]
8094    fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
8095        let view = InputView::<EditorMode>::new(cx);
8096        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8097        setup_cursors(&mut cx, &view.input, "// (|)");
8098        cx.update(|window, cx| {
8099            view.input.update(cx, |state, cx| {
8100                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
8101                state.replace_text_in_range(None, ")", window, cx);
8102            });
8103        });
8104        assert_cursors(&mut cx, &view.input, "// ()|)");
8105    }
8106
8107    #[gpui::test]
8108    fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
8109        let view = InputView::<EditorMode>::new(cx);
8110        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8111        setup_cursors(&mut cx, &view.input, "(a|)");
8112        let before = view.input.read_with(&cx, |state, _| state.text.to_string());
8113        cx.update(|window, cx| {
8114            view.input.update(cx, |state, cx| {
8115                state.replace_text_in_range(Some(2..2), ")", window, cx);
8116            });
8117        });
8118        assert_cursors(&mut cx, &view.input, "(a)|");
8119        cx.update(|window, cx| {
8120            view.input
8121                .update(cx, |state, cx| state.undo(&Undo, window, cx));
8122        });
8123        view.input.read_with(&cx, |state, _| {
8124            assert_eq!(
8125                state.text.to_string(),
8126                before,
8127                "skip must not remove an existing closer on undo"
8128            );
8129        });
8130    }
8131
8132    #[gpui::test]
8133    fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
8134        let view = InputView::<EditorMode>::new(cx);
8135        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8136        setup_cursors(&mut cx, &view.input, "|");
8137        cx.update(|window, cx| {
8138            view.input.update(cx, |state, cx| {
8139                state.replace_text_in_range(None, "(", window, cx);
8140            });
8141        });
8142        assert_cursors(&mut cx, &view.input, "(|)");
8143        cx.update(|window, cx| {
8144            view.input.update(cx, |state, cx| {
8145                state.undo(&Undo, window, cx);
8146                state.redo(&Redo, window, cx);
8147            });
8148        });
8149        assert_cursors(&mut cx, &view.input, "(|)");
8150    }
8151
8152    #[gpui::test]
8153    fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
8154        let view = InputView::<EditorMode>::new(cx);
8155        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8156        setup_cursors(&mut cx, &view.input, "{|}");
8157        cx.update(|window, cx| {
8158            view.input.update(cx, |state, cx| {
8159                state.enter(
8160                    &Enter {
8161                        secondary: false,
8162                        shift: false,
8163                    },
8164                    window,
8165                    cx,
8166                );
8167            });
8168        });
8169        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
8170        cx.update(|window, cx| {
8171            view.input.update(cx, |state, cx| {
8172                state.undo(&Undo, window, cx);
8173            });
8174        });
8175        assert_cursors(&mut cx, &view.input, "{|}");
8176        cx.update(|window, cx| {
8177            view.input
8178                .update(cx, |state, cx| state.redo(&Redo, window, cx));
8179        });
8180        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
8181    }
8182
8183    #[gpui::test]
8184    fn test_auto_close_parens(cx: &mut TestAppContext) {
8185        let view = InputView::<EditorMode>::new(cx);
8186        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8187        setup_cursors(&mut cx, &view.input, "|");
8188        cx.update(|window, cx| {
8189            view.input.update(cx, |state, cx| {
8190                state.replace_text_in_range(None, "(", window, cx);
8191            });
8192        });
8193        assert_cursors(&mut cx, &view.input, "(|)");
8194        // Selection must be collapsed: typing next must insert, not replace.
8195        cx.update(|window, cx| {
8196            view.input.update(cx, |state, cx| {
8197                state.replace_text_in_range(None, "x", window, cx);
8198            });
8199        });
8200        assert_cursors(&mut cx, &view.input, "(x|)");
8201    }
8202
8203    #[gpui::test]
8204    fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
8205        let view = InputView::<EditorMode>::new(cx);
8206        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8207        setup_cursors(&mut cx, &view.input, "(|)");
8208        cx.update(|window, cx| {
8209            view.input.update(cx, |state, cx| {
8210                state.replace_text_in_range(None, ")", window, cx);
8211            });
8212        });
8213        // No duplicate closer, cursor moves past the existing one.
8214        assert_cursors(&mut cx, &view.input, "()|");
8215        // Selection must be collapsed, not covering blank space.
8216        view.input.read_with(&cx, |state, _| {
8217            assert!(state.active_selection().is_empty());
8218        });
8219    }
8220
8221    #[gpui::test]
8222    fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
8223        let view = InputView::<EditorMode>::new(cx);
8224        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8225        setup_cursors(&mut cx, &view.input, "don|");
8226        cx.update(|window, cx| {
8227            view.input.update(cx, |state, cx| {
8228                state.replace_text_in_range(None, "'", window, cx);
8229            });
8230        });
8231        // Contraction: no auto-close.
8232        assert_cursors(&mut cx, &view.input, "don'|");
8233    }
8234
8235    #[gpui::test]
8236    fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
8237        let view = InputView::<EditorMode>::new(cx);
8238        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8239        // Unicode-safe previous-char lookup: must not panic on multi-byte prefix.
8240        // CJK counts as word-like, so no pairing — single quote inserted.
8241        setup_cursors(&mut cx, &view.input, "中|");
8242        cx.update(|window, cx| {
8243            view.input.update(cx, |state, cx| {
8244                state.replace_text_in_range(None, "'", window, cx);
8245            });
8246        });
8247        assert_cursors(&mut cx, &view.input, "中'|");
8248    }
8249
8250    #[gpui::test]
8251    fn test_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
8252        let view = InputView::<EditorMode>::new(cx);
8253        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8254        // Cursor before existing closing quote: typing `"` skips past it.
8255        setup_cursors(&mut cx, &view.input, "\"hello|\"");
8256        cx.update(|window, cx| {
8257            view.input.update(cx, |state, cx| {
8258                state.replace_text_in_range(None, "\"", window, cx);
8259            });
8260        });
8261        assert_cursors(&mut cx, &view.input, "\"hello\"|");
8262        view.input.read_with(&cx, |state, _| {
8263            assert!(state.active_selection().is_empty());
8264        });
8265    }
8266
8267    #[gpui::test]
8268    fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
8269        let view = InputView::<EditorMode>::new(cx);
8270        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8271        // UTF-16 conversion: deleting `()` after CJK must not touch neighbors.
8272        setup_cursors(&mut cx, &view.input, "中(|)abc");
8273        cx.update(|window, cx| {
8274            view.input
8275                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
8276        });
8277        assert_cursors(&mut cx, &view.input, "中|abc");
8278    }
8279
8280    #[gpui::test]
8281    fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
8282        let view = InputView::<EditorMode>::new(cx);
8283        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8284        setup_cursors(&mut cx, &view.input, "{|}");
8285        cx.update(|window, cx| {
8286            view.input.update(cx, |state, cx| {
8287                state.set_smart_indent(false, window, cx);
8288                state.enter(
8289                    &Enter {
8290                        secondary: false,
8291                        shift: false,
8292                    },
8293                    window,
8294                    cx,
8295                );
8296            });
8297        });
8298        // Smart indent controls both structural splitting and extra indentation.
8299        assert_cursors(&mut cx, &view.input, "{\n|}");
8300    }
8301
8302    #[gpui::test]
8303    fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
8304        let view = InputView::<EditorMode>::new(cx);
8305        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8306        setup_cursors(&mut cx, &view.input, "{|}");
8307        cx.update(|window, cx| {
8308            view.input.update(cx, |state, cx| {
8309                state.set_auto_close(false, window, cx);
8310                state.enter(
8311                    &Enter {
8312                        secondary: false,
8313                        shift: false,
8314                    },
8315                    window,
8316                    cx,
8317                );
8318            });
8319        });
8320        // Disabling automatic insertion does not disable structural indentation.
8321        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
8322    }
8323
8324    #[gpui::test]
8325    fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
8326        use crate::input::{AutoClosingPair, set_language_config};
8327        let view = InputView::<EditorMode>::new(cx);
8328        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8329        cx.update(|window, cx| {
8330            set_language_config(
8331                "alpha",
8332                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
8333                cx,
8334            );
8335            set_language_config(
8336                "beta",
8337                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
8338                cx,
8339            );
8340            let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
8341            let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
8342            first.update(cx, |state, cx| {
8343                state.replace_text_in_range(None, "«", window, cx);
8344                assert_eq!(state.text().to_string(), "«»");
8345                state.set_value("", window, cx);
8346                state.set_smart_indent(false, window, cx);
8347                state.set_highlighter("beta", cx);
8348                assert!(!state.mode.is_smart_indent());
8349                state.replace_text_in_range(None, "‹", window, cx);
8350                assert_eq!(state.text().to_string(), "‹›");
8351                state.set_value("", window, cx);
8352                state.set_highlighter("unknown", cx);
8353                state.replace_text_in_range(None, "(", window, cx);
8354                assert_eq!(state.text().to_string(), "()");
8355            });
8356            second.update(cx, |state, cx| {
8357                state.replace_text_in_range(None, "‹", window, cx);
8358                assert_eq!(state.text().to_string(), "‹›");
8359            });
8360        });
8361    }
8362
8363    #[gpui::test]
8364    fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
8365        use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
8366        struct StringLanguages(Rc<Cell<usize>>);
8367        impl LanguageProvider for StringLanguages {
8368            fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
8369                self.0.set(self.0.get() + 1);
8370                Some(Rc::new(StringAllProvider))
8371            }
8372        }
8373        struct CodeLanguages;
8374        impl LanguageProvider for CodeLanguages {}
8375        let view = InputView::<EditorMode>::new(cx);
8376        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8377        cx.update(|window, cx| {
8378            let creations = Rc::new(Cell::new(0));
8379            set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
8380            view.input.update(cx, |state, cx| {
8381                state.replace_text_in_range(None, "(", window, cx);
8382                state.replace_text_in_range(None, "[", window, cx);
8383                assert_eq!(state.text().to_string(), "([");
8384                assert_eq!(
8385                    creations.get(),
8386                    1,
8387                    "retain the document provider between edits"
8388                );
8389            });
8390            set_language_provider(Rc::new(CodeLanguages), cx);
8391            view.input.update(cx, |state, cx| {
8392                state.replace_text_in_range(None, "{", window, cx);
8393                assert_eq!(state.text().to_string(), "([{}");
8394            });
8395        });
8396    }
8397
8398    #[gpui::test]
8399    fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
8400        use crate::input::{AutoClosingPair, set_language_config};
8401        let view = InputView::<EditorMode>::new(cx);
8402        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8403        setup_cursors(&mut cx, &view.input, "|");
8404        cx.update(|window, cx| {
8405            view.input.update(cx, |state, cx| {
8406                state.set_highlighter("CUSTOM", cx);
8407                state.set_auto_close(false, window, cx);
8408                state.set_smart_indent(false, window, cx);
8409            });
8410            set_language_config(
8411                "custom",
8412                LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
8413                cx,
8414            );
8415            // Batched registrations must update every affected language.
8416            set_language_config("other", LanguageConfig::default(), cx);
8417            view.input.update(cx, |state, cx| {
8418                assert!(!state.mode.is_auto_close());
8419                assert!(!state.mode.is_smart_indent());
8420                state.set_auto_close(true, window, cx);
8421                state.replace_text_in_range(None, "«", window, cx);
8422            });
8423        });
8424        assert_cursors(&mut cx, &view.input, "«|»");
8425    }
8426
8427    #[gpui::test]
8428    fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
8429        let view = InputView::<EditorMode>::new(cx);
8430        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8431        setup_cursors(&mut cx, &view.input, "|word");
8432        cx.update(|window, cx| {
8433            view.input.update(cx, |state, cx| {
8434                state.replace_text_in_range(None, "(", window, cx)
8435            });
8436        });
8437        assert_cursors(&mut cx, &view.input, "(|word");
8438        setup_cursors(&mut cx, &view.input, "|word");
8439        cx.update(|window, cx| {
8440            view.input.update(cx, |state, cx| {
8441                crate::input::set_language_config(
8442                    state.language_name(),
8443                    LanguageConfig::default().auto_close_before("w"),
8444                    cx,
8445                );
8446                state.replace_text_in_range(None, "(", window, cx);
8447            });
8448        });
8449        assert_cursors(&mut cx, &view.input, "(|)word");
8450    }
8451
8452    #[gpui::test]
8453    fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
8454        use crate::input::{AutoClosingPair, SyntaxContext};
8455        let view = InputView::<EditorMode>::new(cx);
8456        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8457        setup_cursors(&mut cx, &view.input, "|");
8458        cx.update(|window, cx| {
8459            view.input.update(cx, |state, cx| {
8460                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
8461                crate::input::set_language_config(
8462                    state.language_name(),
8463                    LanguageConfig::default().auto_closing_pairs([
8464                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
8465                        AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
8466                    ]),
8467                    cx,
8468                );
8469                state.replace_text_in_range(None, "(", window, cx);
8470                state.replace_text_in_range(None, "[", window, cx);
8471            });
8472        });
8473        assert_cursors(&mut cx, &view.input, "([|)");
8474    }
8475
8476    #[gpui::test]
8477    fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
8478        use crate::input::{AutoClosingPair, SyntaxContext};
8479        struct BlockComment;
8480        impl crate::input::SyntaxContextProvider for BlockComment {
8481            fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
8482                if text.to_string().contains("/*") {
8483                    SyntaxContext::Comment
8484                } else {
8485                    SyntaxContext::Code
8486                }
8487            }
8488        }
8489        let view = InputView::<EditorMode>::new(cx);
8490        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8491        setup_cursors(&mut cx, &view.input, "|");
8492        cx.update(|window, cx| {
8493            view.input.update(cx, |state, cx| {
8494                set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
8495                crate::input::set_language_config(
8496                    state.language_name(),
8497                    LanguageConfig::default()
8498                        .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
8499                            .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
8500                    cx,
8501                );
8502                state.replace_text_in_range(None, "/", window, cx);
8503                state.replace_text_in_range(None, "*", window, cx);
8504            });
8505        });
8506        assert_cursors(&mut cx, &view.input, "/*|*/");
8507        cx.update(|window, cx| {
8508            view.input
8509                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
8510        });
8511        assert_cursors(&mut cx, &view.input, "|");
8512        cx.update(|window, cx| {
8513            view.input.update(cx, |state, cx| {
8514                state.undo(&Undo, window, cx);
8515                state.replace_text_in_range(None, "*", window, cx);
8516                state.replace_text_in_range(None, "/", window, cx);
8517            });
8518        });
8519        assert_cursors(&mut cx, &view.input, "/**/|");
8520    }
8521
8522    #[gpui::test]
8523    fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
8524        use crate::input::BracketPair;
8525        let view = InputView::<EditorMode>::new(cx);
8526        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8527        setup_cursors(&mut cx, &view.input, "|");
8528        cx.update(|window, cx| {
8529            view.input.update(cx, |state, cx| {
8530                let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
8531                rules.auto_closing_pairs = None;
8532                crate::input::set_language_config(state.language_name(), rules.clone(), cx);
8533                state.replace_text_in_range(None, "«", window, cx);
8534                crate::input::set_language_config(
8535                    state.language_name(),
8536                    rules.auto_closing_pairs([]),
8537                    cx,
8538                );
8539                state.replace_text_in_range(None, "«", window, cx);
8540            });
8541        });
8542        assert_cursors(&mut cx, &view.input, "««|»");
8543    }
8544
8545    #[gpui::test]
8546    fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
8547        use crate::input::{AutoClosingPair, SyntaxContext};
8548        let view = InputView::<EditorMode>::new(cx);
8549        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8550        setup_cursors(&mut cx, &view.input, "|");
8551        cx.update(|window, cx| {
8552            view.input.update(cx, |state, cx| {
8553                crate::input::set_language_config(
8554                    state.language_name(),
8555                    LanguageConfig::default()
8556                        .auto_closing_pairs([
8557                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
8558                        ]),
8559                    cx,
8560                );
8561                state.replace_text_in_range(None, "/", window, cx);
8562                state.replace_text_in_range(None, "*", window, cx);
8563                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
8564                state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
8565                state.undo(&Undo, window, cx);
8566                state.replace_text_in_range(None, "*", window, cx);
8567                state.replace_text_in_range(None, "/", window, cx);
8568            });
8569        });
8570        assert_cursors(&mut cx, &view.input, "/**/|");
8571    }
8572
8573    #[gpui::test]
8574    fn test_undo_does_not_promote_literal_comment_delimiters(cx: &mut TestAppContext) {
8575        use crate::input::{AutoClosingPair, SyntaxContext};
8576        let view = InputView::<EditorMode>::new(cx);
8577        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8578        setup_cursors(&mut cx, &view.input, "/*|*/");
8579        cx.update(|window, cx| {
8580            view.input.update(cx, |state, cx| {
8581                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
8582                crate::input::set_language_config(
8583                    state.language_name(),
8584                    LanguageConfig::default()
8585                        .auto_closing_pairs([
8586                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
8587                        ]),
8588                    cx,
8589                );
8590                state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
8591                state.undo(&Undo, window, cx);
8592                state.backspace(&Backspace, window, cx);
8593            });
8594        });
8595        assert_cursors(&mut cx, &view.input, "/|*/");
8596    }
8597
8598    #[gpui::test]
8599    fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
8600        use crate::input::{AutoClosingPair, SyntaxContext};
8601        struct CommentScope;
8602        impl crate::input::SyntaxContextProvider for CommentScope {
8603            fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
8604                if text
8605                    .to_string()
8606                    .find("*/")
8607                    .is_some_and(|end| offset < end + 2)
8608                {
8609                    SyntaxContext::Comment
8610                } else {
8611                    SyntaxContext::Code
8612                }
8613            }
8614        }
8615        let view = InputView::<EditorMode>::new(cx);
8616        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8617        setup_cursors(&mut cx, &view.input, "|");
8618        cx.update(|window, cx| {
8619            view.input.update(cx, |state, cx| {
8620                set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
8621                crate::input::set_language_config(
8622                    state.language_name(),
8623                    LanguageConfig::default().auto_closing_pairs([
8624                        AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
8625                        AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
8626                    ]),
8627                    cx,
8628                );
8629                state.replace_text_in_range(None, "/", window, cx);
8630                state.replace_text_in_range(None, "*", window, cx);
8631                state.set_selected_range(4..4, cx);
8632                state.replace_text_in_range(None, "(", window, cx);
8633                state.set_selected_range(2..2, cx);
8634                state.replace_text_in_range(None, "*", window, cx);
8635                state.replace_text_in_range(None, "/", window, cx);
8636            });
8637        });
8638        assert_cursors(&mut cx, &view.input, "/**/|()");
8639        cx.update(|window, cx| {
8640            view.input.update(cx, |state, cx| {
8641                state.set_selected_range(2..2, cx);
8642                state.backspace(&Backspace, window, cx);
8643                state.undo(&Undo, window, cx);
8644                state.redo(&Redo, window, cx);
8645            });
8646        });
8647        assert_cursors(&mut cx, &view.input, "|()");
8648    }
8649
8650    #[gpui::test]
8651    fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
8652        use crate::input::{AutoClosingPair, SyntaxContext};
8653        let view = InputView::<EditorMode>::new(cx);
8654        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8655        setup_cursors(&mut cx, &view.input, "|");
8656        cx.update(|window, cx| {
8657            view.input.update(cx, |state, cx| {
8658                crate::input::set_language_config(
8659                    state.language_name(),
8660                    LanguageConfig::default()
8661                        .auto_closing_pairs([
8662                            AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
8663                        ]),
8664                    cx,
8665                );
8666                state.replace_text_in_range(None, "/", window, cx);
8667                state.replace_text_in_range(None, "*", window, cx);
8668                state.replace_text_in_range(Some(0..2), "//", window, cx);
8669                set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
8670                state.replace_text_in_range(None, "*", window, cx);
8671            });
8672        });
8673        assert_cursors(&mut cx, &view.input, "//*|*/");
8674    }
8675
8676    #[gpui::test]
8677    fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
8678        use crate::input::IndentationRules;
8679        let view = InputView::<EditorMode>::new(cx);
8680        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8681        setup_cursors(&mut cx, &view.input, "BEGIN|");
8682        cx.update(|window, cx| {
8683            view.input.update(cx, |state, cx| {
8684                let rules = |insensitive| {
8685                    LanguageConfig::default().indentation_rules(IndentationRules::new(
8686                        regex::RegexBuilder::new("begin$")
8687                            .case_insensitive(insensitive)
8688                            .build()
8689                            .unwrap(),
8690                        regex::Regex::new("^end").unwrap(),
8691                    ))
8692                };
8693                crate::input::set_language_config(state.language_name(), rules(false), cx);
8694                crate::input::set_language_config(state.language_name(), rules(true), cx);
8695                state.enter(
8696                    &Enter {
8697                        secondary: false,
8698                        shift: false,
8699                    },
8700                    window,
8701                    cx,
8702                );
8703            });
8704        });
8705        assert_cursors(&mut cx, &view.input, "BEGIN\n  |");
8706    }
8707
8708    #[gpui::test]
8709    fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
8710        use crate::input::IndentationRules;
8711        let view = InputView::<EditorMode>::new(cx);
8712        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8713        let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
8714            regex::Regex::new(r"\bbegin\s*$").unwrap(),
8715            regex::Regex::new(r"^\s*end\b").unwrap(),
8716        ));
8717        for (before, expected) in [("begin|", "begin\n  |"), ("  |end", "  \n|end")] {
8718            setup_cursors(&mut cx, &view.input, before);
8719            cx.update(|window, cx| {
8720                view.input.update(cx, |state, cx| {
8721                    crate::input::set_language_config(state.language_name(), rules.clone(), cx);
8722                    state.enter(
8723                        &Enter {
8724                            secondary: false,
8725                            shift: false,
8726                        },
8727                        window,
8728                        cx,
8729                    );
8730                });
8731            });
8732            assert_cursors(&mut cx, &view.input, expected);
8733        }
8734    }
8735
8736    #[gpui::test]
8737    fn test_custom_language_config(cx: &mut TestAppContext) {
8738        let view = InputView::<EditorMode>::new(cx);
8739        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8740        cx.update(|_window, cx| {
8741            view.input.update(cx, |state, cx| {
8742                crate::input::set_language_config(
8743                    state.language_name(),
8744                    crate::input::language_config::LanguageConfig::default()
8745                        .brackets([crate::input::BracketPair::new("«", "»")])
8746                        .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
8747                    cx,
8748                );
8749            });
8750        });
8751        // Custom pair closes.
8752        setup_cursors(&mut cx, &view.input, "|");
8753        cx.update(|window, cx| {
8754            view.input.update(cx, |state, cx| {
8755                state.replace_text_in_range(None, "«", window, cx);
8756            });
8757        });
8758        assert_cursors(&mut cx, &view.input, "«|»");
8759        // Default `(` no longer pairs under custom rules.
8760        cx.update(|window, cx| {
8761            view.input.update(cx, |state, cx| {
8762                state.set_value("\n", window, cx);
8763                state.set_selected_range(0..0, cx);
8764                state.replace_text_in_range(None, "(", window, cx);
8765            });
8766        });
8767        assert_cursors(&mut cx, &view.input, "(|");
8768    }
8769
8770    #[gpui::test]
8771    fn test_skip_records_no_history(cx: &mut TestAppContext) {
8772        let view = InputView::<EditorMode>::new(cx);
8773        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8774        setup_cursors(&mut cx, &view.input, "(a|)");
8775        cx.update(|window, cx| {
8776            view.input.update(cx, |state, cx| {
8777                // Type a normal char (recorded), then skip over `)`.
8778                state.replace_text_in_range(None, "b", window, cx);
8779            });
8780        });
8781        assert_cursors(&mut cx, &view.input, "(ab|)");
8782        cx.update(|window, cx| {
8783            view.input.update(cx, |state, cx| {
8784                state.replace_text_in_range(None, ")", window, cx);
8785            });
8786        });
8787        // Skip is a pure cursor move: no history entry of its own.
8788        assert_cursors(&mut cx, &view.input, "(ab)|");
8789        // Undo removes `b`, never exposing a transient `())`.
8790        cx.update(|window, cx| {
8791            view.input
8792                .update(cx, |state, cx| state.undo(&Undo, window, cx));
8793        });
8794        assert_cursors(&mut cx, &view.input, "(a|)");
8795    }
8796
8797    #[gpui::test]
8798    fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
8799        let view = InputView::<EditorMode>::new(cx);
8800        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8801        setup_cursors(&mut cx, &view.input, "|");
8802        cx.update(|window, cx| {
8803            view.input.update(cx, |state, cx| {
8804                state.replace_text_in_range(None, "(", window, cx);
8805            });
8806        });
8807        assert_cursors(&mut cx, &view.input, "(|)");
8808        // One undo removes the whole pair (typing coalescing).
8809        cx.update(|window, cx| {
8810            view.input
8811                .update(cx, |state, cx| state.undo(&Undo, window, cx));
8812        });
8813        assert_cursors(&mut cx, &view.input, "|");
8814    }
8815
8816    #[gpui::test]
8817    fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
8818        let view = InputView::<EditorMode>::new(cx);
8819        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8820        // Odd backslashes: the typed quote is escaped, insert literally.
8821        setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
8822        cx.update(|window, cx| {
8823            view.input.update(cx, |state, cx| {
8824                state.replace_text_in_range(None, "\"", window, cx);
8825            });
8826        });
8827        assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
8828    }
8829
8830    #[gpui::test]
8831    fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
8832        let view = InputView::<EditorMode>::new(cx);
8833        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8834        // Even backslashes: quote is not escaped, skip over the terminator.
8835        setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
8836        cx.update(|window, cx| {
8837            view.input.update(cx, |state, cx| {
8838                state.replace_text_in_range(None, "\"", window, cx);
8839            });
8840        });
8841        assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
8842    }
8843
8844    #[gpui::test]
8845    fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
8846        use crate::input::{BracketPair, LanguageConfig};
8847
8848        let view = InputView::<EditorMode>::new(cx);
8849        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8850        cx.update(|window, cx| {
8851            view.input.update(cx, |state, cx| {
8852                // Language changes update rules without changing editor preferences.
8853                state.set_smart_indent(false, window, cx);
8854                crate::input::set_language_config(
8855                    state.language_name(),
8856                    LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
8857                    cx,
8858                );
8859            });
8860        });
8861        view.input.read_with(&cx, |state, _| {
8862            assert!(!state.mode.is_smart_indent(), "editor option preserved");
8863            assert!(state.mode.is_auto_close());
8864            let pairs = &state.mode.language_config().unwrap().brackets;
8865            assert_eq!(pairs.len(), 1, "pairs follow configuration");
8866            assert_eq!(pairs[0].open.as_ref(), "«");
8867        });
8868    }
8869
8870    struct CommentAllProvider;
8871    impl crate::input::SyntaxContextProvider for CommentAllProvider {
8872        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
8873            crate::input::SyntaxContext::Comment
8874        }
8875    }
8876
8877    struct StringAllProvider;
8878    impl crate::input::SyntaxContextProvider for StringAllProvider {
8879        fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
8880            crate::input::SyntaxContext::String
8881        }
8882    }
8883
8884    #[gpui::test]
8885    fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
8886        use std::rc::Rc;
8887
8888        let view = InputView::<EditorMode>::new(cx);
8889        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8890        cx.update(|_window, cx| {
8891            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
8892        });
8893        // Trigger `{` inside a string: no extra level, base indent only.
8894        setup_cursors(&mut cx, &view.input, "  x = {|");
8895        cx.update(|window, cx| {
8896            view.input.update(cx, |state, cx| {
8897                state.enter(
8898                    &Enter {
8899                        secondary: false,
8900                        shift: false,
8901                    },
8902                    window,
8903                    cx,
8904                );
8905            });
8906        });
8907        assert_cursors(&mut cx, &view.input, "  x = {\n  |");
8908    }
8909
8910    #[gpui::test]
8911    fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
8912        use std::rc::Rc;
8913
8914        let view = InputView::<EditorMode>::new(cx);
8915        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8916        cx.update(|_window, cx| {
8917            set_test_syntax_provider(Rc::new(StringAllProvider), cx);
8918        });
8919        // No three-way split inside strings: plain newline instead.
8920        setup_cursors(&mut cx, &view.input, "{|}");
8921        cx.update(|window, cx| {
8922            view.input.update(cx, |state, cx| {
8923                state.enter(
8924                    &Enter {
8925                        secondary: false,
8926                        shift: false,
8927                    },
8928                    window,
8929                    cx,
8930                );
8931            });
8932        });
8933        assert_cursors(&mut cx, &view.input, "{\n|}");
8934    }
8935
8936    #[gpui::test]
8937    fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
8938        use std::rc::Rc;
8939
8940        let view = InputView::<EditorMode>::new(cx);
8941        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8942        cx.update(|_window, cx| {
8943            set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
8944        });
8945        setup_cursors(&mut cx, &view.input, "|");
8946        cx.update(|window, cx| {
8947            view.input.update(cx, |state, cx| {
8948                state.replace_text_in_range(None, "(", window, cx);
8949            });
8950        });
8951        // In comments every character is literal.
8952        assert_cursors(&mut cx, &view.input, "(|");
8953    }
8954
8955    #[gpui::test]
8956    fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
8957        let view = InputView::<EditorMode>::new(cx);
8958        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8959        setup_cursors(&mut cx, &view.input, "{|}");
8960        cx.update(|window, cx| {
8961            view.input
8962                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
8963        });
8964        assert_cursors(&mut cx, &view.input, "|");
8965    }
8966
8967    #[gpui::test]
8968    fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
8969        let view = InputView::<EditorMode>::new(cx);
8970        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8971        setup_cursors(&mut cx, &view.input, "{d|}");
8972        cx.update(|window, cx| {
8973            view.input
8974                .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
8975        });
8976        // Only `d` is deleted, the closing brace stays.
8977        assert_cursors(&mut cx, &view.input, "{|}");
8978    }
8979
8980    #[gpui::test]
8981    fn test_enter_splits_brackets(cx: &mut TestAppContext) {
8982        let view = InputView::<EditorMode>::new(cx);
8983        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
8984        setup_cursors(&mut cx, &view.input, "{|}");
8985        cx.update(|window, cx| {
8986            view.input.update(cx, |state, cx| {
8987                state.enter(
8988                    &Enter {
8989                        secondary: false,
8990                        shift: false,
8991                    },
8992                    window,
8993                    cx,
8994                );
8995            });
8996        });
8997        assert_cursors(&mut cx, &view.input, "{\n  |\n}");
8998        // Selection must be collapsed: typing next must insert, not replace.
8999        view.input.read_with(&cx, |state, _| {
9000            assert!(state.active_selection().is_empty());
9001        });
9002        cx.update(|window, cx| {
9003            view.input.update(cx, |state, cx| {
9004                state.replace_text_in_range(None, "x", window, cx);
9005            });
9006        });
9007        assert_cursors(&mut cx, &view.input, "{\n  x|\n}");
9008    }
9009
9010    #[gpui::test]
9011    fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
9012        let view = InputView::<EditorMode>::new(cx);
9013        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9014        setup_cursors(&mut cx, &view.input, "fn main() {|");
9015        cx.update(|window, cx| {
9016            view.input.update(cx, |state, cx| {
9017                state.enter(
9018                    &Enter {
9019                        secondary: false,
9020                        shift: false,
9021                    },
9022                    window,
9023                    cx,
9024                );
9025            });
9026        });
9027        assert_cursors(&mut cx, &view.input, "fn main() {\n  |");
9028    }
9029
9030    #[gpui::test]
9031    fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
9032        let view = multi_line(cx);
9033        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9034        setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
9035        cx.update(|window, cx| {
9036            view.input
9037                .update(cx, |state, cx| state.indent(true, window, cx));
9038        });
9039        assert_cursors(&mut cx, &view.input, "  |ab\n  |cd\n  |ef");
9040        cx.update(|window, cx| {
9041            view.input
9042                .update(cx, |state, cx| state.outdent(true, window, cx));
9043        });
9044        assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
9045    }
9046
9047    #[gpui::test]
9048    fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
9049        let view = multi_line(cx);
9050        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9051        setup_cursors(&mut cx, &view.input, "ab\n | cd");
9052        cx.update(|window, cx| {
9053            view.input
9054                .update(cx, |state, cx| state.outdent(true, window, cx));
9055        });
9056        assert_cursors(&mut cx, &view.input, "ab\n|cd");
9057    }
9058
9059    #[gpui::test]
9060    fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
9061        let view = InputView::build(cx, |state| state);
9062        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9063        cx.update(|window, cx| {
9064            view.input.update(cx, |state, cx| {
9065                state.set_value("abc", window, cx);
9066                state.set_selected_range(1..2, cx);
9067                state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
9068                state.replace_text_in_range(None, "你", window, cx);
9069                state.undo(&Undo, window, cx);
9070                assert_eq!(state.value(), "abc");
9071                assert_eq!(state.selected_range(), 1..2);
9072                state.redo(&Redo, window, cx);
9073                assert_eq!(state.selected_range(), 4..4);
9074            });
9075        });
9076    }
9077
9078    #[gpui::test]
9079    fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
9080        let view = multi_line(cx);
9081        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9082        cx.update(|window, cx| {
9083            view.input.update(cx, |state, cx| {
9084                state.set_value("abc", window, cx);
9085                state.set_selected_range(1..1, cx);
9086                state.replace_text_in_range(None, "X", window, cx);
9087                state.set_selected_range(0..0, cx);
9088                state.replace_text_in_range(None, "", window, cx);
9089                state.undo(&Undo, window, cx);
9090                state.redo(&Redo, window, cx);
9091                assert_eq!(state.value(), "aXbc");
9092                assert_eq!(state.selected_range(), 2..2);
9093            });
9094        });
9095    }
9096
9097    #[gpui::test]
9098    fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
9099        let view = multi_line(cx);
9100        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9101        let input = view.input;
9102
9103        setup_cursors(&mut cx, &input, "|hello |world|");
9104        cx.update(|window, cx| {
9105            input.update(cx, |state, cx| {
9106                state.replace_text_in_range(None, ">>>", window, cx);
9107            });
9108        });
9109        assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
9110    }
9111
9112    #[gpui::test]
9113    fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
9114        let view = multi_line(cx);
9115        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9116        let input = view.input;
9117
9118        setup_cursors(&mut cx, &input, "|islands| cars|");
9119        cx.update(|window, cx| {
9120            input.update(cx, |state, cx| {
9121                state.backspace(&Backspace, window, cx);
9122            });
9123        });
9124        // The first cursor has nothing to delete. The others delete an `s`.
9125        assert_cursors(&mut cx, &input, "|island| car|");
9126    }
9127
9128    #[gpui::test]
9129    fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
9130        let view = multi_line(cx);
9131        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9132        let input = view.input;
9133
9134        setup_cursors(&mut cx, &input, "hello| |world");
9135        cx.update(|window, cx| {
9136            input.update(cx, |state, cx| {
9137                state.delete(&Delete, window, cx);
9138            });
9139        });
9140        // Adjacent deletions merge into a single cursor.
9141        assert_cursors(&mut cx, &input, "hello|orld");
9142    }
9143
9144    #[gpui::test]
9145    fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
9146        let view = multi_line(cx);
9147        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9148        let input = view.input;
9149
9150        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9151        cx.update(|window, cx| {
9152            input.update(cx, |state, cx| {
9153                state.replace_text_in_range(None, "a", window, cx);
9154            });
9155        });
9156        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
9157
9158        // The whole multi-edit insert is a single undo transaction.
9159        input.read_with(&cx, |state, _| {
9160            assert_eq!(state.undo_manager.undo_count(), 1);
9161        });
9162
9163        cx.update(|window, cx| {
9164            input.update(cx, |state, cx| {
9165                state.backspace(&Backspace, window, cx);
9166            });
9167        });
9168        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9169    }
9170
9171    #[gpui::test]
9172    fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
9173        let view = multi_line(cx);
9174        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9175        let input = view.input;
9176
9177        setup_cursors(&mut cx, &input, "ab|cd\nabcd");
9178        cx.update(|window, cx| {
9179            input.update(cx, |state, cx| {
9180                state.add_cursor_below(&AddCursorBelow, window, cx);
9181            });
9182        });
9183        assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
9184    }
9185
9186    #[gpui::test]
9187    fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
9188        let view = multi_line(cx);
9189        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9190        let input = view.input;
9191
9192        setup_cursors(&mut cx, &input, "he|llo");
9193        cx.update(|_, cx| {
9194            input.update(cx, |state, cx| {
9195                // Duplicate of the existing cursor is rejected.
9196                state.add_cursor_at(2, cx);
9197                assert_eq!(state.selections.len(), 1);
9198                // A distinct offset adds a cursor.
9199                state.add_cursor_at(4, cx);
9200                assert_eq!(state.selections.len(), 2);
9201            });
9202        });
9203    }
9204
9205    #[gpui::test]
9206    fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
9207        let view = multi_line(cx);
9208        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9209        let input = view.input;
9210
9211        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9212        cx.update(|window, cx| {
9213            input.update(cx, |state, cx| {
9214                state.replace_text_in_range(None, "a", window, cx);
9215            });
9216        });
9217        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
9218
9219        cx.update(|window, cx| {
9220            input.update(cx, |state, cx| {
9221                state.undo(&Undo, window, cx);
9222            });
9223        });
9224        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9225
9226        cx.update(|window, cx| {
9227            input.update(cx, |state, cx| {
9228                state.redo(&Redo, window, cx);
9229            });
9230        });
9231        assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
9232    }
9233
9234    #[gpui::test]
9235    fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
9236        let view = multi_line(cx);
9237        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9238        let input = view.input;
9239
9240        setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
9241        cx.update(|window, cx| {
9242            input.update(cx, |state, cx| {
9243                state.replace_text_in_range(None, "a", window, cx);
9244            });
9245        });
9246        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
9247
9248        cx.update(|window, cx| {
9249            input.update(cx, |state, cx| {
9250                state.undo(&Undo, window, cx);
9251            });
9252        });
9253        assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
9254
9255        cx.update(|window, cx| {
9256            input.update(cx, |state, cx| {
9257                state.redo(&Redo, window, cx);
9258            });
9259        });
9260        assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
9261    }
9262
9263    #[gpui::test]
9264    fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
9265        let view = multi_line(cx);
9266        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9267        let input = view.input;
9268
9269        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9270        for ch in ['a', 'b', 'c'] {
9271            cx.update(|window, cx| {
9272                input.update(cx, |state, cx| {
9273                    state.replace_text_in_range(None, &ch.to_string(), window, cx);
9274                });
9275            });
9276        }
9277        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
9278
9279        // The repeated keystrokes form one typing gesture.
9280        cx.update(|window, cx| {
9281            input.update(cx, |state, cx| {
9282                assert_eq!(state.undo_manager.undo_count(), 1);
9283                state.undo(&Undo, window, cx);
9284            });
9285        });
9286        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9287
9288        cx.update(|window, cx| {
9289            input.update(cx, |state, cx| {
9290                state.redo(&Redo, window, cx);
9291            });
9292        });
9293        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
9294    }
9295
9296    #[gpui::test]
9297    fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
9298        let view = multi_line(cx);
9299        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9300        let input = view.input;
9301
9302        setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
9303        for _ in 0..3 {
9304            cx.update(|window, cx| {
9305                input.update(cx, |state, cx| {
9306                    state.backspace(&Backspace, window, cx);
9307                });
9308            });
9309        }
9310        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9311
9312        cx.update(|window, cx| {
9313            input.update(cx, |state, cx| {
9314                assert_eq!(state.undo_manager.undo_count(), 1);
9315                state.undo(&Undo, window, cx);
9316            });
9317        });
9318        assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
9319    }
9320
9321    #[gpui::test]
9322    fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
9323        let view = multi_line(cx);
9324        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9325        let input = view.input;
9326
9327        setup_cursors(&mut cx, &input, "|1\n2\n3");
9328        cx.update(|window, cx| {
9329            input.update(cx, |state, cx| {
9330                state.replace_text_in_range(None, "a", window, cx);
9331                state.add_cursor_below(&AddCursorBelow, window, cx);
9332                state.replace_text_in_range(None, "b", window, cx);
9333            });
9334        });
9335        assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
9336
9337        // The keystroke after the cursor was added is its own undo entry.
9338        cx.update(|window, cx| {
9339            input.update(cx, |state, cx| {
9340                state.undo(&Undo, window, cx);
9341            });
9342        });
9343        assert_cursors(&mut cx, &input, "a|1\n2|\n3");
9344    }
9345
9346    #[gpui::test]
9347    fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
9348        let view = multi_line(cx);
9349        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9350        let input = view.input;
9351
9352        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9353        cx.update(|window, cx| {
9354            input.update(cx, |state, cx| {
9355                state.indent_inline(&IndentInline, window, cx);
9356                assert_eq!(state.undo_manager.undo_count(), 1);
9357                state.undo(&Undo, window, cx);
9358            });
9359        });
9360        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9361    }
9362
9363    #[gpui::test]
9364    fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
9365        let view = multi_line(cx);
9366        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9367        let input = view.input;
9368
9369        // Cursors at line starts.
9370        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9371        cx.update(|window, cx| {
9372            input.update(cx, |state, cx| {
9373                state.indent(false, window, cx);
9374            });
9375        });
9376        assert_cursors(&mut cx, &input, "  |1\n  |2\n  |3");
9377
9378        cx.update(|window, cx| {
9379            input.update(cx, |state, cx| {
9380                state.outdent(false, window, cx);
9381            });
9382        });
9383        assert_cursors(&mut cx, &input, "|1\n|2\n|3");
9384    }
9385
9386    #[gpui::test]
9387    fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
9388        let view = multi_line(cx);
9389        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9390        let input = view.input;
9391
9392        // A mid-line indent lands at the cursor, and the outdent does not
9393        // take it back: it only ever removes leading line indentation.
9394        setup_cursors(&mut cx, &input, "1|2\n1|2");
9395        cx.update(|window, cx| {
9396            input.update(cx, |state, cx| {
9397                state.indent(false, window, cx);
9398            });
9399        });
9400        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
9401
9402        cx.update(|window, cx| {
9403            input.update(cx, |state, cx| {
9404                state.outdent(false, window, cx);
9405            });
9406        });
9407        assert_cursors(&mut cx, &input, "1  |2\n1  |2");
9408
9409        // A line with leading indentation loses that, wherever the cursor is.
9410        setup_cursors(&mut cx, &input, "  1|2\n  1|2");
9411        cx.update(|window, cx| {
9412            input.update(cx, |state, cx| {
9413                state.outdent(false, window, cx);
9414            });
9415        });
9416        assert_cursors(&mut cx, &input, "1|2\n1|2");
9417    }
9418
9419    #[gpui::test]
9420    fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
9421        let view = multi_line(cx);
9422        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9423        let input = view.input;
9424
9425        setup_cursors(&mut cx, &input, "a|b\nc|d");
9426        cx.update(|window, cx| {
9427            input.update(cx, |state, cx| {
9428                let before: Vec<_> = state.selections.iter().copied().collect();
9429                state.set_readonly(true, cx);
9430                state.backspace(&Backspace, window, cx);
9431                state.indent_inline(&IndentInline, window, cx);
9432
9433                assert_eq!(state.value(), "ab\ncd\n");
9434                assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
9435            });
9436        });
9437    }
9438
9439    #[gpui::test]
9440    fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
9441        let view = multi_line(cx);
9442        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9443        let input = view.input;
9444
9445        setup_cursors(&mut cx, &input, "x|\n|y");
9446        cx.update(|window, cx| {
9447            input.update(cx, |state, cx| {
9448                let mut selections: Vec<_> = state.selections.iter().copied().collect();
9449                selections.swap(0, 1);
9450                state.selections.replace_all(selections);
9451                let active_id = state.active_selection().id;
9452                state.replace_text_in_range(None, "!", window, cx);
9453                assert_eq!(state.active_selection().id, active_id);
9454            });
9455        });
9456    }
9457
9458    #[gpui::test]
9459    fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
9460        let view = multi_line(cx);
9461        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9462        let input = view.input;
9463
9464        cx.update(|window, cx| {
9465            input.update(cx, |state, cx| {
9466                state.set_value("line1\nline2\nline3", window, cx);
9467                let id = state.selections.generate_id();
9468                state
9469                    .selections
9470                    .replace_all(vec![CursorSelection::new(id, 0, 17)]);
9471                cx.notify();
9472            });
9473        });
9474
9475        cx.update(|window, cx| {
9476            input.update(cx, |state, cx| {
9477                state.indent(true, window, cx);
9478            });
9479        });
9480        input.read_with(&cx, |state, _| {
9481            assert_eq!(state.text.to_string(), "  line1\n  line2\n  line3");
9482        });
9483
9484        cx.update(|window, cx| {
9485            input.update(cx, |state, cx| {
9486                state.outdent(true, window, cx);
9487            });
9488        });
9489        input.read_with(&cx, |state, _| {
9490            assert_eq!(state.text.to_string(), "line1\nline2\nline3");
9491        });
9492    }
9493
9494    #[gpui::test]
9495    fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
9496        let view = multi_line(cx);
9497        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9498        let input = view.input;
9499
9500        setup_cursors(
9501            &mut cx,
9502            &input,
9503            "on|e two three\none t|wo three\non|e two three",
9504        );
9505
9506        cx.update(|window, cx| {
9507            input.update(cx, |state, cx| {
9508                state.move_to_next_word(&MoveToNextWord, window, cx);
9509            });
9510        });
9511        assert_cursors(
9512            &mut cx,
9513            &input,
9514            "one| two three\none two| three\none| two three",
9515        );
9516
9517        cx.update(|window, cx| {
9518            input.update(cx, |state, cx| {
9519                state.move_to_previous_word(&MoveToPreviousWord, window, cx);
9520            });
9521        });
9522        assert_cursors(
9523            &mut cx,
9524            &input,
9525            "|one two three\none |two three\n|one two three",
9526        );
9527
9528        // Move to end/start of document collapses to a single cursor.
9529        cx.update(|window, cx| {
9530            input.update(cx, |state, cx| {
9531                state.move_to_end(&MoveToEnd, window, cx);
9532            });
9533        });
9534        input.read_with(&cx, |state, _| {
9535            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
9536            assert_eq!(cursors, vec![state.text.len()]);
9537        });
9538
9539        cx.update(|window, cx| {
9540            input.update(cx, |state, cx| {
9541                state.move_to_start(&MoveToStart, window, cx);
9542            });
9543        });
9544        input.read_with(&cx, |state, _| {
9545            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
9546            assert_eq!(cursors, vec![0]);
9547        });
9548    }
9549
9550    #[gpui::test]
9551    fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
9552        let view = multi_line(cx);
9553        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9554        let input = view.input;
9555
9556        setup_cursors(
9557            &mut cx,
9558            &input,
9559            "on|e two three\none t|wo three\non|e two three",
9560        );
9561        cx.update(|window, cx| {
9562            input.update(cx, |state, cx| {
9563                state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
9564            });
9565        });
9566        assert_cursors(
9567            &mut cx,
9568            &input,
9569            "|one two three\n|one two three\n|one two three",
9570        );
9571
9572        // Select to document start collapses to the active cursor only.
9573        setup_cursors(
9574            &mut cx,
9575            &input,
9576            "on|e two three\none t|wo three\non|e two three",
9577        );
9578        cx.update(|window, cx| {
9579            input.update(cx, |state, cx| {
9580                state.select_to_start(&SelectToStart, window, cx);
9581            });
9582        });
9583        input.read_with(&cx, |state, _| {
9584            let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
9585            assert_eq!(cursors, vec![0]);
9586        });
9587    }
9588
9589    #[gpui::test]
9590    fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
9591        let view = multi_line(cx);
9592        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9593        let input = view.input;
9594
9595        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
9596        cx.update(|window, cx| {
9597            input.update(cx, |state, cx| {
9598                state.select_right(&SelectRight, window, cx);
9599            });
9600        });
9601        input.read_with(&cx, |state, _| {
9602            let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
9603            assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
9604        });
9605
9606        cx.update(|window, cx| {
9607            input.update(cx, |state, cx| {
9608                state.replace_text_in_range(None, "x", window, cx);
9609            });
9610        });
9611        assert_cursors(&mut cx, &input, "x|\nx|\nx|");
9612    }
9613
9614    #[gpui::test]
9615    fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
9616        let view = multi_line(cx);
9617        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9618        let input = view.input;
9619
9620        setup_cursors(&mut cx, &input, "|a\n|b\n|c");
9621        cx.update(|window, cx| {
9622            input.update(cx, |state, cx| {
9623                state.escape(&Escape, window, cx);
9624            });
9625        });
9626        input.read_with(&cx, |state, _| {
9627            assert_eq!(state.selections.len(), 1);
9628        });
9629    }
9630
9631    #[gpui::test]
9632    fn test_build_columnar_selection(cx: &mut TestAppContext) {
9633        let view = multi_line(cx);
9634        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9635        let input = view.input;
9636
9637        setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
9638        cx.update(|_, cx| {
9639            input.update(cx, |state, cx| {
9640                // From row 0 col 1 to row 2 col 3.
9641                state.build_columnar_selection(
9642                    ColumnarPoint::new(1, 0),
9643                    ColumnarPoint::new(13, 0),
9644                    cx,
9645                );
9646                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
9647                assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
9648            });
9649        });
9650    }
9651
9652    #[gpui::test]
9653    fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
9654        let view = multi_line(cx);
9655        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9656        let input = view.input;
9657
9658        setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
9659        cx.update(|_, cx| {
9660            input.update(cx, |state, cx| {
9661                // Ends on the short row, 3 columns past its end: the block still spans
9662                // columns 1..5, and only that row is clipped to what it has.
9663                state.build_columnar_selection(
9664                    ColumnarPoint::new(1, 0),
9665                    ColumnarPoint::new(9, 3),
9666                    cx,
9667                );
9668                let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
9669                assert_eq!(ranges, vec![(1, 5), (8, 9)]);
9670            });
9671        });
9672    }
9673
9674    #[gpui::test]
9675    fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
9676        let view = multi_line(cx);
9677        let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
9678        let input = view.input;
9679
9680        setup_cursors(&mut cx, &input, "|1\n|2\n|3");
9681        cx.update(|_, cx| {
9682            cx.write_to_clipboard(ClipboardItem::new_string("x\ny\nz".to_string()));
9683        });
9684        cx.update(|window, cx| {
9685            input.update(cx, |state, cx| {
9686                state.paste(&Paste, window, cx);
9687            });
9688        });
9689        // One clipboard line per cursor.
9690        assert_cursors(&mut cx, &input, "x|1\ny|2\nz|3");
9691    }
9692
9693    #[gpui::test]
9694    fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
9695        use gpui::{ClipboardEntry, Image, ImageFormat};
9696
9697        let input_view = InputView::build(cx, |state| state);
9698        let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9699        let input = input_view.input;
9700
9701        cx.update(|window, cx| {
9702            input.update(cx, |state, cx| {
9703                state.set_value("hello world", window, cx);
9704                state.select_all(window, cx);
9705                cx.write_to_clipboard(ClipboardItem {
9706                    entries: vec![ClipboardEntry::Image(Image::from_bytes(
9707                        ImageFormat::Png,
9708                        vec![0x89, b'P', b'N', b'G'],
9709                    ))],
9710                });
9711
9712                // An image-only clipboard must not replace the selection
9713                // with nothing.
9714                state.paste(&Paste, window, cx);
9715                assert_eq!(state.value(), "hello world");
9716                assert_eq!(state.selected_range(), 0..11);
9717            });
9718        });
9719    }
9720}
9721
9722/// Methods that only a single-line input offers.
9723impl InputBaseState<crate::input::InputMode> {
9724    /// Create a single-line text input state.
9725    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
9726        Self::new_in_mode(window, cx)
9727    }
9728
9729    /// Set a custom step function of the [`super::NumberInput`].
9730    ///
9731    /// The `f` receives the current value and the [`StepAction`], and returns
9732    /// the step to apply, so the step can vary with the value.
9733    ///
9734    /// # Example
9735    ///
9736    /// ```ignore
9737    /// // At the boundary 1.0 the step is 0.1 going down and 0.5 going up.
9738    /// InputState::new(window, cx).step_by(|value, action, _cx| match action {
9739    ///     StepAction::Increment => if value < 1.0 { 0.1 } else { 0.5 },
9740    ///     StepAction::Decrement => if value <= 1.0 { 0.1 } else { 0.5 },
9741    /// })
9742    /// ```
9743    pub fn step_by(mut self, f: impl Fn(f64, StepAction, &mut App) -> f64 + 'static) -> Self {
9744        self.number_step = Some(NumberStep::by_value(f));
9745        self
9746    }
9747
9748    /// Set with password masked state.
9749    pub fn masked(mut self, masked: bool) -> Self {
9750        self.masked = masked;
9751        self
9752    }
9753
9754    /// Set the password masked state of the input field.
9755    pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
9756        self.masked = masked;
9757        cx.notify();
9758    }
9759
9760    /// Set the regular expression pattern of the input field.
9761    pub fn pattern(mut self, pattern: regex::Regex) -> Self {
9762        self.pattern = Some(pattern);
9763        self
9764    }
9765
9766    /// Set the regular expression pattern of the input field with reference.
9767    pub fn set_pattern(
9768        &mut self,
9769        pattern: regex::Regex,
9770        _window: &mut Window,
9771        _cx: &mut Context<Self>,
9772    ) {
9773        self.pattern = Some(pattern);
9774    }
9775
9776    /// Set the validation function of the input field.
9777    pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
9778        self.validate = Some(Box::new(f));
9779        self
9780    }
9781
9782    pub fn set_validator(
9783        &mut self,
9784        validate: impl Fn(&str, &mut App) -> bool + 'static,
9785        _cx: &mut Context<Self>,
9786    ) {
9787        self.validate = Some(Box::new(validate));
9788    }
9789
9790    /// Set the step value of the [`super::NumberInput`] for increment/decrement.
9791    ///
9792    /// If any of `step`, `min`, `max` is set, the [`super::NumberInput`] will
9793    /// update the value internally (step by `step`, default 1, clamp to the
9794    /// `min`/`max` range and emit [`InputEvent::Change`]) instead of emitting
9795    /// [`super::NumberInputEvent::Step`].
9796    ///
9797    /// See also [`Self::step_by`] to calculate the step value
9798    /// based on the current value.
9799    pub fn step(mut self, step: impl Into<NumberStep>) -> Self {
9800        self.number_step = Some(step.into());
9801        self
9802    }
9803
9804    /// Set the minimum value of the [`super::NumberInput`].
9805    ///
9806    /// The value will be clamped to the minimum value on stepping and on
9807    /// blur (only if the clamped value passes the `pattern`/`validate` check).
9808    /// See also [`Self::step`].
9809    pub fn min(mut self, min: f64) -> Self {
9810        self.number_min = Some(min);
9811        self
9812    }
9813
9814    /// Set the maximum value of the [`super::NumberInput`].
9815    ///
9816    /// The value will be clamped to the maximum value on stepping and on
9817    /// blur (only if the clamped value passes the `pattern`/`validate` check).
9818    /// See also [`Self::step`].
9819    pub fn max(mut self, max: f64) -> Self {
9820        self.number_max = Some(max);
9821        self
9822    }
9823
9824    /// Update the step value after construction, `None` to fall back to
9825    /// emitting [`super::NumberInputEvent::Step`] (if `min`, `max` are unset).
9826    ///
9827    /// See [`Self::step`] and [`Self::step_by`].
9828    pub fn set_step(
9829        &mut self,
9830        step: impl Into<Option<NumberStep>>,
9831        _: &mut Window,
9832        _: &mut Context<Self>,
9833    ) {
9834        self.number_step = step.into();
9835    }
9836
9837    /// Update the minimum value after construction. See [`Self::min`].
9838    pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
9839        self.number_min = min;
9840    }
9841
9842    /// Update the maximum value after construction. See [`Self::max`].
9843    pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
9844        self.number_max = max;
9845    }
9846
9847    /// Set true to show spinner at the input right.
9848    pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
9849        self.loading = loading;
9850        cx.notify();
9851    }
9852}
9853
9854/// Methods shared by the two multi-line modes, and reachable on neither a
9855/// single-line input nor anything else.
9856impl<M: crate::input::MultiLineMode> InputBaseState<M> {
9857    /// Whether the built-in search panel and its shortcut are enabled. Off by
9858    /// default, on for the code editor.
9859    ///
9860    /// This only concerns the panel. An input that is not searchable still
9861    /// answers [`InputBaseState::set_search_query`] and the other search
9862    /// methods, and lets `Ctrl-F` / `Cmd-F` bubble up to its ancestors, so an
9863    /// application can put its own search UI on top of the same engine.
9864    pub fn searchable(mut self, searchable: bool) -> Self {
9865        self.searchable = searchable;
9866        self
9867    }
9868
9869    /// See [`InputBaseState::searchable`].
9870    pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
9871        self.searchable = searchable;
9872        cx.notify();
9873    }
9874
9875    /// Set the soft wrap mode, default is true.
9876    #[doc(hidden)]
9877    pub fn soft_wrap(mut self, wrap: bool) -> Self {
9878        self.soft_wrap = wrap;
9879        self
9880    }
9881
9882    /// Update the soft wrap mode, default is true.
9883    pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
9884        self.soft_wrap = wrap;
9885        if wrap {
9886            let wrap_width = self
9887                .last_layout
9888                .as_ref()
9889                .and_then(|b| b.wrap_width)
9890                .unwrap_or(self.input_bounds.size.width);
9891
9892            self.display_map.on_layout_changed(Some(wrap_width), cx);
9893
9894            // Reset scroll to left 0
9895            let mut offset = self.scroll_handle.offset();
9896            offset.x = px(0.);
9897            self.scroll_handle.set_offset(offset);
9898        } else {
9899            self.display_map.on_layout_changed(None, cx);
9900        }
9901        cx.notify();
9902    }
9903
9904    /// Set how soft-wrapped continuation lines are indented, default is [`WrappingIndent::Same`]
9905    #[doc(hidden)]
9906    pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
9907        self.wrapping_indent = wrapping_indent;
9908        self
9909    }
9910
9911    /// Update how soft-wrapped continuation lines are indented.
9912    pub fn set_wrapping_indent(
9913        &mut self,
9914        wrapping_indent: WrappingIndent,
9915        _: &mut Window,
9916        cx: &mut Context<Self>,
9917    ) {
9918        self.wrapping_indent = wrapping_indent;
9919        self.display_map.set_wrapping_indent(wrapping_indent, cx);
9920        cx.notify();
9921    }
9922}
9923
9924/// Methods that only ordinary multi-line text offers.
9925impl InputBaseState<crate::input::TextareaMode> {
9926    /// Create a multi-line text state.
9927    ///
9928    /// Being multi-line is carried by the mode, not by the layout, so the
9929    /// default plain-text layout needs no adjustment here.
9930    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
9931        Self::new_in_mode(window, cx)
9932    }
9933
9934    pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
9935        self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
9936        cx.notify();
9937    }
9938
9939    /// Set the number of rows for the multi-line Textarea.
9940    ///
9941    /// This is only used when `multi_line` is set to true.
9942    ///
9943    /// default: 2
9944    #[doc(hidden)]
9945    pub fn rows(mut self, rows: usize) -> Self {
9946        match &mut self.mode {
9947            LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
9948                *r = rows
9949            }
9950            LayoutMode::AutoGrow {
9951                max_rows: max_r,
9952                rows: r,
9953                ..
9954            } => {
9955                *r = rows;
9956                *max_r = rows;
9957            }
9958        }
9959        self
9960    }
9961
9962    pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
9963        match &mut self.mode {
9964            LayoutMode::PlainText { rows: value, .. }
9965            | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
9966            LayoutMode::AutoGrow {
9967                rows: value,
9968                max_rows,
9969                ..
9970            } => {
9971                *value = rows;
9972                *max_rows = rows;
9973            }
9974        }
9975        cx.notify();
9976    }
9977
9978    /// Grow with the content from `min_rows` through `max_rows`.
9979    pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
9980        self.mode = LayoutMode::auto_grow(min_rows, max_rows);
9981        self
9982    }
9983}
9984
9985/// Methods that only a source-code editor offers.
9986impl InputBaseState<crate::input::EditorMode> {
9987    /// Create a source-code editor state.
9988    ///
9989    /// Default options: line numbers on, tab size 2 with soft tabs, indent
9990    /// guides on, multi-line, and search enabled. Set the language for syntax
9991    /// highlighting with [`Self::language`]; without one the text is shown
9992    /// unhighlighted.
9993    ///
9994    /// The editor aims at simple code editing or display, not at being a
9995    /// full-featured code editor. It offers syntax highlighting, auto indent,
9996    /// line numbers, and handles large text up to about 50K lines.
9997    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
9998        let mut state = Self::new_in_mode(window, cx);
9999        state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
10000        state.searchable = true;
10001        state
10002    }
10003
10004    /// Set the language to highlight, e.g. `"rust"`.
10005    ///
10006    /// See [`Self::set_highlighter`] to change it after construction.
10007    pub fn language(mut self, language: impl Into<SharedString>) -> Self {
10008        if let LayoutMode::CodeEditor {
10009            language: l,
10010            highlighter,
10011            ..
10012        } = &mut self.mode
10013        {
10014            l.set_name(language.into());
10015            *highlighter.borrow_mut() = None;
10016        }
10017        self
10018    }
10019
10020    /// The current language name, e.g. `"rust"`.
10021    pub fn language_name(&self) -> SharedString {
10022        match &self.mode {
10023            LayoutMode::CodeEditor { language, .. } => language.name(),
10024            _ => SharedString::default(),
10025        }
10026    }
10027
10028    /// Set enable/disable code folding.
10029    ///
10030    /// Default: true
10031    #[doc(hidden)]
10032    pub fn folding(mut self, folding: bool) -> Self {
10033        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
10034            *f = folding;
10035        }
10036        self
10037    }
10038
10039    /// Set code folding at runtime.
10040    ///
10041    /// When disabling, all existing folds are cleared.
10042    pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
10043        if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
10044            *f = folding;
10045        }
10046        if !folding {
10047            self.display_map.clear_folds();
10048        }
10049        cx.notify();
10050    }
10051
10052    /// Unfold any folded ranges that hide the given position.
10053    ///
10054    /// Use this to reveal a position before acting on it (e.g. before
10055    /// [`Self::set_cursor_position`], which stops at a fold boundary),
10056    /// without touching folds elsewhere in the buffer. Fold candidates are
10057    /// kept, so the opened ranges can be folded again from the gutter.
10058    ///
10059    /// A fold keeps its own first and last line visible, so a position on
10060    /// either of them opens nothing. Nested folds all open, since opening
10061    /// only the outermost would leave the position hidden.
10062    ///
10063    /// Returns whether any fold was opened.
10064    pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
10065        let offset = self.text.position_to_offset(&position.into());
10066        let line = self.text.offset_to_point(offset).row;
10067        // A fold hides start_line + 1 ..= end_line - 1, so a line is hidden
10068        // exactly when some folded range strictly contains it.
10069        let covering: Vec<usize> = self
10070            .display_map
10071            .folded_ranges()
10072            .iter()
10073            .filter(|fold| line > fold.start_line && line < fold.end_line)
10074            .map(|fold| fold.start_line)
10075            .collect();
10076        if covering.is_empty() {
10077            return false;
10078        }
10079
10080        for start_line in covering {
10081            self.display_map.set_folded(start_line, false);
10082        }
10083        cx.notify();
10084        true
10085    }
10086
10087    /// Set enable/disable line number.
10088    #[doc(hidden)]
10089    pub fn line_number(mut self, line_number: bool) -> Self {
10090        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
10091            *l = line_number;
10092        }
10093        self
10094    }
10095
10096    /// Set line number.
10097    pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
10098        if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
10099            *l = line_number;
10100        }
10101        cx.notify();
10102    }
10103
10104    /// Set enable/disable automatic closing brackets and quotes.
10105    ///
10106    /// When enabled, typing an opener from [`LanguageConfig::auto_closing_pairs`](crate::input::language_config::LanguageConfig::auto_closing_pairs) inserts the
10107    /// matching closer and places the cursor inside. Typing a closer that is
10108    /// already present just moves past it. Default: true
10109    #[doc(hidden)]
10110    pub fn auto_close(mut self, auto_close: bool) -> Self {
10111        self.mode.set_auto_close(auto_close);
10112        self
10113    }
10114
10115    /// Set automatic closing brackets and quotes at runtime.
10116    pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
10117        self.mode.set_auto_close(auto_close);
10118        cx.notify();
10119    }
10120
10121    /// Set enable/disable smart indent on Enter.
10122    ///
10123    /// When enabled, Enter uses structural brackets and
10124    /// [`LanguageConfig::indentation_rules`](crate::input::language_config::LanguageConfig::indentation_rules) to choose indentation.
10125    /// Default: true
10126    #[doc(hidden)]
10127    pub fn smart_indent(mut self, smart_indent: bool) -> Self {
10128        self.mode.set_smart_indent(smart_indent);
10129        self
10130    }
10131
10132    /// Set smart indent on Enter at runtime.
10133    pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
10134        self.mode.set_smart_indent(smart_indent);
10135        cx.notify();
10136    }
10137}