BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / state.rs

state.rs

state.rs 446.6 KiB Download Raw
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::{
29 EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, TextElement,
30 clamp_horizontal_scroll_offset,
31 },
32 kind::InputModeKind,
33 mask_pattern::normalize_number_input,
34 mode::LayoutMode,
35 undo_manager::{EditIntent, UndoManager},
36};
37use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
38use crate::input::blink_cursor::CURSOR_WIDTH;
39use crate::input::movement::MoveDirection;
40use crate::input::{
41 InputExtras as _, Position, RopeExt as _, element::RIGHT_MARGIN, layout::LastLayout,
42};
43use crate::{AutoScroll, StepAction};
44
45/// Vertical clearance to retain when revealing a text position.
46pub(crate) enum ScrollPadding {
47 Minimal,
48 SurroundingLines,
49}
50
51#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
52#[action(namespace = input, no_json)]
53pub struct Enter {
54 /// Is confirm with secondary.
55 pub secondary: bool,
56 /// Whether the Shift modifier was held when Enter was pressed.
57 pub shift: bool,
58}
59
60impl Enter {
61 /// Returns true if `action` is a primary `Enter` action (`secondary: false`),
62 /// regardless of whether Shift was held.
63 pub fn is_primary(action: &dyn Action) -> bool {
64 action.partial_eq(&Enter {
65 secondary: false,
66 shift: false,
67 }) || action.partial_eq(&Enter {
68 secondary: false,
69 shift: true,
70 })
71 }
72}
73
74actions!(
75 input,
76 [
77 ActivateToken,
78 Backspace,
79 Delete,
80 DeleteToBeginningOfLine,
81 DeleteToEndOfLine,
82 DeleteToPreviousWordStart,
83 DeleteToNextWordEnd,
84 Indent,
85 Outdent,
86 IndentInline,
87 OutdentInline,
88 MoveUp,
89 MoveDown,
90 MoveLeft,
91 MoveRight,
92 MoveHome,
93 MoveEnd,
94 MovePageUp,
95 MovePageDown,
96 AddCursorAbove,
97 AddCursorBelow,
98 SelectAll,
99 SelectToStartOfLine,
100 SelectToEndOfLine,
101 SelectToStart,
102 SelectToEnd,
103 SelectToPreviousWordStart,
104 SelectToNextWordEnd,
105 ShowCharacterPalette,
106 Copy,
107 Cut,
108 Paste,
109 Undo,
110 Redo,
111 MoveToStartOfLine,
112 MoveToEndOfLine,
113 MoveToStart,
114 MoveToEnd,
115 MoveToPreviousWord,
116 MoveToNextWord,
117 Escape,
118 ToggleCodeActions,
119 Search,
120 Replace,
121 GoToDefinition,
122 ]
123);
124
125#[derive(Clone)]
126pub enum InputEvent {
127 Change,
128 PressEnter { secondary: bool, shift: bool },
129 Focus,
130 Blur,
131}
132
133pub(super) const CONTEXT: &str = "Input";
134
135pub(crate) fn init(cx: &mut App) {
136 cx.bind_keys([
137 KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
138 KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
139 #[cfg(target_os = "macos")]
140 KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
141 KeyBinding::new("delete", Delete, Some(CONTEXT)),
142 KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
143 #[cfg(target_os = "macos")]
144 KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
145 #[cfg(target_os = "macos")]
146 KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
147 #[cfg(target_os = "macos")]
148 KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
149 #[cfg(not(target_os = "macos"))]
150 KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
151 #[cfg(target_os = "macos")]
152 KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
153 #[cfg(not(target_os = "macos"))]
154 KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
155 KeyBinding::new(
156 "enter",
157 Enter {
158 secondary: false,
159 shift: false,
160 },
161 Some(CONTEXT),
162 ),
163 KeyBinding::new(
164 "shift-enter",
165 Enter {
166 secondary: false,
167 shift: true,
168 },
169 Some(CONTEXT),
170 ),
171 KeyBinding::new(
172 "secondary-enter",
173 Enter {
174 secondary: true,
175 shift: false,
176 },
177 Some(CONTEXT),
178 ),
179 KeyBinding::new("escape", Escape, Some(CONTEXT)),
180 KeyBinding::new("up", MoveUp, Some(CONTEXT)),
181 KeyBinding::new("down", MoveDown, Some(CONTEXT)),
182 KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
183 KeyBinding::new("right", MoveRight, Some(CONTEXT)),
184 KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
185 KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
186 KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
187 KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
188 #[cfg(target_os = "macos")]
189 KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
190 #[cfg(not(target_os = "macos"))]
191 KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
192 #[cfg(target_os = "macos")]
193 KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
194 #[cfg(not(target_os = "macos"))]
195 KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
196 KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
197 KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
198 KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
199 KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
200 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
201 KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
202 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
203 KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
204 // Avoid Ctrl+Alt+arrows on Linux, where desktops may reserve them.
205 #[cfg(target_os = "macos")]
206 KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
207 #[cfg(target_os = "macos")]
208 KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
209 #[cfg(target_os = "windows")]
210 KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
211 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
212 KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
213 #[cfg(target_os = "windows")]
214 KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
215 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
216 KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
217 KeyBinding::new("home", MoveHome, Some(CONTEXT)),
218 KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
219 #[cfg(not(target_os = "macos"))]
220 KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
221 #[cfg(not(target_os = "macos"))]
222 KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
223 #[cfg(not(target_os = "macos"))]
224 KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
225 #[cfg(not(target_os = "macos"))]
226 KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
227 KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
228 KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
229 #[cfg(target_os = "macos")]
230 KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
231 #[cfg(target_os = "macos")]
232 KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
233 #[cfg(target_os = "macos")]
234 KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
235 #[cfg(target_os = "macos")]
236 KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
237 #[cfg(any(target_os = "macos", target_os = "linux"))]
238 KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
239 #[cfg(not(target_os = "macos"))]
240 KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
241 #[cfg(any(target_os = "macos", target_os = "linux"))]
242 KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
243 #[cfg(not(target_os = "macos"))]
244 KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
245 #[cfg(target_os = "macos")]
246 KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
247 #[cfg(target_os = "macos")]
248 KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
249 #[cfg(not(target_os = "macos"))]
250 KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
251 #[cfg(target_os = "macos")]
252 KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
253 #[cfg(not(target_os = "macos"))]
254 KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
255 #[cfg(target_os = "macos")]
256 KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
257 #[cfg(not(target_os = "macos"))]
258 KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
259 #[cfg(target_os = "macos")]
260 KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
261 #[cfg(not(target_os = "macos"))]
262 KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
263 #[cfg(target_os = "macos")]
264 KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
265 #[cfg(target_os = "macos")]
266 KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
267 #[cfg(target_os = "macos")]
268 KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
269 #[cfg(target_os = "macos")]
270 KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
271 #[cfg(target_os = "macos")]
272 KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
273 #[cfg(target_os = "macos")]
274 KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
275 #[cfg(target_os = "macos")]
276 KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
277 #[cfg(target_os = "macos")]
278 KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
279 #[cfg(target_os = "macos")]
280 KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
281 #[cfg(target_os = "macos")]
282 KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
283 #[cfg(not(target_os = "macos"))]
284 KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
285 #[cfg(not(target_os = "macos"))]
286 KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
287 #[cfg(target_os = "macos")]
288 KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
289 #[cfg(target_os = "macos")]
290 KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
291 #[cfg(not(target_os = "macos"))]
292 KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
293 #[cfg(not(target_os = "macos"))]
294 KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
295 #[cfg(target_os = "macos")]
296 KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
297 #[cfg(not(target_os = "macos"))]
298 KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
299 #[cfg(target_os = "macos")]
300 KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
301 #[cfg(not(target_os = "macos"))]
302 KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
303 #[cfg(target_os = "macos")]
304 KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
305 #[cfg(not(target_os = "macos"))]
306 KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
307 ]);
308}
309
310/// A mouse position resolved for a columnar (block) selection.
311///
312/// A position past the end of a short row has no glyph to land on, so `offset` clips to
313/// that row's end and `columns_past_line_end` keeps what the clip dropped. Together they
314/// say which column the pointer really reached, which is what a block spanning rows of
315/// different lengths has to be measured in.
316#[derive(Debug, Clone, Copy, PartialEq, Eq)]
317pub(super) struct ColumnarPoint {
318 offset: usize,
319 columns_past_line_end: usize,
320}
321
322impl ColumnarPoint {
323 pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
324 Self {
325 offset,
326 columns_past_line_end,
327 }
328 }
329}
330
331/// The document and selections a paste was asked to replace, taken when the
332/// `Paste` action ran so a clipboard read that resolves later can tell
333/// whether it still applies. See [`InputBaseState::paste_target`].
334#[derive(Debug, PartialEq)]
335struct PasteTarget {
336 document_revision: u64,
337 selections: Vec<CursorSelection>,
338}
339
340/// The shared text-editing engine behind [`crate::input::InputState`],
341/// [`crate::input::TextareaState`] and [`crate::input::EditorState`].
342///
343/// `M` is the mode marker: it carries no data and only decides which methods
344/// exist, so an ordinary input cannot reach the editor's language features.
345///
346/// The three states are type aliases of this one, which is why this name is
347/// public: an alias is only as usable as the type behind it, so hiding this
348/// would leave `InputState` unable to do anything. Prefer naming the aliases
349/// — write `InputState`, not `InputBaseState<InputMode>`.
350pub struct InputBaseState<M: InputModeKind> {
351 /// State only this mode needs. See [`InputModeKind::Extras`].
352 pub(crate) extras: M::Extras,
353 pub(super) focus_handle: FocusHandle,
354 pub(super) mode: LayoutMode,
355 pub(super) text: Rope,
356 pub(super) display_map: DisplayMap,
357 pub(super) undo_manager: UndoManager,
358 pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
359 pub(super) pending_token: Option<super::InlineToken>,
360 pub(super) replaying_history: bool,
361 pub(super) validated_token_edit: bool,
362 pub(super) document_revision: u64,
363 pub(super) token_presentation: super::InlineTokenPresentation,
364 pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
365 /// Real per-frame bounds of the placed token elements, keyed by token
366 /// start offset; used for hover payloads and stale-hover reconciliation.
367 pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
368 /// Text painted right-aligned in the indent before a byte offset, e.g. line numbers.
369 pub(super) line_labels: Vec<(usize, SharedString)>,
370 pub(super) line_label_color: gpui::Hsla,
371 /// The currently hovered token: its entered span, last measured bounds,
372 /// and UTF-16 range as of entry. Retained so hover exit can still be
373 /// delivered when the token is removed, replaced, scrolled out, or
374 /// disabled.
375 pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
376 pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
377 /// The start offset of a pressed token, with the document revision and
378 /// pointer position at the press.
379 pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
380 pub(super) search_session: super::SearchSession,
381 /// Advances every time search is explicitly invoked. See
382 /// [`InputBaseState::search_activation_revision`].
383 pub(super) search_activation_revision: u64,
384 pub(super) searchable: bool,
385 pub(super) replaceable: bool,
386 pub(super) soft_wrap: bool,
387 pub(super) wrapping_indent: WrappingIndent,
388 pub(super) scroll_beyond_last_line: Option<usize>,
389 pub(super) cursor_surrounding_lines: Option<usize>,
390 pub(super) blink_cursor: Entity<BlinkCursor>,
391 pub(super) loading: bool,
392 /// The cursors and selections.
393 ///
394 /// Always contains at least one selection where index 0 is the active cursor.
395 pub(super) selections: Selections,
396 /// Range for save the selected word, use to keep word range when drag move.
397 pub(super) selected_word_range: Option<CursorSelection>,
398 /// The marked range is the temporary insert text on IME typing.
399 pub(super) ime_marked_range: Option<CursorSelection>,
400 pub(super) last_layout: Option<LastLayout>,
401 pub(super) last_cursor: Option<usize>,
402 /// The input container bounds
403 pub(super) input_bounds: Bounds<Pixels>,
404 /// The text bounds
405 pub(super) last_bounds: Option<Bounds<Pixels>>,
406 pub(super) last_selected_range: Option<CursorSelection>,
407 pub(super) selecting: bool,
408 /// Anchor point of an in-progress columnar (block) selection.
409 pub(super) column_select_start: Option<ColumnarPoint>,
410 /// The selection a long press made, with its handles and edit menu.
411 pub(super) touch_selection: super::touch::TouchSelection,
412 pub(crate) disabled: bool,
413 pub(crate) readonly: bool,
414 pub(crate) text_align: TextAlign,
415 pub(super) masked: bool,
416 pub(super) clean_on_escape: bool,
417 pub(super) submit_on_enter: bool,
418 pub(super) show_whitespaces: bool,
419 /// This flag tells the renderer to prefer the end of the current visual line.
420 pub(crate) cursor_line_end_affinity: bool,
421 pub(super) pattern: Option<regex::Regex>,
422 pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
423 /// The step strategy for [`super::NumberInput`] to increment/decrement.
424 /// See [`Self::step`] and [`Self::step_by`].
425 pub(crate) number_step: Option<NumberStep>,
426 /// The minimum value for [`super::NumberInput`]. See [`Self::min`].
427 pub(crate) number_min: Option<f64>,
428 /// The maximum value for [`super::NumberInput`]. See [`Self::max`].
429 pub(crate) number_max: Option<f64>,
430 pub(crate) scroll_handle: ScrollHandle,
431 /// The deferred scroll offset to apply on next layout.
432 pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
433 /// The size of the scrollable content.
434 pub(crate) scroll_size: gpui::Size<Pixels>,
435 pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
436 /// The unwrapped width of the longest line and what it was measured for.
437 pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
438 pub(super) editor_paddings: Edges<Pixels>,
439 /// The style this state paints with: what was projected onto it, with
440 /// every colour left unset resolved from the palette that is current. It
441 /// is rebuilt at the top of every render, which is what keeps it current
442 /// when the palette changes after the state was built.
443 pub(super) editor_style: InputEditorStyle,
444 /// What a consumer projected, kept verbatim so that resolution never
445 /// consumes its own output: resolving in place would fill the unset
446 /// colours once and then never see them as unset again, which is the same
447 /// freeze in a different place.
448 projected_editor_style: InputEditorStyle,
449
450 /// The mask pattern for formatting the input text
451 pub(crate) mask_pattern: MaskPattern,
452 /// Whether the `mask_pattern` was explicitly set (via [`Self::mask_pattern`]
453 /// or [`Self::set_mask_pattern`]), to let [`super::NumberInput`] only apply
454 /// its default mask when the user has not made an explicit choice.
455 pub(super) mask_pattern_set: bool,
456 pub(super) placeholder: SharedString,
457
458 /// Diagnostic currently requested by pointer hover; applications render it.
459 pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
460
461 context_menu_handler: Option<
462 Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
463 >,
464 pending_context_menu: Option<(Point<Pixels>, usize)>,
465
466 /// Whether the context menu that shows on right-click is enabled.
467 ///
468 pub(super) enable_context_menu: bool,
469
470 /// A flag to indicate if we are currently inserting a completion item.
471 pub(super) completion_inserting: bool,
472 pub(super) overlay_action_handler: Option<
473 Rc<
474 dyn Fn(
475 super::InputOverlayKind,
476 Box<dyn Action>,
477 &mut Window,
478 &mut Context<InputBaseState<M>>,
479 ) -> bool,
480 >,
481 >,
482
483 /// A flag to indicate if we have a pending update to the text.
484 ///
485 /// If true, will call some update (for example LSP, Syntax Highlight) before render.
486 _pending_update: bool,
487 /// A flag to indicate if we should ignore the next completion event.
488 pub(super) silent_replace_text: bool,
489 /// A flag to indicate if we should emit InputEvents.
490 pub(super) emit_events: bool,
491
492 _subscriptions: Vec<Subscription>,
493
494 pub(super) auto_scroll: AutoScroll,
495}
496
497/// Read-only styling data exposed to presentation facades.
498///
499/// The fields are private and read through the methods below, so that a new
500/// one can be added without breaking the facades.
501#[derive(Clone)]
502pub struct InputPresentation {
503 focus_handle: FocusHandle,
504 disabled: bool,
505 readonly: bool,
506 loading: bool,
507 masked: bool,
508 multi_line: bool,
509 code_editor: bool,
510 text_align: TextAlign,
511 placeholder: SharedString,
512 mask_placeholder: Option<String>,
513}
514
515impl InputPresentation {
516 pub fn focus_handle(&self) -> &FocusHandle {
517 &self.focus_handle
518 }
519
520 pub fn is_disabled(&self) -> bool {
521 self.disabled
522 }
523
524 pub fn is_readonly(&self) -> bool {
525 self.readonly
526 }
527
528 /// Returns true if the user is allowed to change the text.
529 ///
530 /// See also: [`InputBaseState::is_editable`].
531 pub fn is_editable(&self) -> bool {
532 !self.disabled && !self.readonly
533 }
534
535 pub fn is_loading(&self) -> bool {
536 self.loading
537 }
538
539 pub fn is_masked(&self) -> bool {
540 self.masked
541 }
542
543 pub fn is_multi_line(&self) -> bool {
544 self.multi_line
545 }
546
547 pub fn is_code_editor(&self) -> bool {
548 self.code_editor
549 }
550
551 pub fn text_align(&self) -> TextAlign {
552 self.text_align
553 }
554
555 pub fn placeholder(&self) -> &SharedString {
556 &self.placeholder
557 }
558
559 /// The placeholder derived from the mask pattern, e.g.: `(___) ___-____`.
560 pub fn mask_placeholder(&self) -> Option<&str> {
561 self.mask_placeholder.as_deref()
562 }
563}
564
565impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
566
567impl<M: InputModeKind> InputBaseState<M> {
568 #[doc(hidden)]
569 pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
570 let layout = self.last_layout.as_ref()?;
571 Some((layout.cursor_bounds?, layout.line_height))
572 }
573
574 pub fn input_bounds(&self) -> Bounds<Pixels> {
575 self.input_bounds
576 }
577
578 pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
579 self.last_bounds
580 }
581
582 pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
583 self.diagnostic_popover.clone()
584 }
585
586 pub fn presentation(&self) -> InputPresentation {
587 InputPresentation {
588 focus_handle: self.focus_handle.clone(),
589 disabled: self.disabled,
590 readonly: self.readonly,
591 loading: self.loading,
592 masked: self.masked,
593 multi_line: self.is_multi_line(),
594 code_editor: self.is_code_editor(),
595 text_align: self.text_align,
596 placeholder: self.placeholder.clone(),
597 mask_placeholder: self.mask_pattern.placeholder(),
598 }
599 }
600
601 /// Whether this input spans more than one line.
602 ///
603 /// Answered by the mode marker, which is fixed when the state is built.
604 /// [`LayoutMode`] holds the row counts and growth policy, not the kind.
605 #[inline]
606 /// Whether this input paints scrollbars.
607 ///
608 /// Only a multi-line input can scroll: a single-line input keeps its
609 /// caret in view by moving its own offset, and never has a viewport a
610 /// user could drag. Adding the editor scrollbar to every input put a
611 /// thumb inside every text field, which is a control the field does not
612 /// have.
613 pub(crate) fn shows_scrollbar(&self) -> bool {
614 self.is_multi_line()
615 }
616
617 pub fn is_multi_line(&self) -> bool {
618 M::MULTI_LINE
619 }
620
621 /// Whether this input is a single-line text field. See [`Self::is_multi_line`].
622 #[inline]
623 pub fn is_single_line(&self) -> bool {
624 !M::MULTI_LINE
625 }
626
627 /// Whether this input is a source-code editor.
628 #[inline]
629 pub fn is_code_editor(&self) -> bool {
630 M::CODE_EDITOR
631 }
632
633 /// Whether the user is allowed to copy the selection out.
634 ///
635 /// A masked input keeps its value out of the clipboard.
636 pub fn is_copyable(&self) -> bool {
637 self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
638 }
639
640 pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
641 let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
642 InputContextMenuCapabilities::new()
643 .disabled(self.disabled)
644 .readonly(self.readonly)
645 .code_editor(self.is_code_editor())
646 .selection(!self.active_selection().is_empty())
647 .masked(self.masked)
648 .go_to_definition(go_to_definition)
649 .code_actions(code_actions)
650 }
651
652 pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
653 if !self.is_single_line() || self.text_align == text_align {
654 return;
655 }
656
657 self.text_align = text_align;
658 cx.notify();
659 }
660
661 /// Flip the password mask.
662 ///
663 /// Setting the mask is a single-line method, but flipping it stays here:
664 /// the reveal button is rendered from the generic path, and it can only be
665 /// switched on through [`crate::input::InputState`] anyway.
666 pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
667 self.masked = !self.masked;
668 cx.notify();
669 }
670
671 pub fn on_context_menu(
672 &mut self,
673 handler: Rc<
674 dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
675 >,
676 ) {
677 self.context_menu_handler = Some(handler);
678 }
679
680 /// Build the engine. Each mode's own `new` sets its layout on top of this.
681 fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
682 let focus_handle = cx.focus_handle().tab_stop(true);
683 let blink_cursor = cx.new(|_| BlinkCursor::new());
684 let undo_manager = UndoManager::new();
685
686 let _subscriptions = vec![
687 // Key bindings can consume events before on_key_down. Observe input
688 // before action dispatch so every keystroke resets the blink delay.
689 cx.intercept_keystrokes({
690 let focus_handle = focus_handle.clone();
691 let blink_cursor = blink_cursor.downgrade();
692 move |_, window, cx| {
693 if focus_handle.is_focused(window) {
694 _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
695 }
696 }
697 }),
698 // Observe the blink cursor to repaint the view when it changes.
699 cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
700 // Blink the cursor when the window is active, pause when it's not.
701 cx.observe_window_activation(window, |input, window, cx| {
702 if window.is_window_active() {
703 let focus_handle = input.focus_handle.clone();
704 if focus_handle.is_focused(window) {
705 input.blink_cursor.update(cx, |blink_cursor, cx| {
706 blink_cursor.start(cx);
707 });
708 }
709 }
710 }),
711 cx.on_focus(&focus_handle, window, Self::on_focus),
712 cx.on_blur(&focus_handle, window, Self::on_blur),
713 ];
714
715 let text_style = window.text_style();
716
717 Self {
718 extras: M::Extras::default(),
719 focus_handle: focus_handle.clone(),
720 text: "".into(),
721 display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
722 search_session: super::SearchSession::default(),
723 search_activation_revision: 0,
724 searchable: false,
725 replaceable: true,
726 soft_wrap: true,
727 wrapping_indent: WrappingIndent::default(),
728 scroll_beyond_last_line: None,
729 cursor_surrounding_lines: None,
730 blink_cursor,
731 undo_manager,
732 inline_tokens: None,
733 pending_token: None,
734 replaying_history: false,
735 validated_token_edit: false,
736 document_revision: 0,
737 token_presentation: Default::default(),
738 token_bounds: Default::default(),
739 line_labels: Vec::new(),
740 line_label_color: gpui::Hsla::default(),
741 hovered_token: None,
742 pending_token_hover_exits: Vec::new(),
743 token_layout_cache: None,
744 pressed_token: None,
745 selections: Selections::default(),
746 selected_word_range: None,
747 ime_marked_range: None,
748 input_bounds: Bounds::default(),
749 selecting: false,
750 touch_selection: Default::default(),
751 disabled: false,
752 readonly: false,
753 text_align: TextAlign::Left,
754 masked: false,
755 clean_on_escape: false,
756 submit_on_enter: false,
757 show_whitespaces: false,
758 loading: false,
759 pattern: None,
760 validate: None,
761 number_step: Some(NumberStep::Fixed(1.)),
762 number_min: None,
763 number_max: None,
764 mode: LayoutMode::default(),
765 last_layout: None,
766 last_bounds: None,
767 last_selected_range: None,
768 column_select_start: None,
769 last_cursor: None,
770 scroll_handle: ScrollHandle::new(),
771 scroll_size: gpui::size(px(0.), px(0.)),
772 editor_scrollbar_snapshot: Cell::new(None),
773 longest_line_width: Cell::new(None),
774 editor_paddings: Edges::default(),
775 deferred_scroll_offset: None,
776 placeholder: SharedString::default(),
777 mask_pattern: MaskPattern::default(),
778 mask_pattern_set: false,
779 editor_style: InputEditorStyle::default(),
780 projected_editor_style: InputEditorStyle::default(),
781 diagnostic_popover: None,
782 context_menu_handler: None,
783 pending_context_menu: None,
784 enable_context_menu: true,
785 completion_inserting: false,
786 overlay_action_handler: None,
787 silent_replace_text: false,
788 emit_events: true,
789 _subscriptions,
790 _pending_update: false,
791 cursor_line_end_affinity: false,
792 auto_scroll: AutoScroll::default(),
793 }
794 }
795
796 /// Sets whether the context menu that shows on right-click is enabled.
797 ///
798 /// The context menu is enabled by default. Disabling it turns off the
799 /// right-click menu entirely, including a custom menu set on the element.
800 /// A custom menu already replaces the built-in one, so keep this enabled
801 /// to show only your own items.
802 pub fn context_menu(mut self, enable: bool) -> Self {
803 self.enable_context_menu = enable;
804 self
805 }
806
807 pub fn set_context_menu_enabled(&mut self, enabled: bool) {
808 self.enable_context_menu = enabled;
809 }
810
811 /// Set whether search UI allows replacement, default is true.
812 #[doc(hidden)]
813 pub fn replaceable(mut self, allow: bool) -> Self {
814 self.replaceable = allow;
815 self
816 }
817
818 /// Set placeholder
819 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
820 self.placeholder = placeholder.into();
821 self
822 }
823
824 /// Set highlighter language for for [`LayoutMode::CodeEditor`] mode.
825 pub fn set_highlighter(
826 &mut self,
827 new_language: impl Into<SharedString>,
828 cx: &mut Context<Self>,
829 ) {
830 match &mut self.mode {
831 LayoutMode::CodeEditor {
832 language,
833 highlighter,
834 ..
835 } => {
836 language.set_name(new_language.into());
837 *highlighter.borrow_mut() = None;
838 }
839 _ => {}
840 }
841 self.refresh(cx);
842 }
843
844 fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
845 match &mut self.mode {
846 LayoutMode::CodeEditor { highlighter, .. } => {
847 *highlighter.borrow_mut() = None;
848 }
849 _ => {}
850 }
851 cx.notify();
852 }
853
854 /// Install the parser/highlighter adapter used by code-editor mode.
855 pub fn set_highlighter_factory(
856 &mut self,
857 factory: InputHighlighterFactory,
858 cx: &mut Context<Self>,
859 ) {
860 self.mode.set_highlighter_factory(factory);
861 self._pending_update = true;
862 self.token_layout_cache = None;
863 cx.notify();
864 }
865
866 /// Install a default adapter without replacing an application-provided one.
867 pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
868 self.mode.ensure_highlighter_factory(factory);
869 }
870
871 pub fn set_editor_style(&mut self, style: InputEditorStyle) {
872 self.editor_style = style.clone();
873 self.projected_editor_style = style;
874 }
875
876 /// Set presentation padding for multi-line text and its scrollbar layout.
877 #[doc(hidden)]
878 pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
879 self.editor_paddings = paddings;
880 }
881
882 pub fn apply_highlighter_fold_candidates(
883 &mut self,
884 candidates: Vec<crate::input::FoldRange>,
885 cx: &mut Context<Self>,
886 ) {
887 if self.mode.is_folding() {
888 self.display_map.set_fold_candidates(candidates);
889 }
890 cx.notify();
891 }
892
893 #[inline]
894 pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
895 self.mode.diagnostics()
896 }
897
898 #[inline]
899 pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
900 self.mode.diagnostics_mut()
901 }
902
903 /// Set placeholder
904 pub fn set_placeholder(
905 &mut self,
906 placeholder: impl Into<SharedString>,
907 _: &mut Window,
908 cx: &mut Context<Self>,
909 ) {
910 self.placeholder = placeholder.into();
911 cx.notify();
912 }
913
914 /// Find which line and sub-line the given offset belongs to, along with the position within that sub-line.
915 ///
916 /// Returns:
917 ///
918 /// - The index of the line (zero-based) containing the offset.
919 /// - The index of the sub-line (zero-based) within the line containing the offset.
920 /// - The position of the offset.
921 pub(super) fn line_and_position_for_offset(
922 &self,
923 offset: usize,
924 ) -> (usize, usize, Option<Point<Pixels>>) {
925 let Some(last_layout) = &self.last_layout else {
926 return (0, 0, None);
927 };
928 let line_height = last_layout.line_height;
929
930 let mut y_offset = last_layout.visible_top;
931 for (vi, line) in last_layout.lines.iter().enumerate() {
932 let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
933 let local_offset = offset.saturating_sub(prev_lines_offset);
934 if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
935 let sub_line_index = line.row_at_y(pos.y, line_height).unwrap_or(0);
936 let adjusted_pos = point(pos.x + last_layout.line_number_width, pos.y + y_offset);
937 return (vi, sub_line_index, Some(adjusted_pos));
938 }
939
940 y_offset += line.size(line_height).height;
941 }
942 (0, 0, None)
943 }
944
945 /// Set the value of the input field: plain text, or [`InputContent`] to
946 /// restore text together with its inline tokens. Editing history is
947 /// cleared and no [`InputEvent::Change`] is emitted.
948 ///
949 /// For single-line inputs the caret is placed at the end of the text while
950 /// the view is scrolled back to the start, so a long value shows its
951 /// beginning instead of its tail (matching HTML `<input>`). Multi-line
952 /// inputs reset the selection to `0..0`.
953 pub fn set_value(
954 &mut self,
955 value: impl Into<super::InputContent>,
956 window: &mut Window,
957 cx: &mut Context<Self>,
958 ) {
959 let content = value.into();
960 self.inline_tokens = None;
961 self.undo_manager.set_ignoring(true);
962 self.emit_events = false;
963 self.replace_text(content.text().clone(), window, cx);
964 self.install_tokens(content);
965 self.undo_manager.set_ignoring(false);
966 self.emit_events = true;
967
968 self.reset_selection();
969 self.reset_lsp_state();
970 self.reset_scroll_to_start();
971
972 self.undo_manager.clear();
973 cx.notify();
974 }
975
976 /// Replace the entire text content while preserving undo history.
977 ///
978 /// Unlike [`set_value`](Self::set_value), this method records the
979 /// replacement in the undo stack, allowing the user to undo/redo
980 /// the change. The selection is placed at the end of the new text
981 /// for single-line inputs, or cleared (0..0) for multi-line inputs.
982 ///
983 /// Use this when programmatically replacing the full text but the
984 /// user should still be able to undo the operation — e.g. formatting.
985 pub fn replace_all(
986 &mut self,
987 text: impl Into<SharedString>,
988 window: &mut Window,
989 cx: &mut Context<Self>,
990 ) {
991 self.replace_text(text, window, cx);
992 self.reset_selection();
993 self.reset_lsp_state();
994 self.reset_scroll_to_start();
995
996 cx.notify();
997 }
998
999 /// Perform `f` with the user-facing edit restrictions lifted.
1000 ///
1001 /// The `disabled` and `readonly` modes only reject the changes made by the
1002 /// user, the programmatic APIs must always be able to update the text.
1003 pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1004 let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1005 (self.disabled, self.readonly) = (false, false);
1006 f(self);
1007 (self.disabled, self.readonly) = (was_disabled, was_readonly);
1008 }
1009
1010 /// Insert text at the current cursor position.
1011 ///
1012 /// And the cursor will be moved to the end of inserted text.
1013 pub fn insert(
1014 &mut self,
1015 text: impl Into<SharedString>,
1016 window: &mut Window,
1017 cx: &mut Context<Self>,
1018 ) {
1019 let text: SharedString = text.into();
1020 self.with_edits_allowed(|this| {
1021 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1022 let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1023 this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1024 let end = this.active_selection().end;
1025 this.set_cursor_to(end);
1026 });
1027 }
1028
1029 /// Apply `(byte range in the current text, replacement)` edits as one undo step.
1030 pub fn apply_edits(
1031 &mut self,
1032 edits: &[(Range<usize>, String)],
1033 window: &mut Window,
1034 cx: &mut Context<Self>,
1035 ) {
1036 self.with_edits_allowed(|this| {
1037 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1038 this.replace_text_in_ranges(edits, window, cx);
1039 });
1040 }
1041
1042 /// Replace text at the current cursor position.
1043 ///
1044 /// And the cursor will be moved to the end of replaced text.
1045 pub fn replace(
1046 &mut self,
1047 text: impl Into<SharedString>,
1048 window: &mut Window,
1049 cx: &mut Context<Self>,
1050 ) {
1051 let text: SharedString = text.into();
1052 self.with_edits_allowed(|this| {
1053 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1054 this.replace_text_in_range_silent(None, &text, window, cx);
1055 let end = this.active_selection().end;
1056 this.set_cursor_to(end);
1057 });
1058 }
1059
1060 fn replace_text(
1061 &mut self,
1062 text: impl Into<SharedString>,
1063 window: &mut Window,
1064 cx: &mut Context<Self>,
1065 ) {
1066 let text: SharedString = text.into();
1067 self.with_edits_allowed(|this| {
1068 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1069 let range = 0..this.text.chars().map(|c| c.len_utf16()).sum();
1070 this.replace_text_in_range_silent(Some(range), &text, window, cx);
1071 this.reset_highlighter(cx);
1072 });
1073 }
1074
1075 fn reset_selection(&mut self) {
1076 self.selections.remove_all_but_active();
1077
1078 // For single-line inputs the caret is placed at the end of the text
1079 // (matching HTML `<input>`); multi-line inputs reset the selection to
1080 // `0..0`.
1081 if self.is_single_line() {
1082 let end = self.text.len();
1083 self.set_cursor_to(end);
1084 } else {
1085 self.active_selection_mut().clear();
1086 }
1087 }
1088
1089 fn reset_lsp_state(&mut self) {
1090 if self.is_code_editor() {
1091 self._pending_update = true;
1092 M::reset_language_features(self);
1093 }
1094 }
1095
1096 fn reset_scroll_to_start(&mut self) {
1097 // Move scroll to the start. For single-line the caret is at the end, so
1098 // override the cursor-follow scroll for the next painted frame to keep
1099 // the start visible; the deferred offset is consumed during that paint.
1100 self.scroll_handle.set_offset(point(px(0.), px(0.)));
1101 if self.is_single_line() {
1102 self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1103 }
1104 }
1105
1106 /// Set with disabled mode.
1107 ///
1108 /// See also: [`Self::set_disabled`].
1109 #[allow(unused)]
1110 pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1111 self.disabled = disabled;
1112 self
1113 }
1114
1115 pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1116 if self.disabled == disabled {
1117 return;
1118 }
1119
1120 self.disabled = disabled;
1121 if disabled {
1122 M::hide_context_menu(self, cx);
1123 M::clear_inline_completion(self, cx);
1124 }
1125 cx.notify();
1126 }
1127
1128 /// Set with read-only mode.
1129 ///
1130 /// Unlike [`Self::disabled`], a read-only input keeps the normal appearance,
1131 /// focus, cursor, selection and copy behavior, it only rejects any change
1132 /// of the text made by the user.
1133 ///
1134 /// See also: [`Self::set_readonly`].
1135 #[allow(unused)]
1136 pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1137 self.readonly = readonly;
1138 self
1139 }
1140
1141 pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1142 if self.readonly == readonly {
1143 return;
1144 }
1145
1146 self.readonly = readonly;
1147 if readonly {
1148 M::hide_context_menu(self, cx);
1149 M::clear_inline_completion(self, cx);
1150 self.search_session.replace_mode = false;
1151 }
1152 cx.notify();
1153 }
1154
1155 /// Returns true if the user is allowed to change the text.
1156 ///
1157 /// This is false when the input is `disabled` or `readonly`, the programmatic
1158 /// APIs (e.g.: [`Self::set_value`], [`Self::insert`]) are not limited by this.
1159 pub fn is_editable(&self) -> bool {
1160 !self.disabled && !self.readonly
1161 }
1162
1163 /// Set true to clear the input by pressing Escape key.
1164 pub fn clean_on_escape(mut self) -> Self {
1165 self.clean_on_escape = true;
1166 self
1167 }
1168
1169 pub fn set_clean_on_escape(&mut self, clean: bool) {
1170 self.clean_on_escape = clean;
1171 }
1172
1173 /// Set true to treat `Enter` as a submit action in multi-line mode,
1174 /// while `Shift+Enter` inserts a newline.
1175 ///
1176 /// Default is `false` (both `Enter` and `Shift+Enter` insert a newline).
1177 #[doc(hidden)]
1178 pub fn submit_on_enter(mut self, submit: bool) -> Self {
1179 self.submit_on_enter = submit;
1180 self
1181 }
1182
1183 pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1184 self.submit_on_enter = submit;
1185 cx.notify();
1186 }
1187
1188 /// Set whether to show whitespace characters.
1189 #[doc(hidden)]
1190 pub fn show_whitespaces(mut self, show: bool) -> Self {
1191 self.show_whitespaces = show;
1192 self
1193 }
1194
1195 /// Update whether to show whitespace characters.
1196 pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1197 self.show_whitespaces = show;
1198 cx.notify();
1199 }
1200
1201 /// Empty rows reserved below the last line of content ("scroll
1202 /// beyond last line"), code-editor mode only. Mirrors VSCode's
1203 /// `editor.scrollBeyondLastLine` / Zed's `scroll_beyond_last_line`.
1204 ///
1205 /// - `None` (default): half the viewport, floored at
1206 /// [`BOTTOM_MARGIN_ROWS`] line-heights.
1207 /// - `Some(0)`: no trailing space; the cursor sits flush with the
1208 /// last row at scroll-max.
1209 /// - `Some(n)`: exactly `n` rows.
1210 pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1211 self.scroll_beyond_last_line = rows;
1212 self
1213 }
1214
1215 /// Update [`Self::scroll_beyond_last_line`] after construction.
1216 pub fn set_scroll_beyond_last_line(
1217 &mut self,
1218 rows: Option<usize>,
1219 _: &mut Window,
1220 cx: &mut Context<Self>,
1221 ) {
1222 if self.scroll_beyond_last_line == rows {
1223 return;
1224 }
1225 self.scroll_beyond_last_line = rows;
1226 cx.notify();
1227 }
1228
1229 /// Minimum number of lines the cursor is kept clear of the viewport's
1230 /// top/bottom edge before auto-scroll engages. Mirrors VSCode's
1231 /// `editor.cursorSurroundingLines` / Zed's `vertical_scroll_margin`.
1232 /// Orthogonal to [`Self::scroll_beyond_last_line`], which sizes the
1233 /// empty region; this controls the cursor's resting distance from the
1234 /// edge.
1235 ///
1236 /// - `None` (default): [`BOTTOM_MARGIN_ROWS`] lines, falling back to
1237 /// one line on small viewports.
1238 /// - `Some(n)`: exactly `n` lines, clamped to half the viewport.
1239 pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1240 self.cursor_surrounding_lines = lines;
1241 self
1242 }
1243
1244 /// Update [`Self::cursor_surrounding_lines`] after construction.
1245 pub fn set_cursor_surrounding_lines(
1246 &mut self,
1247 lines: Option<usize>,
1248 _: &mut Window,
1249 cx: &mut Context<Self>,
1250 ) {
1251 if self.cursor_surrounding_lines == lines {
1252 return;
1253 }
1254 self.cursor_surrounding_lines = lines;
1255 cx.notify();
1256 }
1257
1258 /// Set the default value of the input field.
1259 pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1260 let text: SharedString = value.into();
1261 self.text = Rope::from(self.normalize_input(&text).as_ref());
1262 if let Some(diagnostics) = self.mode.diagnostics_mut() {
1263 diagnostics.reset(&self.text)
1264 }
1265 // Note: We can't call display_map.set_text here because it needs cx.
1266 // The text will be set during prepare_if_need in element.rs
1267 self._pending_update = true;
1268 self
1269 }
1270
1271 /// Return the value of the input field as an owned string.
1272 ///
1273 /// The string is materialized on each call. See [`Self::text`] for the
1274 /// [`Rope`] the state owns, which is borrowed and costs nothing to read.
1275 pub fn value(&self) -> SharedString {
1276 SharedString::new(self.text.to_string())
1277 }
1278
1279 /// Return the portion of the value within the input field that
1280 /// is selected by the user, as an owned string.
1281 ///
1282 /// The string is materialized on each call. See [`Self::selected_text`]
1283 /// for the same selection borrowed out of the [`Rope`] the state owns.
1284 pub fn selected_value(&self) -> SharedString {
1285 SharedString::new(self.selected_text().to_string())
1286 }
1287
1288 /// Return the value without mask.
1289 pub fn unmask_value(&self) -> SharedString {
1290 self.mask_pattern.unmask(&self.text.to_string()).into()
1291 }
1292
1293 /// Kept so existing render paths keep compiling.
1294 ///
1295 /// Configuration used to be collected by a facade and applied here; the
1296 /// state now configures itself, so this does nothing and can be deleted at
1297 /// the call site.
1298 #[doc(hidden)]
1299 pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1300
1301 /// Return the text [`Rope`] of the input field.
1302 ///
1303 /// Borrowed from the state, so reading even a large document copies
1304 /// nothing. See [`Self::value`] when an owned string is wanted.
1305 pub fn text(&self) -> &Rope {
1306 &self.text
1307 }
1308
1309 /// Return the (0-based) [`Position`] of the cursor.
1310 pub fn cursor_position(&self) -> Position {
1311 let offset = self.cursor();
1312 self.text.offset_to_position(offset)
1313 }
1314
1315 /// Set (0-based) [`Position`] of the cursor.
1316 ///
1317 /// This will move the cursor to the specified line and column, and update the selection range.
1318 pub fn set_cursor_position(
1319 &mut self,
1320 position: impl Into<Position>,
1321 window: &mut Window,
1322 cx: &mut Context<Self>,
1323 ) {
1324 let position: Position = position.into();
1325 let offset = self.text.position_to_offset(&position);
1326
1327 self.move_to(offset, None, cx);
1328 self.update_preferred_column();
1329 self.focus(window, cx);
1330 }
1331
1332 /// Focus the input field.
1333 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1334 self.focus_handle.focus(window, cx);
1335 self.blink_cursor.update(cx, |cursor, cx| {
1336 cursor.start(cx);
1337 });
1338 }
1339
1340 /// Refresh the input, so the next render re-runs syntax highlighting and
1341 /// the LSP providers, not just a redraw.
1342 ///
1343 /// Assigning the `lsp` providers (or other render-affecting state) at
1344 /// runtime does not take effect until the text next changes. Call this
1345 /// afterwards to force the refresh on the next render.
1346 ///
1347 /// ```ignore
1348 /// input.update(cx, |state, cx| {
1349 /// state.extras.lsp.hover_provider = Some(provider);
1350 /// state.refresh(cx);
1351 /// });
1352 /// ```
1353 pub fn refresh(&mut self, cx: &mut Context<Self>) {
1354 self._pending_update = true;
1355 cx.notify();
1356 }
1357
1358 pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1359 self.undo_manager.break_transaction_coalescing();
1360 self.select_all_cursors_to(|s, sel| s.previous_boundary(sel.cursor_offset()), cx);
1361 }
1362
1363 pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1364 self.select_all_cursors_to(|s, sel| s.next_boundary(sel.cursor_offset()), cx);
1365 }
1366
1367 pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1368 if self.is_single_line() {
1369 return;
1370 }
1371 self.select_all_cursors_to_with_affinity(
1372 |s, sel| {
1373 s.vertical_selection_target(
1374 sel.cursor_offset(),
1375 sel.column_anchor,
1376 s.line_end_affinity_for(sel),
1377 -1,
1378 )
1379 },
1380 true,
1381 cx,
1382 );
1383 }
1384
1385 pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1386 if self.is_single_line() {
1387 return;
1388 }
1389 self.select_all_cursors_to_with_affinity(
1390 |s, sel| {
1391 s.vertical_selection_target(
1392 sel.cursor_offset(),
1393 sel.column_anchor,
1394 s.line_end_affinity_for(sel),
1395 1,
1396 )
1397 },
1398 true,
1399 cx,
1400 );
1401 }
1402
1403 pub(super) fn on_action_select_all(
1404 &mut self,
1405 _: &SelectAll,
1406 window: &mut Window,
1407 cx: &mut Context<Self>,
1408 ) {
1409 self.select_all(window, cx);
1410 }
1411
1412 pub(super) fn select_to_start(
1413 &mut self,
1414 _: &SelectToStart,
1415 _: &mut Window,
1416 cx: &mut Context<Self>,
1417 ) {
1418 self.undo_manager.break_transaction_coalescing();
1419 self.select_all_cursors_to(|_, _| 0, cx);
1420 }
1421
1422 pub(super) fn select_to_end(
1423 &mut self,
1424 _: &SelectToEnd,
1425 _: &mut Window,
1426 cx: &mut Context<Self>,
1427 ) {
1428 self.undo_manager.break_transaction_coalescing();
1429 let end = self.text.len();
1430 self.select_all_cursors_to(move |_, _| end, cx);
1431 }
1432
1433 pub(super) fn select_to_start_of_line(
1434 &mut self,
1435 _: &SelectToStartOfLine,
1436 _: &mut Window,
1437 cx: &mut Context<Self>,
1438 ) {
1439 self.undo_manager.break_transaction_coalescing();
1440 self.select_all_cursors_to(
1441 |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1442 cx,
1443 );
1444 }
1445
1446 pub(super) fn select_to_end_of_line(
1447 &mut self,
1448 _: &SelectToEndOfLine,
1449 _: &mut Window,
1450 cx: &mut Context<Self>,
1451 ) {
1452 self.undo_manager.break_transaction_coalescing();
1453 self.select_all_cursors_to_with_affinity(
1454 |s, sel| {
1455 (
1456 s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1457 true,
1458 )
1459 },
1460 false,
1461 cx,
1462 );
1463 }
1464
1465 pub(super) fn select_to_previous_word(
1466 &mut self,
1467 _: &SelectToPreviousWordStart,
1468 _: &mut Window,
1469 cx: &mut Context<Self>,
1470 ) {
1471 self.undo_manager.break_transaction_coalescing();
1472 self.select_all_cursors_to(
1473 |s, sel| s.previous_start_of_word_at(sel.cursor_offset()),
1474 cx,
1475 );
1476 }
1477
1478 pub(super) fn select_to_next_word(
1479 &mut self,
1480 _: &SelectToNextWordEnd,
1481 _: &mut Window,
1482 cx: &mut Context<Self>,
1483 ) {
1484 self.undo_manager.break_transaction_coalescing();
1485 self.select_all_cursors_to(|s, sel| s.next_end_of_word_at(sel.cursor_offset()), cx);
1486 }
1487
1488 /// Return the start offset of the previous word.
1489 /// Return the previous start offset of the word before `offset`.
1490 pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
1491 if self.masked {
1492 // The mask replaces every character, so the displayed text has no
1493 // word boundaries to move or delete by. Collapse the word to the
1494 // whole text.
1495 return 0;
1496 }
1497
1498 let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1499 // FIXME: Avoid to_string
1500 let left_part = self.text.slice(0..offset).to_string();
1501
1502 let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
1503 .rfind(|(_, s)| !s.trim_start().is_empty())
1504 .map(|(i, _)| i)
1505 .unwrap_or(0);
1506 self.token_boundary(target, Bias::Left)
1507 }
1508
1509 /// Return the next end offset of the word after `offset`.
1510 pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
1511 if self.masked {
1512 // See `previous_start_of_word_at`.
1513 return self.text.len();
1514 }
1515
1516 let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
1517 let right_part = self.text.slice(offset..self.text.len()).to_string();
1518
1519 let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
1520 .find(|(_, s)| !s.trim_start().is_empty())
1521 .map(|(i, s)| offset + i + s.len())
1522 .unwrap_or(self.text.len());
1523 self.token_boundary(target, Bias::Right)
1524 }
1525
1526 /// Get start of line byte offset for the given `offset`.
1527 ///
1528 /// When soft wrap is active, first press goes to visual line start,
1529 /// second press (already at visual start) goes to logical line start.
1530 pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1531 if self.is_single_line() {
1532 return 0;
1533 }
1534
1535 let row = self.text.offset_to_point(offset).row;
1536 let logical_start = self.text.line_start_offset(row);
1537
1538 if self.soft_wrap && self.is_code_editor() {
1539 let wrap_point = self
1540 .display_map
1541 .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1542 if let Some(line) = self.display_map.line(row)
1543 && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1544 {
1545 let visual_start = logical_start + range.start;
1546 if offset != visual_start {
1547 return visual_start;
1548 }
1549 }
1550 }
1551
1552 logical_start
1553 }
1554
1555 /// Get end of line byte offset for the given `offset`.
1556 ///
1557 /// When soft wrap is active, first press goes to visual line end,
1558 /// second press (already at visual end) goes to logical line end.
1559 pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
1560 if self.is_single_line() {
1561 return self.text.len();
1562 }
1563
1564 let row = self.text.offset_to_point(offset).row;
1565 let logical_start = self.text.line_start_offset(row);
1566 let logical_end = self.text.line_end_offset(row);
1567
1568 if self.soft_wrap && self.is_code_editor() {
1569 // Use the row the caret is drawn on: at a wrap boundary the raw offset would name
1570 // the next row, and a second End press would keep walking down instead of falling
1571 // through to the logical line end.
1572 let wrap_point = self
1573 .display_map
1574 .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
1575 if let Some(line) = self.display_map.line(row)
1576 && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
1577 {
1578 let visual_end = logical_start + range.end;
1579 if offset != visual_end {
1580 return visual_end;
1581 }
1582 }
1583 }
1584
1585 logical_end
1586 }
1587
1588 /// Get indent string of next line.
1589 ///
1590 /// To get current and next line indent, to return more depth one.
1591 pub(super) fn indent_of_next_line(&mut self) -> String {
1592 self.indent_of_next_line_at(self.cursor())
1593 }
1594
1595 /// Get indent string of the next line, relative to the given `offset`.
1596 pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
1597 if self.is_single_line() {
1598 return "".into();
1599 }
1600
1601 let mut current_indent = String::new();
1602 let mut next_indent = String::new();
1603 let line_end_affinity = self.line_end_affinity_at(offset);
1604 let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
1605 let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
1606 for c in self.text.slice(current_line_start_pos..).chars() {
1607 if !c.is_whitespace() {
1608 break;
1609 }
1610 if c == '\n' || c == '\r' {
1611 break;
1612 }
1613 current_indent.push(c);
1614 }
1615
1616 for c in self.text.slice(next_line_start_pos..).chars() {
1617 if !c.is_whitespace() {
1618 break;
1619 }
1620 if c == '\n' || c == '\r' {
1621 break;
1622 }
1623 next_indent.push(c);
1624 }
1625
1626 if next_indent.len() > current_indent.len() {
1627 return next_indent;
1628 }
1629
1630 // Smart indent: one extra level after lines ending with a trigger.
1631 // Skipped inside strings and comments: the trigger is literal text.
1632 if let Some(rules) = self.mode.language_config() {
1633 if self.mode.is_smart_indent()
1634 && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
1635 {
1636 let line_before: String = self
1637 .text
1638 .slice(current_line_start_pos..offset)
1639 .chars()
1640 .collect();
1641 if rules.opens_indent(line_before.trim_end()) {
1642 let tab = self.mode.tab_size();
1643 if tab.hard_tabs {
1644 current_indent.push('\t');
1645 } else {
1646 for _ in 0..tab.tab_size {
1647 current_indent.push(' ');
1648 }
1649 }
1650 } else {
1651 let line_after = self.text.slice(offset..next_line_start_pos).to_string();
1652 if rules.closes_indent(&line_after) {
1653 let tab = self.mode.tab_size();
1654 if current_indent.ends_with('\t') {
1655 current_indent.pop();
1656 } else {
1657 for _ in 0..tab.tab_size {
1658 if !current_indent.ends_with(' ') {
1659 break;
1660 }
1661 current_indent.pop();
1662 }
1663 }
1664 }
1665 }
1666 }
1667 }
1668
1669 current_indent
1670 }
1671
1672 /// Delete every selection as one batch. Collapsed cursors are first
1673 /// expanded to a deletion range by `collapsed_target` and non-empty
1674 /// selections delete their own range.
1675 ///
1676 /// `collapsed_intent` is the intent to record when every cursor is
1677 /// collapsed, which is what makes a run of single-character deletes undo
1678 /// as one gesture. Deleting a real selection is always atomic.
1679 fn delete_selections(
1680 &mut self,
1681 silent: bool,
1682 collapsed_intent: EditIntent,
1683 mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
1684 window: &mut Window,
1685 cx: &mut Context<Self>,
1686 ) {
1687 if !self.is_editable() {
1688 return;
1689 }
1690 let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
1691 let intent = if cursors.iter().all(|sel| sel.is_empty()) {
1692 collapsed_intent
1693 } else {
1694 EditIntent::Atomic
1695 };
1696 let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
1697 for sel in &cursors {
1698 let range = if sel.is_empty() {
1699 collapsed_target(self, sel.cursor_offset())
1700 } else {
1701 sel.start..sel.end
1702 };
1703 let (start, end) = (range.start.min(range.end), range.start.max(range.end));
1704 let mut selection = *sel;
1705 selection.start = start;
1706 selection.end = end;
1707 new_selections.push(selection);
1708 }
1709 // Capture the user's selections before expanding or merging deletion
1710 // ranges. The edit ranges cannot reconstruct their original carets.
1711 self.undo_manager.begin_transaction_with(intent);
1712 self.undo_manager
1713 .record_selections(cursors.clone(), cursors.clone());
1714 self.selections.replace_all(new_selections);
1715 self.undo_manager.set_pending_intent(intent);
1716
1717 let was_silent = self.silent_replace_text;
1718 self.silent_replace_text = silent;
1719 self.replace_text_in_range(None, "", window, cx);
1720 self.silent_replace_text = was_silent;
1721 self.undo_manager
1722 .record_selections(cursors, self.selections.iter().copied().collect());
1723 self.undo_manager.commit_transaction();
1724 self.pause_blink_cursor(cx);
1725 }
1726
1727 /// Decide pairing against the pre-edit text, before an opening quote can
1728 /// change its own syntax context. Ordinary characters never query syntax.
1729 fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
1730 if self.silent_replace_text
1731 || self.ime_marked_range.is_some()
1732 || !self.selections.is_single()
1733 || !self.active_selection().is_empty()
1734 || !range.is_empty()
1735 || range.start != self.cursor()
1736 || text.chars().count() != 1
1737 || !self.mode.is_auto_close()
1738 {
1739 return None;
1740 }
1741 let rules = self.mode.language_config()?;
1742 if self
1743 .text
1744 .chars_at(range.start)
1745 .next()
1746 .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
1747 {
1748 return None;
1749 }
1750 for (open, close, not_in) in rules.closing_pairs() {
1751 let Some(prefix) = open.strip_suffix(text) else {
1752 continue;
1753 };
1754 if !self.text_before_matches(range.start, prefix) {
1755 continue;
1756 }
1757 let start = range.start - prefix.len();
1758 if open == close
1759 && (self.is_escaped_at(start)
1760 || self
1761 .text
1762 .chars_at(start)
1763 .reversed()
1764 .next()
1765 .is_some_and(|c| c.is_alphanumeric() || c == '_'))
1766 {
1767 continue;
1768 }
1769 if not_in.contains(&M::editing_syntax_context(self, start)) {
1770 continue;
1771 }
1772 return Some((open.len(), close.into()));
1773 }
1774 None
1775 }
1776
1777 fn text_before_matches(&self, offset: usize, text: &str) -> bool {
1778 offset >= text.len()
1779 && self.text.is_char_boundary(offset - text.len())
1780 && self.text.slice(offset - text.len()..offset) == text
1781 }
1782
1783 fn text_after_matches(&self, offset: usize, text: &str) -> bool {
1784 offset + text.len() <= self.text.len()
1785 && self.text.is_char_boundary(offset + text.len())
1786 && self.text.slice(offset..offset + text.len()) == text
1787 }
1788
1789 fn is_escaped_at(&self, offset: usize) -> bool {
1790 self.text
1791 .chars_at(offset)
1792 .reversed()
1793 .take_while(|c| *c == '\\')
1794 .count()
1795 % 2
1796 == 1
1797 }
1798
1799 /// Cursor target when a typed closer should skip over an existing one.
1800 ///
1801 /// Returns `Some(offset)` when `new_text` is a single closer from the
1802 /// active [`LanguageConfig`](crate::input::language_config::LanguageConfig) that already follows the collapsed cursor and is
1803 /// not escaped. The caller then moves the cursor without editing text or
1804 /// history. `None` means insert normally.
1805 fn skip_over_target(&self, new_text: &str) -> Option<usize> {
1806 if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
1807 return None;
1808 }
1809 let rules = self.mode.language_config()?;
1810 let cursor = self.cursor();
1811 for (open, close, not_in) in rules.closing_pairs() {
1812 for (index, _) in close.char_indices() {
1813 if !close[index..].starts_with(new_text)
1814 || !self.text_before_matches(cursor, &close[..index])
1815 || !self.text_after_matches(cursor, &close[index..])
1816 {
1817 continue;
1818 }
1819 let context = M::editing_syntax_context(self, cursor);
1820 let generated =
1821 self.mode
1822 .auto_closed_pairs()
1823 .contains_closer(cursor, index, close.len());
1824 if !generated
1825 && not_in.contains(&context)
1826 && !(context == crate::input::SyntaxContext::String && open == close)
1827 {
1828 continue;
1829 }
1830 if self.is_escaped_at(cursor - index) {
1831 continue;
1832 }
1833 return Some(cursor + new_text.len());
1834 }
1835 }
1836 None
1837 }
1838
1839 pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
1840 // Nothing to delete at the start of the text. Propagate so an ancestor
1841 // (e.g. a command palette navigating back a level) can act on it.
1842 // This is harmless when nothing upstream is bound to backspace. With multiple
1843 // cursors the others can still delete, so only the lone-cursor case
1844 // propagates.
1845 if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
1846 cx.propagate();
1847 return;
1848 }
1849
1850 // Pair deletion follows automatic closing rules, independently of
1851 // structural brackets used by Enter.
1852 if self.mode.is_auto_close()
1853 && self.selections.is_single()
1854 && self.active_selection().is_empty()
1855 {
1856 let off = self.cursor();
1857 let deletion = self.mode.language_config().and_then(|rules| {
1858 rules.closing_pairs().find_map(|(open, close, not_in)| {
1859 if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
1860 {
1861 return None;
1862 }
1863 let start = off - open.len();
1864 let generated = self
1865 .mode
1866 .auto_closed_pairs()
1867 .contains(start..off, off..off + close.len());
1868 if self.is_escaped_at(start)
1869 || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
1870 {
1871 return None;
1872 }
1873 Some(start..off + close.len())
1874 })
1875 });
1876 if let Some(range) = deletion {
1877 let utf16 = self.range_to_utf16(&range);
1878 self.replace_text_in_range_silent(Some(utf16), "", window, cx);
1879 return;
1880 }
1881 }
1882
1883 self.delete_selections(
1884 false,
1885 EditIntent::Backspace,
1886 |s, offset| s.previous_boundary(offset)..offset,
1887 window,
1888 cx,
1889 );
1890 }
1891
1892 pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
1893 self.delete_selections(
1894 false,
1895 EditIntent::DeleteForward,
1896 |s, offset| offset..s.next_boundary(offset),
1897 window,
1898 cx,
1899 );
1900 }
1901
1902 pub(super) fn delete_to_beginning_of_line(
1903 &mut self,
1904 _: &DeleteToBeginningOfLine,
1905 window: &mut Window,
1906 cx: &mut Context<Self>,
1907 ) {
1908 self.delete_selections(
1909 true,
1910 EditIntent::Atomic,
1911 |s, offset| {
1912 let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
1913 if start == offset {
1914 start = start.saturating_sub(1);
1915 }
1916 start..offset
1917 },
1918 window,
1919 cx,
1920 );
1921 }
1922
1923 pub(super) fn delete_to_end_of_line(
1924 &mut self,
1925 _: &DeleteToEndOfLine,
1926 window: &mut Window,
1927 cx: &mut Context<Self>,
1928 ) {
1929 self.delete_selections(
1930 true,
1931 EditIntent::Atomic,
1932 |s, offset| {
1933 let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
1934 if end == offset {
1935 end = (end + 1).clamp(0, s.text.len());
1936 }
1937 offset..end
1938 },
1939 window,
1940 cx,
1941 );
1942 }
1943
1944 pub(super) fn delete_previous_word(
1945 &mut self,
1946 _: &DeleteToPreviousWordStart,
1947 window: &mut Window,
1948 cx: &mut Context<Self>,
1949 ) {
1950 self.delete_selections(
1951 true,
1952 EditIntent::Atomic,
1953 |s, offset| s.previous_start_of_word_at(offset)..offset,
1954 window,
1955 cx,
1956 );
1957 }
1958
1959 pub(super) fn delete_next_word(
1960 &mut self,
1961 _: &DeleteToNextWordEnd,
1962 window: &mut Window,
1963 cx: &mut Context<Self>,
1964 ) {
1965 self.delete_selections(
1966 true,
1967 EditIntent::Atomic,
1968 |s, offset| offset..s.next_end_of_word_at(offset),
1969 window,
1970 cx,
1971 );
1972 }
1973
1974 pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
1975 if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
1976 return;
1977 }
1978
1979 // Clear inline completion on enter (user chose not to accept it)
1980 if M::has_inline_completion(self) {
1981 M::clear_inline_completion(self, cx);
1982 }
1983
1984 // In multi-line mode with `submit_on_enter` enabled, a plain `Enter`
1985 // (without Shift) is treated as submit: propagate the action and emit
1986 // PressEnter without inserting a newline. `Shift+Enter` still inserts
1987 // a newline.
1988 let insert_newline = self.is_multi_line() && (!self.submit_on_enter || action.shift);
1989
1990 if insert_newline {
1991 if !self.selections.is_single() {
1992 // Insert a newline (with per-line indent) at every cursor.
1993 self.selections.merge_overlapping();
1994 let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
1995 let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
1996 for sel in &selections {
1997 let indent = if self.is_code_editor() {
1998 self.indent_of_next_line_at(sel.cursor_offset())
1999 } else {
2000 String::new()
2001 };
2002 edits.push((sel.start..sel.end, format!("\n{}", indent)));
2003 }
2004 edits.sort_by_key(|(range, _)| range.start);
2005 self.replace_text_in_ranges(&edits, window, cx);
2006 self.pause_blink_cursor(cx);
2007 } else {
2008 // Bracket split: Enter between `{|}` produces `{\n \n}`
2009 // with the cursor on the middle line. Controlled by smart_indent,
2010 // independently of automatic closing.
2011 // Skipped inside strings and comments: splitting there would
2012 // restructure literal text.
2013 let mut split = false;
2014 if self.is_code_editor() && self.active_selection().is_empty() {
2015 if let Some(rules) = self.mode.language_config() {
2016 if self.mode.is_smart_indent()
2017 && M::editing_syntax_context(self, self.cursor())
2018 == crate::input::SyntaxContext::Code
2019 {
2020 let off = self.cursor();
2021 let is_pair = rules.brackets.iter().any(|p| {
2022 !p.open.is_empty()
2023 && !p.close.is_empty()
2024 && p.open != p.close
2025 && self.text_before_matches(off, p.open.as_ref())
2026 && self.text_after_matches(off, p.close.as_ref())
2027 });
2028 if is_pair {
2029 // Base indent: leading whitespace only.
2030 let line_end_affinity = self.line_end_affinity_at(off);
2031 let line_start = self.start_of_line_at(off, line_end_affinity);
2032 let mut indent = String::new();
2033 for c in self.text.slice(line_start..).chars() {
2034 if !c.is_whitespace() || c == '\n' || c == '\r' {
2035 break;
2036 }
2037 indent.push(c);
2038 }
2039 // Extra level only with smart indent enabled.
2040 let mut inner = indent.clone();
2041 if self.mode.is_smart_indent() {
2042 let tab = self.mode.tab_size();
2043 if tab.hard_tabs {
2044 inner.push('\t');
2045 } else {
2046 for _ in 0..tab.tab_size {
2047 inner.push(' ');
2048 }
2049 }
2050 }
2051 let new_line_text = format!("\n{inner}\n{indent}");
2052 self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2053 self.set_cursor_to(off + 1 + inner.len());
2054 self.update_preferred_column();
2055 let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2056 self.undo_manager
2057 .record_selections(cursors.clone(), cursors);
2058 self.pause_blink_cursor(cx);
2059 split = true;
2060 }
2061 }
2062 }
2063 }
2064 if !split {
2065 // Get current line indent
2066 let indent = if self.is_code_editor() {
2067 self.indent_of_next_line()
2068 } else {
2069 "".to_string()
2070 };
2071
2072 // Add newline and indent
2073 let new_line_text = format!("\n{}", indent);
2074 self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2075 self.pause_blink_cursor(cx);
2076 }
2077 }
2078 } else {
2079 // Single line input or submit-on-enter: just emit the event
2080 // (e.g.: in a dialog to confirm, or a chat textarea to send).
2081 self.undo_manager.break_transaction_coalescing();
2082 cx.propagate();
2083 }
2084
2085 cx.emit(InputEvent::PressEnter {
2086 secondary: action.secondary,
2087 shift: action.shift,
2088 });
2089 }
2090
2091 pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2092 self.replace_text("", window, cx);
2093 self.set_selection(0, 0);
2094 self.scroll_to(0, None, cx);
2095 }
2096
2097 pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2098 if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2099 return;
2100 }
2101
2102 // Escape also dismisses a request whose popup has not arrived yet.
2103 M::hide_context_menu(self, cx);
2104
2105 // Collapse extra cursors back to the active one first.
2106 if !self.selections.is_single() {
2107 self.undo_manager.break_transaction_coalescing();
2108 self.selections.remove_all_but_active();
2109 cx.notify();
2110 return;
2111 }
2112
2113 // Clear inline completion on escape
2114 if M::has_inline_completion(self) {
2115 M::clear_inline_completion(self, cx);
2116 return; // Consume the escape, don't propagate
2117 }
2118 M::clear_inline_completion(self, cx);
2119
2120 // The handles and the edit menu are the topmost surface to dismiss.
2121 if self.touch_selection().is_some() {
2122 self.dismiss_touch_selection(cx);
2123 return;
2124 }
2125
2126 if self.ime_marked_range.is_some() {
2127 self.unmark_text(window, cx);
2128 }
2129
2130 if self.clean_on_escape {
2131 return self.clean(window, cx);
2132 }
2133
2134 cx.propagate();
2135 }
2136
2137 /// Show the right-click context menu as a native OS menu.
2138 pub(crate) fn handle_right_click_menu(
2139 &mut self,
2140 position: Point<Pixels>,
2141 offset: usize,
2142 window: &mut Window,
2143 cx: &mut Context<Self>,
2144 ) {
2145 if self.disabled {
2146 return;
2147 }
2148 if crate::GlobalState::is_in_deferred_context(cx) {
2149 return;
2150 }
2151
2152 if !self.active_selection().contains(offset) {
2153 self.move_to(offset, None, cx);
2154 }
2155
2156 if self.is_code_editor() {
2157 M::on_hover_definition(self, offset, window, cx);
2158 }
2159
2160 if let Some(handler) = self.context_menu_handler.clone() {
2161 let capabilities = self.context_menu_capabilities();
2162 cx.defer_in(window, move |_, window, cx| {
2163 handler(NativeMenu::new(), capabilities, position, window, cx);
2164 });
2165 }
2166 }
2167
2168 pub(super) fn add_cursor_above(
2169 &mut self,
2170 _: &AddCursorAbove,
2171 _: &mut Window,
2172 cx: &mut Context<Self>,
2173 ) {
2174 self.add_cursor_vertical(-1, cx);
2175 }
2176
2177 pub(super) fn add_cursor_below(
2178 &mut self,
2179 _: &AddCursorBelow,
2180 _: &mut Window,
2181 cx: &mut Context<Self>,
2182 ) {
2183 self.add_cursor_vertical(1, cx);
2184 }
2185
2186 /// Add a new cursor one display line above (`move_lines < 0`) or below each
2187 /// existing cursor, preserving the column. Cursors that would not move (at
2188 /// the first/last display row) or that would duplicate an existing cursor
2189 /// are skipped.
2190 fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2191 if !self.is_multi_line() {
2192 return;
2193 }
2194
2195 self.pause_blink_cursor(cx);
2196 // Changing the cursor set ends the editing gesture that came before it.
2197 self.undo_manager.break_transaction_coalescing();
2198
2199 let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2200 .selections
2201 .iter()
2202 .map(|sel| {
2203 (
2204 sel.cursor_offset(),
2205 sel.column_anchor,
2206 self.line_end_affinity_for(sel),
2207 )
2208 })
2209 .collect();
2210 let mut offsets: std::collections::HashSet<usize> =
2211 sources.iter().map(|(offset, _, _)| *offset).collect();
2212
2213 let mut newest: Option<usize> = None;
2214 for (offset, anchor, line_end_affinity) in sources {
2215 let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2216 let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2217 if target == offset || offsets.contains(&target) {
2218 continue;
2219 }
2220 offsets.insert(target);
2221 let id = self.selections.generate_id();
2222 let mut cursor = CursorSelection::new(id, target, target);
2223 cursor.column_anchor = anchor;
2224 self.selections.add(cursor);
2225 newest = Some(target);
2226 }
2227
2228 if let Some(newest) = newest {
2229 self.scroll_to(newest, None, cx);
2230 }
2231 cx.notify();
2232 }
2233
2234 /// Add an additional collapsed cursor at `offset`.
2235 ///
2236 /// Rejected when `offset` lands inside an existing selection or exactly on
2237 /// an existing cursor.
2238 pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2239 if !self.is_multi_line() {
2240 return;
2241 }
2242
2243 for sel in self.selections.iter() {
2244 if sel.contains(offset) {
2245 return;
2246 }
2247 if sel.is_collapsed() && sel.cursor_offset() == offset {
2248 return;
2249 }
2250 }
2251
2252 self.undo_manager.break_transaction_coalescing();
2253 let id = self.selections.generate_id();
2254 let mut selection = CursorSelection::new(id, offset, offset);
2255 selection.column_anchor = self.preferred_column_for(offset);
2256 self.selections.add(selection);
2257 cx.notify();
2258 }
2259
2260 /// Build a columnar (block) selection spanning the rows between the two
2261 /// points, one selection per display row at the same column span.
2262 ///
2263 /// The span keeps the columns the pointer sat past the end of a short row, so a row
2264 /// that runs out of text does not narrow the block for the rows that do reach that
2265 /// far. Each row is then clipped to its own end, selecting as much of the span as it
2266 /// actually has.
2267 pub(super) fn build_columnar_selection(
2268 &mut self,
2269 start: ColumnarPoint,
2270 end: ColumnarPoint,
2271 cx: &mut Context<Self>,
2272 ) {
2273 if !self.is_multi_line() {
2274 return;
2275 }
2276
2277 self.undo_manager.break_transaction_coalescing();
2278
2279 let (start_row, start_col) = self.columnar_row_column(start);
2280 let (end_row, end_col) = self.columnar_row_column(end);
2281 let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2282 let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2283
2284 let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2285 for row in start_row..=end_row {
2286 let sel_start = self
2287 .display_map
2288 .display_row_column_to_offset(row, start_col);
2289 let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2290 let id = self.selections.generate_id();
2291 let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2292 let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2293 new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2294 }
2295
2296 self.selections.replace_all(new_selections);
2297 cx.notify();
2298 }
2299
2300 /// Resolve a columnar point to the display row it is on and the column it reaches,
2301 /// counting the columns beyond the row's end so a short row keeps the full span.
2302 fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2303 let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2304 let row = self
2305 .display_map
2306 .wrap_row_to_display_row(display_point.row)
2307 .unwrap_or_else(|| {
2308 self.display_map
2309 .nearest_visible_display_row(display_point.row)
2310 });
2311
2312 (row, display_point.column + point.columns_past_line_end)
2313 }
2314
2315 pub(super) fn on_mouse_down(
2316 &mut self,
2317 event: &MouseDownEvent,
2318 window: &mut Window,
2319 cx: &mut Context<Self>,
2320 ) {
2321 // A token that consumed the press (a double click selecting it) must
2322 // not also place the caret.
2323 if window.default_prevented() {
2324 return;
2325 }
2326 self.undo_manager.break_transaction_coalescing();
2327 // Input has its own text selection; suppress the window-level text
2328 // selection (Root) so it does not start a drag from here.
2329 crate::global_state::GlobalState::suppress_text_selection(cx);
2330
2331 // Clear inline completion on any mouse interaction
2332 M::clear_inline_completion(self, cx);
2333 // A tap on the touch selection asks for its menu back. Any other press
2334 // places the caret or starts a new drag, and the handles and the menu
2335 // no longer belong to what is selected.
2336 if event.button == MouseButton::Left
2337 && event.click_count == 1
2338 && self.reopen_edit_menu_at(event.position, cx)
2339 {
2340 return;
2341 }
2342 self.dismiss_touch_selection(cx);
2343
2344 // If there have IME marked range and is empty (Means pressed Esc to abort IME typing)
2345 // Clear the marked range.
2346 if let Some(ime_marked_range) = &self.ime_marked_range {
2347 if ime_marked_range.len() == 0 {
2348 self.ime_marked_range = None;
2349 }
2350 }
2351
2352 self.selecting = true;
2353 let (offset, line_end_affinity, columns_past_line_end) =
2354 self.resolve_mouse_position(event.position);
2355
2356 if M::on_click(self, event, offset, window, cx) {
2357 return;
2358 }
2359
2360 // Triple click to select line
2361 if event.button == MouseButton::Left && event.click_count >= 3 {
2362 self.select_line(offset, window, cx);
2363 return;
2364 }
2365
2366 // Double click to select word
2367 if event.button == MouseButton::Left && event.click_count == 2 {
2368 self.select_word(offset, window, cx);
2369 // A double tap is touch's other way to select a word, and it
2370 // gets the handles and the menu like a long press does.
2371 if crate::GlobalState::is_touch_press(cx) {
2372 self.keep_touch_selection(cx);
2373 }
2374 return;
2375 }
2376
2377 // Show Mouse context menu
2378 if event.button == MouseButton::Right {
2379 if self.enable_context_menu {
2380 if !self.active_selection().contains(offset) {
2381 self.move_to(offset, None, cx);
2382 }
2383 self.pending_context_menu = Some((event.position, offset));
2384 }
2385 return;
2386 }
2387
2388 // Multi-cursor placement, multi-line only.
2389 if self.is_multi_line() && event.button == MouseButton::Left {
2390 if event.modifiers.alt
2391 && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2392 {
2393 // Alt+Shift starts a block; Linux also accepts Ghostty's Ctrl+Alt.
2394 // Mark selecting so the drag handler extends the block.
2395 self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2396 self.selecting = true;
2397 self.move_to_with_affinity(offset, None, line_end_affinity, cx);
2398 return;
2399 } else if event.modifiers.alt {
2400 self.add_cursor_at(offset, cx);
2401 // Keep click-to-add behavior, but use this press as the block
2402 // anchor if the user continues dragging with the left button.
2403 self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
2404 return;
2405 }
2406 }
2407
2408 if event.modifiers.shift {
2409 self.select_to_with_affinity(offset, line_end_affinity, cx);
2410 } else {
2411 self.move_to_with_affinity(offset, None, line_end_affinity, cx)
2412 }
2413 }
2414
2415 pub(super) fn on_mouse_up(
2416 &mut self,
2417 event: &MouseUpEvent,
2418 window: &mut Window,
2419 cx: &mut Context<Self>,
2420 ) {
2421 if event.button == MouseButton::Right {
2422 if let Some((position, offset)) = self.pending_context_menu.take() {
2423 self.handle_right_click_menu(position, offset, window, cx);
2424 }
2425 }
2426 if self.active_selection().is_empty() {
2427 self.active_selection_mut().reversed = false;
2428 }
2429 self.selecting = false;
2430 self.selected_word_range = None;
2431 self.column_select_start = None;
2432 self.auto_scroll.stop();
2433 }
2434
2435 pub(super) fn on_mouse_move(
2436 &mut self,
2437 event: &MouseMoveEvent,
2438 window: &mut Window,
2439 cx: &mut Context<Self>,
2440 ) {
2441 // Check if mouse is within bounds
2442 let within_bounds = self
2443 .last_bounds
2444 .as_ref()
2445 .map(|bounds| bounds.contains(&event.position))
2446 .unwrap_or(false);
2447
2448 if !within_bounds {
2449 // Clear hover when mouse leaves the input
2450 M::clear_hover_state(self, cx);
2451 return;
2452 }
2453
2454 // Show diagnostic popover on mouse move
2455 let (offset, _) = self.index_for_mouse_position(event.position);
2456 M::on_mouse_move(self, offset, event, window, cx);
2457
2458 if self.is_code_editor() {
2459 // Keep the current popover while the pointer stays on the same
2460 // diagnostic, so moving over a squiggle neither repaints nor
2461 // rebuilds the popover.
2462 match self
2463 .mode
2464 .diagnostics()
2465 .and_then(|set| set.for_offset(offset))
2466 {
2467 Some(diagnostic) => {
2468 if self.diagnostic_popover.as_deref() != Some(diagnostic) {
2469 self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
2470 cx.notify();
2471 }
2472 }
2473 None => {
2474 if self.diagnostic_popover.take().is_some() {
2475 cx.notify();
2476 }
2477 }
2478 }
2479 }
2480 }
2481
2482 pub(super) fn on_scroll_wheel(
2483 &mut self,
2484 event: &ScrollWheelEvent,
2485 window: &mut Window,
2486 cx: &mut Context<Self>,
2487 ) {
2488 let line_height = self
2489 .last_layout
2490 .as_ref()
2491 .map(|layout| layout.line_height)
2492 .unwrap_or(window.line_height());
2493 let delta = event.delta.pixel_delta(line_height);
2494
2495 let old_offset = self.scroll_handle.offset();
2496 self.update_scroll_offset(Some(old_offset + delta), cx);
2497
2498 // Only stop propagation if the offset actually changed
2499 if self.scroll_handle.offset() != old_offset {
2500 cx.stop_propagation();
2501 }
2502
2503 if self.diagnostic_popover.take().is_some() {
2504 cx.notify();
2505 }
2506 // The handles follow the text; the menu would sit over whatever
2507 // scrolls underneath it, so it steps aside until the finger lifts.
2508 self.edit_menu_on_scroll(event.touch_phase, cx);
2509 }
2510
2511 pub(super) fn update_scroll_offset(
2512 &mut self,
2513 offset: Option<Point<Pixels>>,
2514 cx: &mut Context<Self>,
2515 ) {
2516 let mut offset = offset.unwrap_or(self.scroll_handle.offset());
2517 let safe_y_range =
2518 (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.0))..px(0.);
2519
2520 offset.y = if self.is_single_line() {
2521 px(0.)
2522 } else {
2523 offset.y.clamp(safe_y_range.start, safe_y_range.end)
2524 };
2525 offset.x = clamp_horizontal_scroll_offset(
2526 offset.x,
2527 self.scroll_size.width,
2528 self.input_bounds.size.width,
2529 self.text_align,
2530 );
2531 if self.scroll_handle.offset() != offset {
2532 self.scroll_handle.set_offset(offset);
2533 cx.notify();
2534 }
2535 }
2536
2537 /// Scroll to make the given offset visible.
2538 ///
2539 /// If `direction` is Some, will keep edges at the same side.
2540 pub(crate) fn scroll_to(
2541 &mut self,
2542 offset: usize,
2543 direction: Option<MoveDirection>,
2544 cx: &mut Context<Self>,
2545 ) {
2546 let padding = if direction.is_some() {
2547 ScrollPadding::SurroundingLines
2548 } else {
2549 ScrollPadding::Minimal
2550 };
2551 self.scroll_to_with_padding(offset, direction, padding, cx);
2552 }
2553
2554 /// Reveal an offset with independently chosen direction restriction and padding.
2555 /// Search uses surrounding lines without restricting movement to match order.
2556 pub(crate) fn scroll_to_with_padding(
2557 &mut self,
2558 offset: usize,
2559 direction: Option<MoveDirection>,
2560 padding: ScrollPadding,
2561 cx: &mut Context<Self>,
2562 ) {
2563 let Some(last_layout) = self.last_layout.as_ref() else {
2564 return;
2565 };
2566 let Some(bounds) = self.last_bounds.as_ref() else {
2567 return;
2568 };
2569
2570 let mut scroll_offset = self.scroll_handle.offset();
2571 let was_offset = scroll_offset;
2572 let line_height = last_layout.line_height;
2573
2574 let point = self.text.offset_to_point(offset);
2575
2576 let row = point.row;
2577
2578 // Resolve the wrapped row even when the target is outside the last layout.
2579 let display_pos = self
2580 .display_map
2581 .buffer_pos_to_display_pos(crate::input::BufferPoint::new(row, point.column));
2582 let row_offset_y = self.display_map.row_top(display_pos.row, line_height);
2583 let row_extra = self.display_map.row_height(display_pos.row, line_height) - line_height;
2584
2585 // For Right alignment use 0 margin: the cursor indicator is clamped inside bounds
2586 // in layout_cursors, so shifting the text here would cause a first-click visual jump.
2587 let safety_margin = match last_layout.text_align {
2588 TextAlign::Left => RIGHT_MARGIN,
2589 TextAlign::Right => px(0.),
2590 TextAlign::Center => CURSOR_WIDTH,
2591 };
2592 if let Some(vi) = last_layout
2593 .visible_buffer_lines
2594 .iter()
2595 .position(|&line| line == row)
2596 {
2597 let line = &last_layout.lines[vi];
2598 let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
2599 if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
2600 let bounds_width = bounds.size.width - last_layout.line_number_width;
2601 let col_offset_x = pos.x;
2602 if col_offset_x - safety_margin < -scroll_offset.x {
2603 // If the position is out of the visible area, scroll to make it visible
2604 scroll_offset.x = -col_offset_x + safety_margin;
2605 } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
2606 scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
2607 }
2608 }
2609 }
2610
2611 // Scroll the row into view. Use the same edge clearance helper as
2612 // `TextElement::layout_cursors` so both scroll-into-view paths agree
2613 // (a mismatch flickered on `Down` at end-of-buffer with a small
2614 // `cursor_surrounding_lines` override).
2615 let edge_height =
2616 if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
2617 super::element::cursor_surrounding_padding(
2618 self.mode.is_auto_grow(),
2619 self.cursor_surrounding_lines,
2620 super::element::viewport_visible_lines(bounds.size.height, line_height),
2621 line_height,
2622 )
2623 } else {
2624 line_height
2625 };
2626 if row_offset_y - edge_height + line_height < -scroll_offset.y {
2627 // Scroll up
2628 scroll_offset.y = -row_offset_y + edge_height - line_height;
2629 } else if row_offset_y + row_extra + edge_height > -scroll_offset.y + bounds.size.height {
2630 // Scroll down
2631 scroll_offset.y = -(row_offset_y + row_extra - bounds.size.height + edge_height);
2632 }
2633
2634 // Avoid necessary scroll, when it was already in the correct position.
2635 if direction == Some(MoveDirection::Up) {
2636 scroll_offset.y = scroll_offset.y.max(was_offset.y);
2637 } else if direction == Some(MoveDirection::Down) {
2638 scroll_offset.y = scroll_offset.y.min(was_offset.y);
2639 }
2640
2641 // Clamp the deferred target into the same safe range that
2642 // `update_scroll_offset` enforces on persist, so paint never shows an
2643 // over-scrolled frame before the post-paint clamp pulls it back.
2644 let safe_y_min = (-self.scroll_size.height + self.input_bounds.size.height).min(px(0.));
2645 scroll_offset.x = scroll_offset.x.min(px(0.));
2646 scroll_offset.y = scroll_offset.y.clamp(safe_y_min, px(0.));
2647 self.deferred_scroll_offset = Some(scroll_offset);
2648 cx.notify();
2649 }
2650
2651 pub(super) fn show_character_palette(
2652 &mut self,
2653 _: &ShowCharacterPalette,
2654 window: &mut Window,
2655 _: &mut Context<Self>,
2656 ) {
2657 window.show_character_palette();
2658 }
2659
2660 /// The text of every non-empty selection, in document order.
2661 fn selected_texts(&self) -> Vec<String> {
2662 let mut selections: Vec<CursorSelection> = self
2663 .selections
2664 .iter()
2665 .copied()
2666 .filter(|sel| !sel.is_empty())
2667 .collect();
2668 selections.sort_by_key(|sel| sel.start);
2669 selections
2670 .iter()
2671 .map(|sel| self.text.slice(*sel).to_string())
2672 .collect()
2673 }
2674
2675 pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
2676 if !self.is_copyable() {
2677 return;
2678 }
2679
2680 let texts = self.selected_texts();
2681
2682 cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
2683 }
2684
2685 pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
2686 if !self.is_copyable() {
2687 return;
2688 }
2689
2690 let texts = self.selected_texts();
2691
2692 cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
2693
2694 self.undo_manager.set_pending_intent(EditIntent::Atomic);
2695 self.replace_text_in_range_silent(None, "", window, cx);
2696 }
2697
2698 pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
2699 if !self.is_editable() {
2700 return;
2701 }
2702 if let Some(clipboard) = cx.read_from_clipboard() {
2703 self.insert_clipboard(clipboard, window, cx);
2704 return;
2705 }
2706 // The synchronous read is empty on platforms whose clipboard is
2707 // asynchronous and permission-gated (the web), so fall back to the
2708 // real read. It has to start here, still inside the user activation
2709 // that dispatched `Paste`, or the browser refuses the read.
2710 let read = cx.read_from_clipboard_async();
2711 let target = self.paste_target();
2712 cx.spawn_in(window, async move |this, cx| match read.await {
2713 Ok(Some(clipboard)) => {
2714 this.update_in(cx, |this, window, cx| {
2715 // The read can sit behind a permission prompt for as
2716 // long as the user likes. If they edited, moved the
2717 // caret or left the input meanwhile, the paste would
2718 // land where they no longer mean it to; drop it, as the
2719 // browser's own paste event only reaches the focused
2720 // input too.
2721 if this.is_editable()
2722 && this.focus_handle.is_focused(window)
2723 && this.paste_target() == target
2724 {
2725 this.insert_clipboard(clipboard, window, cx);
2726 }
2727 })
2728 .ok();
2729 }
2730 Ok(None) => {}
2731 Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
2732 })
2733 .detach();
2734 }
2735
2736 /// Where a paste would go right now: the document as edited so far and
2737 /// the selections it would replace. Two equal targets mean an edit made
2738 /// for one still applies to the other.
2739 fn paste_target(&self) -> PasteTarget {
2740 PasteTarget {
2741 document_revision: self.document_revision,
2742 selections: self.selections.iter().copied().collect(),
2743 }
2744 }
2745
2746 /// Inserts the clipboard text the way `Paste` does: one atomic edit,
2747 /// newlines dropped on a single-line input, one line per selection when
2748 /// the counts match on a multi-line one. A clipboard without text (an
2749 /// image, say) is left alone rather than replacing the selection with
2750 /// nothing.
2751 fn insert_clipboard(
2752 &mut self,
2753 clipboard: ClipboardItem,
2754 window: &mut Window,
2755 cx: &mut Context<Self>,
2756 ) {
2757 let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
2758 return;
2759 };
2760 // A paste is one atomic edit, never part of a typing run.
2761 self.undo_manager.set_pending_intent(EditIntent::Atomic);
2762
2763 if !self.is_multi_line() {
2764 new_text = new_text.replace('\n', "");
2765 self.replace_text_in_range_silent(None, &new_text, window, cx);
2766 self.scroll_to(self.cursor(), None, cx);
2767 return;
2768 }
2769
2770 // Distribute one clipboard line per selection when the counts match.
2771 // Otherwise insert the whole clipboard text at each cursor.
2772 if !self.selections.is_single() {
2773 self.selections.merge_overlapping();
2774 }
2775 let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
2776 let count = self.selections.len();
2777 if count > 1 && lines.len() == count {
2778 let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2779 selections.sort_by_key(|sel| sel.start);
2780 let edits: Vec<(Range<usize>, String)> = selections
2781 .iter()
2782 .zip(lines)
2783 .map(|(sel, line)| (sel.start..sel.end, line))
2784 .collect();
2785 self.replace_text_in_ranges(&edits, window, cx);
2786 } else {
2787 self.replace_text_in_range_silent(None, &new_text, window, cx);
2788 }
2789 self.scroll_to(self.cursor(), None, cx);
2790 }
2791
2792 /// The intent of a batch the caller did not label: inserting text at
2793 /// collapsed cursors is typing, anything else stands on its own.
2794 fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
2795 if !new_text.is_empty()
2796 && !new_text.contains(['\n', '\r'])
2797 && edits.iter().all(|(range, _)| range.is_empty())
2798 {
2799 EditIntent::Typing
2800 } else {
2801 EditIntent::Atomic
2802 }
2803 }
2804
2805 /// Where a cursor stood before an edit made with this intent.
2806 ///
2807 /// Backspace and forward delete expand a collapsed cursor over the text
2808 /// they are about to remove, so the recorded cursor has to collapse back to
2809 /// the side it came from for undo to restore it where the user left it.
2810 fn collapse_for_intent(
2811 intent: EditIntent,
2812 mut selection: CursorSelection,
2813 range: &Range<usize>,
2814 ) -> CursorSelection {
2815 match intent {
2816 EditIntent::Backspace => selection.place_at(range.end, None),
2817 EditIntent::DeleteForward => selection.place_at(range.start, None),
2818 EditIntent::Typing | EditIntent::Atomic => {}
2819 }
2820 selection
2821 }
2822
2823 /// Whether an edit rewrites the character before a collapsed cursor, as the
2824 /// macOS Korean IME does on each keystroke instead of marking text.
2825 fn rewrites_typed_char(
2826 &self,
2827 selection: CursorSelection,
2828 range: &Range<usize>,
2829 old_text: &str,
2830 new_text: &str,
2831 ) -> bool {
2832 !self.silent_replace_text
2833 && selection.is_collapsed()
2834 && selection.cursor_offset() == range.end
2835 && old_text.chars().count() == 1
2836 && !old_text.contains(['\n', '\r'])
2837 && !new_text.contains(['\n', '\r'])
2838 }
2839
2840 fn push_history(
2841 &mut self,
2842 text: &Rope,
2843 range: &Range<usize>,
2844 new_text: &str,
2845 requested_intent: Option<EditIntent>,
2846 selection_before: CursorSelection,
2847 selection_after: Option<CursorSelection>,
2848 ) -> bool {
2849 self.document_revision = self.document_revision.wrapping_add(1);
2850 let token_delta = self.edit_tokens(range, new_text.len());
2851 if self.undo_manager.is_ignoring() {
2852 return false;
2853 }
2854
2855 let range =
2856 text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
2857 let old_text = text.slice(range.clone()).to_string();
2858 let new_range = range.start..range.start + new_text.len();
2859
2860 let intent = requested_intent.unwrap_or_else(|| {
2861 if range.is_empty()
2862 && old_text.is_empty()
2863 && !new_text.is_empty()
2864 && !new_text.contains(['\n', '\r'])
2865 || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
2866 {
2867 EditIntent::Typing
2868 } else {
2869 EditIntent::Atomic
2870 }
2871 });
2872
2873 let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
2874 let selection_after =
2875 selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
2876
2877 let open_transaction = self.undo_manager.has_open_transaction();
2878 let mut change = Change::new(range, &old_text, new_range, new_text);
2879 change.token_delta = token_delta;
2880 let recorded = self.undo_manager.record_transaction(change, intent);
2881 // A batch records its own cursor sets. This covers a change that is a
2882 // transaction on its own.
2883 if recorded && !open_transaction {
2884 self.undo_manager
2885 .record_selections(vec![selection_before], vec![selection_after]);
2886 }
2887 recorded
2888 }
2889
2890 pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
2891 self.replay_history(true, window, cx);
2892 }
2893
2894 pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
2895 self.replay_history(false, window, cx);
2896 }
2897
2898 fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
2899 if !self.is_editable() {
2900 return;
2901 }
2902 let replay = if undo {
2903 self.undo_manager.undo()
2904 } else {
2905 self.undo_manager.redo()
2906 };
2907 let Some(replay) = replay else {
2908 return;
2909 };
2910 let token_aware = self.inline_tokens.is_some()
2911 || replay
2912 .changes
2913 .iter()
2914 .any(|change| change.token_delta.is_some());
2915 let emit_events = self.emit_events;
2916 if token_aware {
2917 self.emit_events = false;
2918 }
2919 self.replaying_history = token_aware;
2920 self.undo_manager.set_ignoring(true);
2921 for change in &replay.changes {
2922 let (range, text) = if undo {
2923 (change.new_range.into(), &change.old_text)
2924 } else {
2925 (change.old_range.into(), &change.new_text)
2926 };
2927 let range_utf16 = self.range_to_utf16(&range);
2928 self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
2929 self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
2930 }
2931 self.restore_selections(replay.selections);
2932 self.mode
2933 .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
2934 if token_aware {
2935 // Token replay bypasses IME normalization; a stale marked range
2936 // would otherwise describe text that no longer exists.
2937 self.ime_marked_range = None;
2938 }
2939 self.undo_manager.set_ignoring(false);
2940 self.replaying_history = false;
2941 self.emit_events = emit_events;
2942 if token_aware && emit_events {
2943 cx.emit(InputEvent::Change);
2944 }
2945 cx.notify();
2946 }
2947
2948 /// Restore a set of selections captured in a transaction, clamping offsets
2949 /// to the current text length. `None` leaves the current selections as the
2950 /// replay left them.
2951 fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
2952 let Some(selections) = selections else {
2953 return;
2954 };
2955
2956 let len = self.text.len();
2957 let restored: Vec<CursorSelection> = selections
2958 .into_iter()
2959 .map(|mut sel| {
2960 sel.start = sel.start.min(len);
2961 sel.end = sel.end.min(len);
2962 sel
2963 })
2964 .collect();
2965 self.selections.replace_all(restored);
2966 self.selections.merge_overlapping();
2967 }
2968
2969 /// Get byte offset of the cursor.
2970 ///
2971 /// The offset is the UTF-8 offset.
2972 pub fn cursor(&self) -> usize {
2973 if let Some(ime_marked_range) = &self.ime_marked_range {
2974 return ime_marked_range.end;
2975 }
2976
2977 self.selections.active().cursor_offset()
2978 }
2979
2980 /// Returns the active selection.
2981 pub(super) fn active_selection(&self) -> &CursorSelection {
2982 self.selections.active()
2983 }
2984
2985 /// Returns a mutable reference to the active selection.
2986 pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
2987 self.selections.active_mut()
2988 }
2989
2990 /// Sets the active selection to the given range, keeping its `reversed`
2991 /// and `column_anchor` state untouched.
2992 pub(super) fn set_selection(&mut self, start: usize, end: usize) {
2993 let range = self.normalize_token_range(start..end);
2994 let (start, end) = (range.start, range.end);
2995 let active = self.active_selection_mut();
2996 active.start = start;
2997 active.end = end;
2998 }
2999
3000 /// Collapses the active selection to a cursor at the given offset,
3001 /// clearing `reversed`.
3002 pub(super) fn set_cursor_to(&mut self, offset: usize) {
3003 let offset = self.token_boundary(offset, Bias::Right);
3004 let active = self.active_selection_mut();
3005 active.start = offset;
3006 active.end = offset;
3007 active.reversed = false;
3008 }
3009
3010 /// Visible row range in the last laid-out viewport, `None` before first layout.
3011 pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3012 self.last_layout.as_ref().map(|l| l.visible_range.clone())
3013 }
3014
3015 /// Current scroll offset of the editor viewport.
3016 pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
3017 self.scroll_handle.offset()
3018 }
3019
3020 /// Set scroll offset of the editor viewport.
3021 ///
3022 /// The offset will be clamped to the valid range, and applied after the next layout.
3023 pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
3024 self.deferred_scroll_offset = Some(offset);
3025 cx.notify();
3026 }
3027
3028 /// Laid-out line height; `None` before first layout.
3029 pub fn line_height(&self) -> Option<gpui::Pixels> {
3030 self.last_layout.as_ref().map(|l| l.line_height)
3031 }
3032
3033 /// Returns the active selection as a byte range into the text.
3034 ///
3035 /// With multiple cursors, this reads only the active selection.
3036 ///
3037 /// The range is empty (`start == end`) when no text is selected; in
3038 /// that case the offset equals `cursor()`. Byte offsets are measured
3039 /// in the underlying rope's byte units.
3040 pub fn selected_range(&self) -> std::ops::Range<usize> {
3041 (*self.selections.active()).into()
3042 }
3043
3044 pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3045 self.undo_manager.break_transaction_coalescing();
3046 self.selections.remove_all_but_active();
3047 self.set_selection(0, self.text.len());
3048 cx.notify();
3049 }
3050
3051 /// Set the selected range using UTF-8 byte offsets, removing additional cursors.
3052 ///
3053 /// Non-empty ranges expand to character boundaries. Empty ranges remain empty and are
3054 /// clipped to the preceding character boundary.
3055 pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3056 let range = self.normalize_token_range(range);
3057 let end_bias = if range.start == range.end {
3058 Bias::Left
3059 } else {
3060 Bias::Right
3061 };
3062 let start = self.text.clip_offset(range.start, Bias::Left);
3063 let end = self.text.clip_offset(range.end, end_bias);
3064
3065 self.move_to(start, None, cx);
3066 self.active_selection_mut().reversed = false;
3067 self.selected_word_range = None;
3068 self.select_to(end, cx);
3069 }
3070
3071 /// Resolve a mouse position to a byte offset in the text.
3072 ///
3073 /// Also reports the caret's line-end affinity for that offset: `true` when the position
3074 /// landed on the wrap boundary of a non-final visual row, meaning the caret belongs at the
3075 /// end of that row rather than at the start of the next one. Callers that place or extend a
3076 /// selection must pass it on, or clicking past the last glyph of a wrapped row leaves a
3077 /// caret one row below the pointer.
3078 pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3079 let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3080 (offset, line_end_affinity)
3081 }
3082
3083 /// Resolve a mouse position to a text offset, the caret affinity to use for it, and
3084 /// how many columns the pointer sits past the end of that row.
3085 ///
3086 /// Only a columnar selection needs the third value; everywhere else a position past
3087 /// the end of a row means the end of that row, and
3088 /// [`Self::index_for_mouse_position`] is the call to make.
3089 pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3090 // If the text is empty, always return 0
3091 if self.text.len() == 0 {
3092 return (0, false, 0);
3093 }
3094
3095 let (Some(bounds), Some(last_layout)) =
3096 (self.last_bounds.as_ref(), self.last_layout.as_ref())
3097 else {
3098 return (0, false, 0);
3099 };
3100
3101 let line_height = last_layout.line_height;
3102 let line_number_width = last_layout.line_number_width;
3103
3104 // TIP: About the IBeam cursor
3105 //
3106 // If cursor style is IBeam, the mouse mouse position is in the middle of the cursor (This is special in OS)
3107
3108 // The position is relative to the bounds of the text input
3109 //
3110 // bounds.origin:
3111 //
3112 // - included the input padding.
3113 // - included the scroll offset.
3114 let inner_position = position - bounds.origin - point(line_number_width, px(0.));
3115
3116 let mut y_offset = last_layout.visible_top;
3117 // Position relative to the last line walked, kept for a pointer that ends up
3118 // below every line.
3119 let mut last_line_pos = None;
3120
3121 // Traverse visible buffer lines (compact, no hidden entries)
3122 for (vi, (line_layout, _buffer_line)) in last_layout
3123 .lines
3124 .iter()
3125 .zip(last_layout.visible_buffer_lines.iter())
3126 .enumerate()
3127 {
3128 let line_start_offset = last_layout.visible_line_byte_offsets[vi];
3129
3130 // Calculate line origin for this display row
3131 let line_origin = point(px(0.), y_offset);
3132 let pos = inner_position - line_origin;
3133
3134 // Return offset by use closest_index_for_x if is single line mode.
3135 if self.is_single_line() {
3136 let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
3137 // A single line never wraps, so there is no boundary to disambiguate.
3138 return (
3139 self.resolve_index(line_start_offset + local_index),
3140 false,
3141 0,
3142 );
3143 }
3144
3145 // Check if mouse is in this line's bounds
3146 if let Some((local_index, line_end_affinity)) =
3147 line_layout.closest_index_for_position(pos, last_layout)
3148 {
3149 return (
3150 self.resolve_index(line_start_offset + local_index),
3151 line_end_affinity,
3152 line_layout.columns_past_line_end(pos, last_layout),
3153 );
3154 } else if pos.y < px(0.) {
3155 // Mouse is above this line, return start of this line
3156 return (self.resolve_index(line_start_offset), false, 0);
3157 }
3158
3159 y_offset += line_layout.size(line_height).height;
3160 last_line_pos = Some(pos);
3161 }
3162
3163 // Clamp to the last laid-out row. Returning the end of the whole document
3164 // would select unseen text before drag autoscroll has reached it.
3165 let last_position = last_layout
3166 .lines
3167 .last()
3168 .zip(last_line_pos)
3169 .zip(last_layout.visible_line_byte_offsets.last())
3170 .map(|((line_layout, pos), line_start)| {
3171 let last_row_top = line_layout.row_top(
3172 line_layout.wrapped_lines.len().saturating_sub(1),
3173 line_height,
3174 );
3175 let pos = point(pos.x, last_row_top);
3176 (
3177 self.resolve_index(line_start + line_layout.len()),
3178 false,
3179 line_layout.columns_past_line_end(pos, last_layout),
3180 )
3181 });
3182
3183 last_position.unwrap_or((self.text.len(), false, 0))
3184 }
3185
3186 /// Map a display byte index back to a text offset, undoing the mask expansion when the input
3187 /// is masked.
3188 fn resolve_index(&self, index: usize) -> usize {
3189 if self.masked {
3190 self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
3191 } else {
3192 index.min(self.text.len())
3193 }
3194 }
3195
3196 /// Returns a y offsetted point for the line origin.
3197 /// Select the text from the current cursor position to the given offset.
3198 ///
3199 /// The offset is the UTF-8 offset.
3200 ///
3201 /// Ensure the offset use self.next_boundary or self.previous_boundary to get the correct offset.
3202 /// Extend a single selection so its moving end lands at `offset`, flipping
3203 /// `reversed` when the ends cross. When a sticky `word_range` is given the
3204 /// selection is kept covering it.
3205 fn extend_selection(
3206 sel: &mut CursorSelection,
3207 offset: usize,
3208 word_range: Option<CursorSelection>,
3209 ) {
3210 if sel.reversed {
3211 sel.start = offset;
3212 } else {
3213 sel.end = offset;
3214 }
3215
3216 if sel.end < sel.start {
3217 sel.reversed = !sel.reversed;
3218 std::mem::swap(&mut sel.start, &mut sel.end);
3219 }
3220
3221 if let Some(word_range) = word_range {
3222 if sel.start > word_range.start {
3223 sel.start = word_range.start;
3224 }
3225 if sel.end < word_range.end {
3226 sel.end = word_range.end;
3227 }
3228 }
3229 }
3230
3231 /// Extend only the active selection to `offset`. Used by mouse drag.
3232 pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
3233 self.select_to_with_affinity(offset, false, cx);
3234 }
3235
3236 /// Like [`Self::select_to`], but also carries the caret's line-end affinity.
3237 ///
3238 /// See [`Self::move_to_with_affinity`] for why the affinity travels with the offset. Note
3239 /// that plain [`Self::select_to`] clears the affinity: every offset it is given came from
3240 /// the text rather than from a visual position, so the caret has no reason to keep sticking
3241 /// to the end of a wrapped row.
3242 pub(crate) fn select_to_with_affinity(
3243 &mut self,
3244 offset: usize,
3245 line_end_affinity: bool,
3246 cx: &mut Context<Self>,
3247 ) {
3248 M::clear_inline_completion(self, cx);
3249
3250 self.cursor_line_end_affinity = line_end_affinity;
3251 let offset = self.cursor_boundary(offset, Bias::Left);
3252 let word_range = self.selected_word_range;
3253 Self::extend_selection(self.active_selection_mut(), offset, word_range);
3254 let range = self.normalize_token_range(self.selected_range());
3255 self.set_selection(range.start, range.end);
3256
3257 if self.active_selection().is_empty() {
3258 self.update_preferred_column();
3259 }
3260 cx.notify()
3261 }
3262
3263 /// Extend every selection to the offset produced by `f`, then merge any
3264 /// selections that now overlap. Used by keyboard selection commands.
3265 fn select_all_cursors_to(
3266 &mut self,
3267 f: impl Fn(&Self, &CursorSelection) -> usize,
3268 cx: &mut Context<Self>,
3269 ) {
3270 self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
3271 }
3272
3273 /// Extend selections with caret affinity, preserving their column anchors even
3274 /// when vertical movement collapses a selection to a cursor.
3275 fn select_all_cursors_to_with_affinity(
3276 &mut self,
3277 f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
3278 preserve_column: bool,
3279 cx: &mut Context<Self>,
3280 ) {
3281 self.pause_blink_cursor(cx);
3282 self.undo_manager.break_transaction_coalescing();
3283 M::clear_inline_completion(self, cx);
3284
3285 let mut active_affinity = false;
3286 let new_selections: Vec<CursorSelection> = self
3287 .selections
3288 .iter()
3289 .map(|sel| {
3290 let (offset, affinity) = f(self, sel);
3291 if sel.id == self.active_selection().id {
3292 active_affinity = affinity;
3293 }
3294 let offset = self.cursor_boundary(offset, Bias::Left);
3295 let mut new_sel = *sel;
3296 Self::extend_selection(&mut new_sel, offset, None);
3297 let range = self.normalize_token_range(new_sel.start..new_sel.end);
3298 new_sel.start = range.start;
3299 new_sel.end = range.end;
3300 if !preserve_column {
3301 new_sel.column_anchor =
3302 self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
3303 } else if new_sel.column_anchor.is_none() {
3304 new_sel.column_anchor = self.preferred_column_for_with_affinity(
3305 sel.cursor_offset(),
3306 self.line_end_affinity_for(sel),
3307 );
3308 }
3309 new_sel
3310 })
3311 .collect();
3312 self.cursor_line_end_affinity = active_affinity;
3313 self.selections.replace_all(new_selections);
3314 self.selections.merge_overlapping();
3315
3316 self.scroll_to(self.cursor(), None, cx);
3317 cx.notify()
3318 }
3319
3320 /// Unselects the currently selected text.
3321 pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3322 self.undo_manager.break_transaction_coalescing();
3323 let offset = self.cursor();
3324 self.set_cursor_to(offset);
3325 cx.notify()
3326 }
3327
3328 #[inline]
3329 pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
3330 self.text.offset_utf16_to_offset(offset)
3331 }
3332
3333 #[inline]
3334 pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
3335 self.text.offset_to_offset_utf16(offset)
3336 }
3337
3338 #[inline]
3339 pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
3340 self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
3341 }
3342
3343 #[inline]
3344 pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
3345 self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
3346 }
3347
3348 /// If offset falls on a hidden (folded) line, clamp backward to the end of
3349 /// the fold header line (last visible position before the fold).
3350 fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
3351 let line = self.text.offset_to_point(offset).row;
3352 if self.display_map.is_buffer_line_hidden(line) {
3353 for fold in self.display_map.folded_ranges() {
3354 if line > fold.start_line && line <= fold.end_line {
3355 return self.text.line_end_offset(fold.start_line);
3356 }
3357 }
3358 }
3359 offset
3360 }
3361
3362 /// If offset falls on a hidden (folded) line, clamp forward to the start of
3363 /// the fold end line (first visible position after the fold).
3364 fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
3365 let line = self.text.offset_to_point(offset).row;
3366 if self.display_map.is_buffer_line_hidden(line) {
3367 for fold in self.display_map.folded_ranges() {
3368 if line > fold.start_line && line <= fold.end_line {
3369 return self.text.line_start_offset(fold.end_line);
3370 }
3371 }
3372 }
3373 offset
3374 }
3375
3376 /// Clip a cursor/selection offset without splitting a CRLF newline. This does
3377 /// not alter the rope or its byte/UTF-16 conversion used for exact source APIs.
3378 pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
3379 let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
3380 if offset > 0
3381 && self.text.char_at(offset - 1) == Some('\r')
3382 && self.text.char_at(offset) == Some('\n')
3383 {
3384 if bias == Bias::Left {
3385 offset - 1
3386 } else {
3387 offset + 1
3388 }
3389 } else {
3390 offset
3391 }
3392 }
3393
3394 pub(super) fn previous_boundary(&self, offset: usize) -> usize {
3395 let offset = self.cursor_boundary(offset.saturating_sub(1), Bias::Left);
3396 self.clamp_offset_to_visible_backward(offset)
3397 }
3398
3399 pub(super) fn next_boundary(&self, offset: usize) -> usize {
3400 let offset = self.cursor_boundary(offset.saturating_add(1), Bias::Right);
3401 self.clamp_offset_to_visible_forward(offset)
3402 }
3403
3404 /// Returns the true to let InputElement to render cursor, when Input is focused and current BlinkCursor is visible.
3405 pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
3406 (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
3407 && !self.disabled
3408 && self.blink_cursor.read(cx).visible()
3409 && window.is_window_active()
3410 }
3411
3412 fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3413 self.blink_cursor.update(cx, |cursor, cx| {
3414 cursor.start(cx);
3415 });
3416 cx.emit(InputEvent::Focus);
3417 }
3418
3419 fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3420 if M::is_context_menu_open(self, cx) {
3421 return;
3422 }
3423
3424 M::hide_context_menu(self, cx);
3425 self.undo_manager.break_transaction_coalescing();
3426
3427 // NOTE: Do not cancel select, when blur.
3428 // Because maybe user want to copy the selected text by AppMenuBar (will take focus handle).
3429
3430 M::clear_hover_state(self, cx);
3431 self.diagnostic_popover = None;
3432 M::clear_inline_completion(self, cx);
3433 self.dismiss_touch_selection(cx);
3434 self.blink_cursor.update(cx, |cursor, cx| {
3435 cursor.stop(cx);
3436 });
3437 self.clamp_number_value(window, cx);
3438 cx.emit(InputEvent::Blur);
3439 cx.notify();
3440 }
3441
3442 /// Clamp the number value to the `min`/`max` range, used on blur.
3443 ///
3444 /// Out-of-range values are allowed while typing (e.g. `1` is an
3445 /// intermediate state of `15` when min is 10), and clamped on blur.
3446 fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3447 if !self.is_single_line() {
3448 return;
3449 }
3450 if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
3451 return;
3452 }
3453 if self.number_min.is_none() && self.number_max.is_none() {
3454 return;
3455 }
3456
3457 let Ok(value) = self.unmask_value().parse::<f64>() else {
3458 return;
3459 };
3460
3461 let clamped = match (self.number_min, self.number_max) {
3462 (Some(min), _) if value < min => min,
3463 (_, Some(max)) if value > max => max,
3464 _ => return,
3465 };
3466
3467 // The clamped value must pass the `pattern`/`validate` check,
3468 // otherwise keep the value as is.
3469 let new_text = clamped.to_string();
3470 if !self.is_valid_input(&new_text, cx) {
3471 return;
3472 }
3473
3474 let range = self.range_to_utf16(&(0..self.text.len()));
3475 self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
3476 }
3477
3478 pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
3479 self.blink_cursor.update(cx, |cursor, cx| {
3480 cursor.pause(cx);
3481 });
3482 }
3483
3484 pub(super) fn on_drag_move(
3485 &mut self,
3486 event: &MouseMoveEvent,
3487 window: &mut Window,
3488 cx: &mut Context<Self>,
3489 ) {
3490 if self.text.len() == 0 {
3491 return;
3492 }
3493
3494 if self.last_layout.is_none() {
3495 return;
3496 }
3497
3498 if !self.focus_handle.is_focused(window) {
3499 return;
3500 }
3501
3502 if !self.selecting {
3503 return;
3504 }
3505
3506 self.auto_scroll.last_drag_position = Some(event.position);
3507 let (offset, line_end_affinity, columns_past_line_end) =
3508 self.resolve_mouse_position(event.position);
3509 if let Some(start) = self.column_select_start {
3510 let end = ColumnarPoint::new(offset, columns_past_line_end);
3511 self.build_columnar_selection(start, end, cx);
3512 } else {
3513 self.select_to_with_affinity(offset, line_end_affinity, cx);
3514 }
3515
3516 if !self.is_single_line() {
3517 let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
3518 // Input's ScrollHandle uses negative-y-is-down; negate the positive-towards-bottom delta.
3519 let scroll_delta = delta.map(|d| -d);
3520 self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
3521 let current = state.scroll_handle.offset();
3522 state.update_scroll_offset(Some(point(current.x, current.y + delta)), cx);
3523 if let Some(pos) = state.auto_scroll.last_drag_position {
3524 let (offset, line_end_affinity, columns_past_line_end) =
3525 state.resolve_mouse_position(pos);
3526 if let Some(start) = state.column_select_start {
3527 let end = ColumnarPoint::new(offset, columns_past_line_end);
3528 state.build_columnar_selection(start, end, cx);
3529 } else {
3530 state.select_to_with_affinity(offset, line_end_affinity, cx);
3531 }
3532 }
3533 });
3534 }
3535 }
3536
3537 /// Normalize the inserted text before applying it to the input.
3538 ///
3539 /// For number inputs (with [`MaskPattern::Number`]), this converts
3540 /// full-width number characters into their ASCII equivalents,
3541 /// e.g. `12。5` -> `12.5`.
3542 pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
3543 let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
3544 normalize_number_input(new_text)
3545 } else {
3546 Cow::Borrowed(new_text)
3547 };
3548
3549 if self.is_single_line() && normalized.contains(['\n', '\r']) {
3550 Cow::Owned(normalized.replace(['\n', '\r'], ""))
3551 } else {
3552 normalized
3553 }
3554 }
3555
3556 pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
3557 if new_text.is_empty() {
3558 return true;
3559 }
3560
3561 if let Some(validate) = &self.validate {
3562 if !validate(new_text, cx) {
3563 return false;
3564 }
3565 }
3566
3567 if !self.mask_pattern.is_valid(new_text) {
3568 return false;
3569 }
3570
3571 let Some(pattern) = &self.pattern else {
3572 return true;
3573 };
3574
3575 pattern.is_match(new_text)
3576 }
3577
3578 /// Set the mask pattern for formatting the input text.
3579 ///
3580 /// The pattern can contain:
3581 /// - 9: Any digit or dot
3582 /// - A: Any letter
3583 /// - *: Any character
3584 /// - Other characters will be treated as literal mask characters
3585 ///
3586 /// Example: "(999)999-999" for phone numbers
3587 pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
3588 self.mask_pattern = pattern.into();
3589 self.mask_pattern_set = true;
3590 if let Some(placeholder) = self.mask_pattern.placeholder() {
3591 self.placeholder = placeholder.into();
3592 }
3593 self
3594 }
3595
3596 pub fn set_mask_pattern(
3597 &mut self,
3598 pattern: impl Into<MaskPattern>,
3599 _: &mut Window,
3600 cx: &mut Context<Self>,
3601 ) {
3602 self.mask_pattern = pattern.into();
3603 self.mask_pattern_set = true;
3604 if let Some(placeholder) = self.mask_pattern.placeholder() {
3605 self.placeholder = placeholder.into();
3606 }
3607 cx.notify();
3608 }
3609
3610 /// Apply the default numeric mask unless the caller explicitly selected a mask.
3611 pub fn ensure_number_mask(&mut self) {
3612 if self.mask_pattern_set {
3613 return;
3614 }
3615 self.mask_pattern = MaskPattern::Number {
3616 separator: None,
3617 fraction: None,
3618 };
3619 }
3620
3621 pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
3622 let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
3623 self.input_bounds = new_bounds;
3624
3625 // Update display_map wrap_width if changed.
3626 if let Some(last_layout) = self.last_layout.as_ref() {
3627 if wrap_width_changed {
3628 let wrap_width = if !self.soft_wrap {
3629 // None to disable wrapping (will use Pixels::MAX)
3630 None
3631 } else {
3632 last_layout.wrap_width
3633 };
3634
3635 self.display_map.on_layout_changed(wrap_width, cx);
3636 if self.is_multi_line() {
3637 self.mode
3638 .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
3639 }
3640 cx.notify();
3641 }
3642 }
3643 }
3644
3645 /// Return the active selection's text, borrowed out of the [`Rope`]
3646 /// the state owns.
3647 ///
3648 /// See [`Self::selected_value`] when an owned string is wanted.
3649 pub fn selected_text(&self) -> RopeSlice<'_> {
3650 let range_utf16 = self.range_to_utf16(&self.selected_range());
3651 let range = self.range_from_utf16(&range_utf16);
3652 self.text.slice(range)
3653 }
3654
3655 /// Return the rendered bounds for a UTF-8 byte range in the current input contents.
3656 ///
3657 /// Returns `None` when the requested range is not currently laid out or visible.
3658 pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
3659 let Some(last_layout) = self.last_layout.as_ref() else {
3660 return None;
3661 };
3662
3663 let Some(last_bounds) = self.last_bounds else {
3664 return None;
3665 };
3666
3667 let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
3668 let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
3669
3670 let Some(start_pos) = start_pos else {
3671 return None;
3672 };
3673 let Some(end_pos) = end_pos else {
3674 return None;
3675 };
3676
3677 Some(Bounds::from_corners(
3678 last_bounds.origin + start_pos,
3679 last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
3680 ))
3681 }
3682
3683 /// Replace text in range in silent.
3684 ///
3685 /// This will not trigger any UI interaction, such as auto-completion.
3686 pub(crate) fn replace_text_in_range_silent(
3687 &mut self,
3688 range_utf16: Option<Range<usize>>,
3689 new_text: &str,
3690 window: &mut Window,
3691 cx: &mut Context<Self>,
3692 ) {
3693 self.silent_replace_text = true;
3694 self.replace_text_in_range(range_utf16, new_text, window, cx);
3695 self.silent_replace_text = false;
3696 }
3697
3698 /// Apply a batch of edits as one atomic history transaction.
3699 ///
3700 /// `edits` are `(byte range in the current pre-edit document, replacement)`
3701 /// pairs.
3702 pub(crate) fn replace_text_in_ranges(
3703 &mut self,
3704 edits: &[(Range<usize>, String)],
3705 window: &mut Window,
3706 cx: &mut Context<Self>,
3707 ) {
3708 if !self.is_editable() || edits.is_empty() {
3709 return;
3710 }
3711
3712 // Every edit invalidates provider responses for the previous document,
3713 // including deletion and indentation which do not trigger completion.
3714 M::hide_context_menu(self, cx);
3715 M::clear_inline_completion(self, cx);
3716
3717 // Sort descending by start so applying front-of-vec first edits the
3718 // highest offsets first, leaving lower offsets unchanged.
3719 let mut sorted: Vec<(Range<usize>, &str)> = edits
3720 .iter()
3721 .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
3722 .collect();
3723 sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
3724 if !self.token_spans().is_empty() {
3725 let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
3726 for (range, text) in sorted {
3727 if let Some(last) = merged
3728 .last_mut()
3729 .filter(|last| range.end > last.0.start || range == last.0)
3730 {
3731 last.0.start = range.start.min(last.0.start);
3732 last.0.end = range.end.max(last.0.end);
3733 } else {
3734 merged.push((range, text));
3735 }
3736 }
3737 sorted = merged;
3738 }
3739
3740 #[cfg(debug_assertions)]
3741 for pair in sorted.windows(2) {
3742 debug_assert!(
3743 pair[1].0.end <= pair[0].0.start,
3744 "replace_text_in_ranges requires disjoint ranges"
3745 );
3746 }
3747
3748 // Wrap multiple edits in one explicit transaction so they undo as a
3749 // unit. A single edit records directly, which keeps it eligible for
3750 // the undo manager's typing coalescing.
3751 let requested_intent = self.undo_manager.take_pending_intent();
3752 let selection_before = *self.active_selection();
3753 let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3754 // Snapshot the cursors before applying, so undo can restore them. A
3755 // delete has already expanded them over the text it removes, so they
3756 // collapse back to where the user left them.
3757 let selections_before: Vec<CursorSelection> = self
3758 .selections
3759 .iter()
3760 .map(|selection| {
3761 Self::collapse_for_intent(
3762 requested_intent.unwrap_or(EditIntent::Atomic),
3763 *selection,
3764 &(selection.start..selection.end),
3765 )
3766 })
3767 .collect();
3768 let group = sorted.len() > 1;
3769 if group {
3770 self.undo_manager.begin_transaction();
3771 }
3772
3773 let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
3774 let mut recorded = false;
3775 // Several edits reach the highlighter as one batch, so it reparses
3776 // once for the change instead of once per edit.
3777 let mut highlighter_edits = Vec::new();
3778 for (range, new_text) in &sorted {
3779 let old_text = self.text.clone();
3780 self.mode.adjust_auto_closed_pair(range, new_text.len());
3781 self.text.replace(range.clone(), new_text);
3782
3783 M::adjust_annotations(self, range, new_text.len());
3784 recorded |= self.push_history(
3785 &old_text,
3786 range,
3787 new_text,
3788 requested_intent,
3789 selection_before,
3790 None,
3791 );
3792
3793 // Incremental, single-range updates must run per edit.
3794 self.display_map
3795 .adjust_folds_for_edit(&old_text, range, new_text);
3796 self.display_map
3797 .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
3798
3799 if group {
3800 if self.is_code_editor() {
3801 let edit =
3802 super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
3803 highlighter_edits.push((edit, self.text.clone()));
3804 }
3805 } else {
3806 self.mode.update_highlighter(
3807 super::mode::HighlighterUpdate {
3808 selected_range: range,
3809 old_text: &old_text,
3810 new_text: &self.text,
3811 change_text: new_text,
3812 force: true,
3813 },
3814 window,
3815 cx,
3816 );
3817
3818 self.update_fold_candidates_incremental(range, new_text);
3819 }
3820 }
3821
3822 if group {
3823 self.mode
3824 .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
3825
3826 // Fold candidates are read from the reparsed document, so each
3827 // edit is located where it ended up once every edit was applied.
3828 // `sorted` runs from the highest offset down.
3829 let mut shift = 0isize;
3830 for (range, new_text) in sorted.iter().rev() {
3831 let start = (range.start as isize + shift) as usize;
3832 self.update_fold_candidates_incremental(&(start..start), new_text);
3833 shift += new_text.len() as isize - range.len() as isize;
3834 }
3835
3836 self.undo_manager.commit_transaction();
3837 }
3838
3839 // One observable update per batch instead of one per edit.
3840 if let Some(diagnostics) = self.mode.diagnostics_mut() {
3841 diagnostics.reset(&self.text)
3842 }
3843 M::refresh_language_features(self, window, cx);
3844 self.update_search(cx);
3845
3846 // Compute the resulting cursors.
3847 // One collapsed cursor per edit, at the end of its inserted text.
3848 let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
3849 ascending.sort_by_key(|edit| edit.0.start);
3850 let text_len = self.text.len();
3851 let mut delta: isize = 0;
3852 let mut edit_results = Vec::with_capacity(ascending.len());
3853 for (range, new_text) in &ascending {
3854 let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
3855 edit_results.push((range.clone(), offset));
3856 delta += new_text.len() as isize - (range.end as isize - range.start as isize);
3857 }
3858
3859 let mut used = vec![false; edit_results.len()];
3860 let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
3861 for selection in original_selections {
3862 if let Ok(index) = edit_results
3863 .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
3864 (range.start, range.end)
3865 })
3866 && !used[index]
3867 {
3868 let offset = edit_results[index].1;
3869 used[index] = true;
3870 let mut selection = selection;
3871 selection.place_at(offset, None);
3872 new_selections.push(selection);
3873 }
3874 }
3875 for (index, (_, offset)) in edit_results.into_iter().enumerate() {
3876 if !used[index] {
3877 new_selections.push(CursorSelection::new(
3878 self.selections.generate_id(),
3879 offset,
3880 offset,
3881 ));
3882 }
3883 }
3884 self.selections.replace_all(new_selections);
3885 self.selections.merge_overlapping();
3886
3887 // Record the cursor snapshots for undo/redo restore.
3888 let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
3889 if recorded {
3890 self.undo_manager.record_auto_closed_pairs(
3891 auto_closed_pairs_before,
3892 self.mode.auto_closed_pairs().clone(),
3893 );
3894 self.undo_manager
3895 .record_selections(selections_before, selections_after);
3896 }
3897
3898 self.ime_marked_range.take();
3899 self.update_preferred_column();
3900 self.dismiss_touch_selection(cx);
3901 if self.is_multi_line() {
3902 self.mode
3903 .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
3904 }
3905 if self.emit_events {
3906 cx.emit(InputEvent::Change);
3907 }
3908 cx.notify();
3909 }
3910
3911 /// Update fold candidates from tree-sitter syntax tree (full extraction).
3912 /// Used only on initial load or language changes.
3913 fn update_fold_candidates(&mut self) {
3914 if !self.mode.is_folding() {
3915 return;
3916 }
3917
3918 let Some(highlighter_rc) = self.mode.highlighter() else {
3919 return;
3920 };
3921
3922 let highlighter = highlighter_rc.borrow();
3923 let Some(highlighter) = highlighter.as_ref() else {
3924 return;
3925 };
3926
3927 let fold_ranges = highlighter.fold_ranges(&self.text);
3928 self.display_map.set_fold_candidates(fold_ranges);
3929 }
3930
3931 /// Incrementally update fold candidates after a text edit.
3932 /// Only traverses the edited region of the syntax tree instead of the full tree.
3933 fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
3934 if !self.mode.is_folding() {
3935 return;
3936 }
3937
3938 let Some(highlighter_rc) = self.mode.highlighter() else {
3939 return;
3940 };
3941
3942 let highlighter = highlighter_rc.borrow();
3943 let Some(highlighter) = highlighter.as_ref() else {
3944 return;
3945 };
3946
3947 // The new byte range in the updated text after the edit
3948 let new_end = edit_range.start + new_text.len();
3949 self.display_map.update_fold_candidates_for_edit(
3950 |range, text| highlighter.fold_ranges_for_edit(range, text),
3951 edit_range.start..new_end,
3952 &self.text,
3953 );
3954 }
3955}
3956
3957impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
3958 fn text_for_range(
3959 &mut self,
3960 range_utf16: Range<usize>,
3961 adjusted_range: &mut Option<Range<usize>>,
3962 _window: &mut Window,
3963 _cx: &mut Context<Self>,
3964 ) -> Option<String> {
3965 let range = self.range_from_utf16(&range_utf16);
3966 adjusted_range.replace(self.range_to_utf16(&range));
3967 Some(self.text.slice(range).to_string())
3968 }
3969
3970 fn selected_text_range(
3971 &mut self,
3972 _ignore_disabled_input: bool,
3973 _window: &mut Window,
3974 _cx: &mut Context<Self>,
3975 ) -> Option<UTF16Selection> {
3976 Some(UTF16Selection {
3977 range: self.range_to_utf16(&self.selected_range()),
3978 reversed: self.active_selection().reversed,
3979 })
3980 }
3981
3982 fn marked_text_range(
3983 &self,
3984 _window: &mut Window,
3985 _cx: &mut Context<Self>,
3986 ) -> Option<Range<usize>> {
3987 self.ime_marked_range
3988 .map(|range| self.range_to_utf16(&range.into()))
3989 }
3990
3991 fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
3992 self.ime_marked_range = None;
3993 self.undo_manager.commit_transaction();
3994 }
3995
3996 /// Replace text in range.
3997 ///
3998 /// - If the new text is invalid, it will not be replaced.
3999 /// - If `range_utf16` is not provided, the current selected range will be used.
4000 fn replace_text_in_range(
4001 &mut self,
4002 range_utf16: Option<Range<usize>>,
4003 new_text: &str,
4004 window: &mut Window,
4005 cx: &mut Context<Self>,
4006 ) {
4007 let requested_intent = self.undo_manager.take_pending_intent();
4008 if !self.is_editable() {
4009 return;
4010 }
4011 let selection_before = *self.active_selection();
4012 // Committing a composition ends the transaction it opened, whether or
4013 // not the platform follows up with `unmark_text`.
4014 let ends_composition = self.ime_marked_range.is_some();
4015
4016 self.pause_blink_cursor(cx);
4017
4018 // NOTE: The normalization keeps the UTF-16 length, but may change the
4019 // UTF-8 byte length, so all the byte-offset calculations below must
4020 // use the normalized text.
4021 let new_text = if self.replaying_history {
4022 Cow::Borrowed(new_text)
4023 } else {
4024 self.normalize_input(new_text)
4025 };
4026 let new_text: &str = &new_text;
4027
4028 let range = range_utf16
4029 .as_ref()
4030 .map(|range_utf16| self.range_from_utf16(range_utf16))
4031 .or(self.ime_marked_range.map(|range| {
4032 let range = self.range_to_utf16(&(range.start..range.end));
4033 self.range_from_utf16(&range)
4034 }))
4035 .unwrap_or(self.selected_range());
4036 let range = self.normalize_token_range(range);
4037
4038 // Skip-over as a pure cursor move: a typed closer that already follows
4039 // the cursor moves past it without touching text or history, so Undo
4040 // never exposes a transient duplicate. Only for interactive single
4041 // keystrokes (current selection, no IME mark, not silent replays).
4042 // `take_pending_intent` above already consumed any request.
4043 if range.is_empty()
4044 && range.start == self.cursor()
4045 && self.ime_marked_range.is_none()
4046 && !self.silent_replace_text
4047 && self.is_code_editor()
4048 && self.selections.is_single()
4049 && self.active_selection().is_empty()
4050 {
4051 if let Some(target) = self.skip_over_target(new_text) {
4052 self.set_cursor_to(target);
4053 self.update_preferred_column();
4054 cx.notify();
4055 return;
4056 }
4057 }
4058
4059 if self.is_multi_line() {
4060 let multi_cursor = range_utf16.is_none()
4061 && self.ime_marked_range.is_none()
4062 && !self.selections.is_single();
4063 if multi_cursor {
4064 self.selections.merge_overlapping();
4065 let mut edits: Vec<(Range<usize>, String)> = self
4066 .selections
4067 .iter()
4068 .map(|sel| (sel.start..sel.end, new_text.to_string()))
4069 .collect();
4070 edits.sort_by_key(|(range, _)| range.start);
4071 // One keystroke across several cursors is one batch, committed
4072 // with the intent of the keystroke so a run of them coalesces
4073 // into one undo just like single-cursor typing.
4074 let intent =
4075 requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
4076 self.undo_manager.begin_transaction_with(intent);
4077 self.undo_manager.set_pending_intent(intent);
4078 self.replace_text_in_ranges(&edits, window, cx);
4079 self.undo_manager.commit_transaction();
4080 } else {
4081 if range_utf16.is_some() {
4082 self.selections.remove_all_but_active();
4083 }
4084 if let Some(intent) = requested_intent {
4085 self.undo_manager.set_pending_intent(intent);
4086 }
4087 if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
4088 // One edit keeps the pair atomic even at undo coalescing limits.
4089 let replacement = format!("{new_text}{closer}");
4090 self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
4091 let cursor = range.start + new_text.len();
4092 self.mode.track_auto_closed_pair(
4093 cursor - open_len..cursor,
4094 cursor..cursor + closer.len(),
4095 );
4096 self.undo_manager
4097 .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
4098 self.set_cursor_to(cursor);
4099 self.update_preferred_column();
4100 self.undo_manager.record_selections(
4101 vec![selection_before],
4102 self.selections.iter().copied().collect(),
4103 );
4104 } else {
4105 self.replace_text_in_ranges(
4106 &[(range.clone(), new_text.to_string())],
4107 window,
4108 cx,
4109 );
4110 }
4111 }
4112 if ends_composition {
4113 self.undo_manager.commit_transaction();
4114 }
4115
4116 if !self.silent_replace_text {
4117 M::on_text_typed(self, &range, new_text, window, cx);
4118 }
4119 return;
4120 }
4121
4122 // Single-line path
4123 let old_text = self.text.clone();
4124 self.mode.adjust_auto_closed_pair(&range, new_text.len());
4125 self.text.replace(range.clone(), new_text);
4126
4127 let mut new_offset = (range.start + new_text.len()).min(self.text.len());
4128
4129 // True if the mask has changed the text, e.g. regrouping the
4130 // separators or completing a leading dot.
4131 let mut mask_changed = false;
4132
4133 if self.is_single_line() {
4134 let pending_text = self.text.to_string();
4135 // Check if the new text is valid.
4136 //
4137 // Only reject the edit if the old text was valid, to avoid
4138 // trapping a pre-existing invalid text (e.g. a `default_value`
4139 // that does not conform), the user can still edit to fix it.
4140 if !self.replaying_history
4141 && !self.validated_token_edit
4142 && !self.is_valid_input(&pending_text, cx)
4143 && self.is_valid_input(&old_text.to_string(), cx)
4144 {
4145 self.text = old_text;
4146 return;
4147 }
4148
4149 if !self.replaying_history && !self.mask_pattern.is_none() {
4150 let mask_text = self.mask_pattern.mask(&pending_text);
4151 mask_changed = mask_text.as_str() != pending_text;
4152 self.text = Rope::from(mask_text.as_str());
4153 let new_text_len =
4154 (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
4155 new_offset = (range.start + new_text_len).min(mask_text.len());
4156 }
4157 }
4158
4159 if mask_changed {
4160 // Masking rewrites the whole document, so ranges recorded against
4161 // the old text no longer point at anything.
4162 M::reset_annotations(self);
4163 } else {
4164 M::adjust_annotations(self, &range, new_text.len());
4165 }
4166 if mask_changed {
4167 // A segment-based history entry no longer matches the masked
4168 // document, record a whole-document change instead, so that
4169 // undo/redo can restore the text exactly.
4170 self.push_history(
4171 &old_text,
4172 &(0..old_text.len()),
4173 &self.text.to_string(),
4174 Some(EditIntent::Atomic),
4175 selection_before,
4176 Some((new_offset..new_offset).into()),
4177 );
4178 } else {
4179 self.push_history(
4180 &old_text,
4181 &range,
4182 &new_text,
4183 requested_intent,
4184 selection_before,
4185 None,
4186 );
4187 }
4188 if let Some(diagnostics) = self.mode.diagnostics_mut() {
4189 diagnostics.reset(&self.text)
4190 }
4191 // Adjust folds before updating wrap map: remove overlapping folds and shift others
4192 self.display_map
4193 .adjust_folds_for_edit(&old_text, &range, new_text);
4194 self.display_map
4195 .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4196
4197 self.mode.update_highlighter::<M>(
4198 super::mode::HighlighterUpdate {
4199 selected_range: &range,
4200 old_text: &old_text,
4201 new_text: &self.text,
4202 change_text: &new_text,
4203 force: true,
4204 },
4205 window,
4206 cx,
4207 );
4208
4209 self.update_fold_candidates_incremental(&range, new_text);
4210 M::refresh_language_features(self, window, cx);
4211 self.set_cursor_to(new_offset);
4212 self.ime_marked_range.take();
4213 // A commit ends the IME composition: macOS delivers `insertText:` for
4214 // the confirmed candidate without a following `unmarkText`, so close
4215 // the transaction here. Leaving it open would keep merging every later
4216 // edit into the same change, which then carries the text and selection
4217 // of the first composition.
4218 if ends_composition {
4219 self.undo_manager
4220 .record_selections(vec![selection_before], vec![*self.active_selection()]);
4221 self.undo_manager.commit_transaction();
4222 }
4223 self.update_preferred_column();
4224 self.update_search(cx);
4225 self.dismiss_touch_selection(cx);
4226 if self.is_multi_line() {
4227 self.mode
4228 .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
4229 }
4230 if !self.silent_replace_text {
4231 M::on_text_typed(self, &range, &new_text, window, cx);
4232 }
4233 if self.emit_events {
4234 cx.emit(InputEvent::Change);
4235 }
4236 cx.notify();
4237 }
4238
4239 /// Mark text is the IME temporary insert on typing.
4240 fn replace_and_mark_text_in_range(
4241 &mut self,
4242 range_utf16: Option<Range<usize>>,
4243 new_text: &str,
4244 new_selected_range_utf16: Option<Range<usize>>,
4245 window: &mut Window,
4246 cx: &mut Context<Self>,
4247 ) {
4248 let requested_intent = self.undo_manager.take_pending_intent();
4249 if !self.is_editable() {
4250 return;
4251 }
4252 let selection_before = *self.active_selection();
4253
4254 let starts_composition = self.ime_marked_range.is_none();
4255 if starts_composition {
4256 // Even a canceled preedit separates the typing gestures on either
4257 // side; its no-op transaction must not reconnect those gestures.
4258 self.undo_manager.break_transaction_coalescing();
4259 self.undo_manager.begin_transaction();
4260 }
4261
4262 // Collapse any extra cursors so we never leave stale secondary cursors behind.
4263 self.selections.remove_all_but_active();
4264
4265 M::reset_language_features(self);
4266
4267 // See the same NOTE in `replace_text_in_range`.
4268 let new_text = if self.replaying_history {
4269 Cow::Borrowed(new_text)
4270 } else {
4271 self.normalize_input(new_text)
4272 };
4273 let new_text: &str = &new_text;
4274
4275 let range = range_utf16
4276 .as_ref()
4277 .map(|range_utf16| self.range_from_utf16(range_utf16))
4278 .or(self.ime_marked_range.map(|range| {
4279 let range = self.range_to_utf16(&(range.start..range.end));
4280 self.range_from_utf16(&range)
4281 }))
4282 .unwrap_or(self.selected_range());
4283 let range = self.normalize_token_range(range);
4284
4285 let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4286 let old_text = self.text.clone();
4287 self.mode.adjust_auto_closed_pair(&range, new_text.len());
4288 self.text.replace(range.clone(), new_text);
4289
4290 if self.is_single_line() {
4291 let pending_text = self.text.to_string();
4292 // See the same NOTE in `replace_text_in_range`.
4293 if !self.replaying_history
4294 && !self.validated_token_edit
4295 && !self.is_valid_input(&pending_text, cx)
4296 && self.is_valid_input(&old_text.to_string(), cx)
4297 {
4298 self.text = old_text;
4299 if starts_composition {
4300 self.undo_manager.commit_transaction();
4301 }
4302 return;
4303 }
4304 }
4305
4306 M::adjust_annotations(self, &range, new_text.len());
4307 if let Some(diagnostics) = self.mode.diagnostics_mut() {
4308 diagnostics.reset(&self.text)
4309 }
4310 // Adjust folds before updating wrap map: remove overlapping folds and shift others
4311 self.display_map
4312 .adjust_folds_for_edit(&old_text, &range, new_text);
4313 self.display_map
4314 .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
4315
4316 self.mode.update_highlighter::<M>(
4317 super::mode::HighlighterUpdate {
4318 selected_range: &range,
4319 old_text: &old_text,
4320 new_text: &self.text,
4321 change_text: &new_text,
4322 force: true,
4323 },
4324 window,
4325 cx,
4326 );
4327
4328 self.update_fold_candidates_incremental(&range, new_text);
4329 M::refresh_language_features(self, window, cx);
4330 if new_text.is_empty() {
4331 // Cancel selection, when cancel IME input.
4332 self.set_cursor_to(range.start);
4333 self.ime_marked_range = None;
4334 } else {
4335 self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
4336 let new_range = new_selected_range_utf16
4337 .as_ref()
4338 .map(|range_utf16| {
4339 let new_text = Rope::from(new_text);
4340 range.start + new_text.offset_utf16_to_offset(range_utf16.start)
4341 ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
4342 })
4343 .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
4344 self.set_selection(new_range.start, new_range.end);
4345 }
4346 if self.is_multi_line() {
4347 self.mode
4348 .update_auto_grow(&self.display_map, self.line_height().unwrap_or(px(1.)));
4349 }
4350 if self.push_history(
4351 &old_text,
4352 &range,
4353 new_text,
4354 requested_intent,
4355 selection_before,
4356 Some(*self.active_selection()),
4357 ) {
4358 self.undo_manager
4359 .record_selections(vec![selection_before], vec![*self.active_selection()]);
4360 self.undo_manager.record_auto_closed_pairs(
4361 auto_closed_pairs_before,
4362 self.mode.auto_closed_pairs().clone(),
4363 );
4364 }
4365 if new_text.is_empty() {
4366 self.undo_manager.commit_transaction();
4367 }
4368 cx.notify();
4369 }
4370
4371 /// Used to position IME candidates.
4372 fn bounds_for_range(
4373 &mut self,
4374 range_utf16: Range<usize>,
4375 bounds: Bounds<Pixels>,
4376 _window: &mut Window,
4377 _cx: &mut Context<Self>,
4378 ) -> Option<Bounds<Pixels>> {
4379 let last_layout = self.last_layout.as_ref()?;
4380 let line_height = last_layout.line_height;
4381 let line_number_width = last_layout.line_number_width;
4382 let range = self.range_from_utf16(&range_utf16);
4383
4384 let mut start_origin = None;
4385 let mut start_height = line_height;
4386 let mut end_origin = None;
4387 let line_number_origin = point(line_number_width, px(0.));
4388 let mut y_offset = last_layout.visible_top;
4389
4390 for (vi, line) in last_layout.lines.iter().enumerate() {
4391 if start_origin.is_some() && end_origin.is_some() {
4392 break;
4393 }
4394
4395 let index_offset = last_layout.visible_line_byte_offsets[vi];
4396
4397 if start_origin.is_none() {
4398 if let Some(p) = line.position_for_index(
4399 range.start.saturating_sub(index_offset),
4400 last_layout,
4401 false,
4402 ) {
4403 start_origin = Some(p + point(px(0.), y_offset));
4404 start_height = line
4405 .row_at_y(p.y, line_height)
4406 .map_or(line_height, |ix| line.row_height(ix, line_height));
4407 }
4408 }
4409
4410 if end_origin.is_none() {
4411 if let Some(p) = line.position_for_index(
4412 range.end.saturating_sub(index_offset),
4413 last_layout,
4414 false,
4415 ) {
4416 end_origin = Some(p + point(px(0.), y_offset));
4417 }
4418 }
4419
4420 y_offset += line.size(line_height).height;
4421 }
4422
4423 let start_origin = start_origin.or_else(|| {
4424 let offset = self.last_cursor.or(Some(self.cursor()))?;
4425 let (_, _, origin) = self.line_and_position_for_offset(offset);
4426 origin.map(|origin| origin - line_number_origin)
4427 })?;
4428 let mut end_origin = end_origin.unwrap_or(start_origin);
4429 // Ensure at same line.
4430 end_origin.y = start_origin.y;
4431
4432 Some(Bounds::from_corners(
4433 bounds.origin + line_number_origin + start_origin,
4434 // + row height for show IME panel under the cursor line.
4435 bounds.origin + line_number_origin + point(end_origin.x, end_origin.y + start_height),
4436 ))
4437 }
4438
4439 fn character_index_for_point(
4440 &mut self,
4441 point: gpui::Point<Pixels>,
4442 _window: &mut Window,
4443 _cx: &mut Context<Self>,
4444 ) -> Option<usize> {
4445 let last_layout = self.last_layout.as_ref()?;
4446 let line_point = self.last_bounds?.localize(&point)?;
4447
4448 for (vi, line) in last_layout.lines.iter().enumerate() {
4449 let offset = last_layout.visible_line_byte_offsets[vi];
4450 if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
4451 return Some(self.offset_to_utf16(offset + utf8_index));
4452 }
4453 }
4454
4455 None
4456 }
4457}
4458
4459impl<M: InputModeKind> Focusable for InputBaseState<M> {
4460 fn focus_handle(&self, _cx: &App) -> FocusHandle {
4461 self.focus_handle.clone()
4462 }
4463}
4464
4465impl<M: InputModeKind> Render for InputBaseState<M> {
4466 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
4467 // Before anything reads it: the element resolves this style during
4468 // layout and paint, and both happen after this call in the same frame.
4469 self.editor_style = self
4470 .projected_editor_style
4471 .resolved(&crate::Theme::global(cx).tokens);
4472 let entity = cx.entity();
4473 if self._pending_update {
4474 self.mode.update_highlighter::<M>(
4475 super::mode::HighlighterUpdate {
4476 selected_range: &(0..0),
4477 old_text: &self.text,
4478 new_text: &self.text,
4479 change_text: "",
4480 force: false,
4481 },
4482 window,
4483 cx,
4484 );
4485
4486 self.update_fold_candidates();
4487 M::refresh_language_features(self, window, cx);
4488 self._pending_update = false;
4489 }
4490
4491 let element = div()
4492 .id("input-state")
4493 .key_context(CONTEXT)
4494 .track_focus(&self.focus_handle)
4495 .when(self.is_editable(), |this| {
4496 this.on_action(window.listener_for(&entity, InputBaseState::backspace))
4497 .on_action(window.listener_for(&entity, InputBaseState::delete))
4498 .on_action(
4499 window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
4500 )
4501 .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
4502 .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
4503 .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
4504 .on_action(window.listener_for(&entity, InputBaseState::enter))
4505 .on_action(window.listener_for(&entity, InputBaseState::escape))
4506 .on_action(window.listener_for(&entity, InputBaseState::paste))
4507 .on_action(window.listener_for(&entity, InputBaseState::cut))
4508 .on_action(window.listener_for(&entity, InputBaseState::undo))
4509 .on_action(window.listener_for(&entity, InputBaseState::redo))
4510 .when(self.is_multi_line(), |this| {
4511 this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
4512 .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
4513 .on_action(window.listener_for(&entity, InputBaseState::indent_block))
4514 .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
4515 })
4516 })
4517 .on_action(window.listener_for(&entity, InputBaseState::left))
4518 .on_action(window.listener_for(&entity, InputBaseState::right))
4519 .on_action(window.listener_for(&entity, InputBaseState::select_left))
4520 .on_action(window.listener_for(&entity, InputBaseState::select_right))
4521 .when(self.is_multi_line(), |this| {
4522 this.on_action(window.listener_for(&entity, InputBaseState::up))
4523 .on_action(window.listener_for(&entity, InputBaseState::down))
4524 .on_action(window.listener_for(&entity, InputBaseState::select_up))
4525 .on_action(window.listener_for(&entity, InputBaseState::select_down))
4526 .on_action(window.listener_for(&entity, InputBaseState::page_up))
4527 .on_action(window.listener_for(&entity, InputBaseState::page_down))
4528 .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
4529 .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
4530 })
4531 .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
4532 .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
4533 .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
4534 .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
4535 .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
4536 .on_action(window.listener_for(&entity, InputBaseState::home))
4537 .on_action(window.listener_for(&entity, InputBaseState::end))
4538 .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
4539 .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
4540 .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
4541 .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
4542 .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
4543 .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
4544 .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
4545 .on_action({
4546 let entity = entity.clone();
4547 move |_: &ActivateToken, window, cx| {
4548 let state = entity.read(cx);
4549 let activation = state
4550 .token_spans()
4551 .iter()
4552 .find(|span| span.range() == state.selected_range())
4553 .and_then(|span| {
4554 state.range_to_bounds(&span.range()).and_then(|bounds| {
4555 state.token_activation(
4556 span.range().start,
4557 bounds,
4558 gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
4559 bounds,
4560 ..Default::default()
4561 }),
4562 )
4563 })
4564 });
4565 if let Some((listener, event)) = activation {
4566 listener(&event, window, cx);
4567 }
4568 }
4569 })
4570 .on_action(window.listener_for(&entity, InputBaseState::copy))
4571 .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
4572 .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
4573 .on_mouse_down(
4574 MouseButton::Left,
4575 window.listener_for(&entity, InputBaseState::on_mouse_down),
4576 )
4577 .on_mouse_down(
4578 MouseButton::Right,
4579 window.listener_for(&entity, InputBaseState::on_mouse_down),
4580 )
4581 .on_mouse_up(
4582 MouseButton::Left,
4583 window.listener_for(&entity, InputBaseState::on_mouse_up),
4584 )
4585 .on_mouse_up(
4586 MouseButton::Right,
4587 window.listener_for(&entity, InputBaseState::on_mouse_up),
4588 )
4589 .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
4590 .on_scroll_wheel(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
4591 .when(self.is_multi_line() && !self.disabled, |this| {
4592 this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
4593 })
4594 .when(!self.disabled, |this| {
4595 if self.is_multi_line() && window.modifiers().alt {
4596 this.cursor_crosshair()
4597 } else {
4598 this.cursor_text()
4599 }
4600 })
4601 .flex_1()
4602 // A single line fills the frame and sits at its vertical center,
4603 // so the frame needs no layout of its own to hold it. It is never
4604 // shorter than its line, though: this root clips (overflow-x
4605 // hidden clips both axes), and a frame whose padding leaves less
4606 // than a line, like Component's Input, would cut off descenders.
4607 .map(|this| {
4608 if self.is_multi_line() {
4609 this.h_full()
4610 } else {
4611 this.min_h_full().flex().items_center()
4612 }
4613 })
4614 .flex_grow_1()
4615 .overflow_x_hidden()
4616 .when(self.is_multi_line(), |this| {
4617 this.pt(self.editor_paddings.top)
4618 .pr(self.editor_paddings.right)
4619 .pb(self.editor_paddings.bottom)
4620 .pl(self.editor_paddings.left)
4621 })
4622 .child(TextElement::new(entity.clone()).placeholder(self.placeholder.clone()))
4623 .when(self.shows_scrollbar(), |this| {
4624 this.child(EditorScrollbar::new(entity.clone()))
4625 });
4626
4627 // Actions only one mode handles are registered by that mode, where
4628 // `Self` is concrete enough to name its own entity type.
4629 M::register_actions(element, &entity, window)
4630 }
4631}
4632
4633#[cfg(test)]
4634mod tests {
4635 use super::*;
4636
4637 #[gpui::test]
4638 fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) {
4639 use crate::input::{CompletionProvider, EditorState};
4640 use gpui::Task;
4641 use lsp_types::{CompletionContext, CompletionResponse};
4642 use std::cell::RefCell;
4643
4644 #[derive(Default)]
4645 struct Provider {
4646 starts: RefCell<Vec<usize>>,
4647 queries: RefCell<Vec<(usize, String)>>,
4648 }
4649
4650 impl CompletionProvider for Provider {
4651 fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
4652 self.starts.borrow_mut().push(offset);
4653 true
4654 }
4655
4656 fn completions(
4657 &self,
4658 _: &Rope,
4659 offset: usize,
4660 trigger: CompletionContext,
4661 _: &mut Window,
4662 _: &mut App,
4663 ) -> Task<anyhow::Result<CompletionResponse>> {
4664 self.queries
4665 .borrow_mut()
4666 .push((offset, trigger.trigger_character.unwrap()));
4667 Task::ready(Ok(CompletionResponse::Array(vec![])))
4668 }
4669 }
4670
4671 cx.update(crate::init);
4672 let mut editor = None;
4673 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
4674 editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
4675 gpui::EmptyView
4676 });
4677 let editor = editor.unwrap();
4678 let provider = Rc::new(Provider::default());
4679 window
4680 .update(cx, |_, window, cx| {
4681 editor.update(cx, |state, cx| {
4682 state.extras.lsp.completion_provider = Some(provider.clone());
4683 state
4684 .extras
4685 .context_menu_content
4686 .completion
4687 .trigger_start_offset = Some(0);
4688 state.extras.context_menu_content.completion.query = "aa".into();
4689 state.set_cursor_to(1);
4690 state.add_cursor_at(0, cx);
4691
4692 state.replace_text_in_range(None, "中", window, cx);
4693
4694 assert_eq!(state.value(), "中a中a");
4695 assert_eq!(provider.starts.borrow().as_slice(), &[4]);
4696 assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
4697 });
4698 })
4699 .unwrap();
4700 }
4701
4702 #[gpui::test]
4703 fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
4704 use crate::input::{InlineToken, InlineTokenPresentation};
4705 let width = Rc::new(Cell::new(4000.));
4706 let render_width = width.clone();
4707 let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
4708 view.window_handle
4709 .update(cx, |_, window, cx| {
4710 view.input.update(cx, |state, cx| {
4711 state
4712 .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
4713 .unwrap();
4714 state
4715 .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
4716 .unwrap();
4717 state.set_token_presentation(
4718 InlineTokenPresentation::default()
4719 .token(move |_, _, _| div().w(px(render_width.get()))),
4720 );
4721 });
4722 })
4723 .unwrap();
4724 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4725 visual.update(|window, cx| window.draw(cx).clear(cx));
4726 view.input.read_with(&visual, |state, _| {
4727 assert_eq!(state.display_map.wrap_row_count(), 2);
4728 let first = state.range_to_bounds(&(0..2)).unwrap();
4729 let second = state.range_to_bounds(&(2..4)).unwrap();
4730 assert!(second.origin.y > first.origin.y);
4731 assert_eq!(
4732 state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
4733 2
4734 );
4735 });
4736 width.set(100.);
4737 view.input.update(&mut visual, |_, cx| cx.notify());
4738 visual.update(|window, cx| window.draw(cx).clear(cx));
4739 view.input.read_with(&visual, |state, _| {
4740 assert_eq!(state.display_map.wrap_row_count(), 1)
4741 });
4742 }
4743
4744 fn build_block_view(
4745 cx: &mut TestAppContext,
4746 value: &'static str,
4747 token_range: Range<usize>,
4748 ) -> (InputView<TextareaMode>, VisualTestContext) {
4749 use crate::input::{InlineToken, InlineTokenPresentation};
4750 let view =
4751 InputView::build_textarea(cx, move |state| state.auto_grow(1, 40).default_value(value));
4752 view.window_handle
4753 .update(cx, |_, window, cx| {
4754 view.input.update(cx, |state, cx| {
4755 state.set_token_presentation(
4756 InlineTokenPresentation::default()
4757 .token(|_, _, _| div().w(px(200.)).h(px(120.))),
4758 );
4759 state
4760 .replace_range_with_token(
4761 token_range,
4762 InlineToken::new("img", "[img]").block(),
4763 window,
4764 cx,
4765 )
4766 .unwrap();
4767 });
4768 })
4769 .unwrap();
4770 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
4771 visual.update(|window, cx| window.draw(cx).clear(cx));
4772 visual.update(|window, cx| window.draw(cx).clear(cx));
4773 (view, visual)
4774 }
4775
4776 #[gpui::test]
4777 fn test_block_token_row_height_feeds_row_top_and_auto_grow(cx: &mut TestAppContext) {
4778 let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);
4779 view.input.read_with(&visual, |state, _| {
4780 let line_height = state.line_height().unwrap();
4781 assert_eq!(
4782 state.display_map.line(0).unwrap().wrapped_lines.as_slice(),
4783 [0..2, 2..7, 7..9]
4784 );
4785 assert_eq!(
4786 state.display_map.row_top(2, line_height),
4787 line_height + px(120.)
4788 );
4789 assert_eq!(
4790 state.display_map.content_height(line_height),
4791 line_height * 2. + px(120.)
4792 );
4793 assert_eq!(state.display_map.row_at_y(px(119.), line_height), 1);
4794 assert_eq!(state.display_map.row_at_y(px(1000.), line_height), 2);
4795 assert!(state.mode.rows() > state.display_map.wrap_row_count());
4796 assert_eq!(
4797 state.mode.rows(),
4798 state.display_map.content_rows(line_height)
4799 );
4800 });
4801 }
4802
4803 struct GrowingRoot(Entity<InputBaseState<TextareaMode>>);
4804
4805 impl Render for GrowingRoot {
4806 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4807 div()
4808 .flex()
4809 .items_end()
4810 .child(div().w(px(600.)).child(self.0.clone()))
4811 }
4812 }
4813
4814 fn build_growing_view(
4815 cx: &mut TestAppContext,
4816 max_rows: usize,
4817 ) -> (Entity<InputBaseState<TextareaMode>>, VisualTestContext) {
4818 use crate::input::InlineTokenPresentation;
4819 let mut input = None;
4820 let window = cx.update(|cx| {
4821 cx.open_window(Default::default(), |window, cx| {
4822 cx.set_global(Theme::default());
4823 super::super::init(cx);
4824 let state = cx.new(|cx| {
4825 let mut state =
4826 crate::input::TextareaState::new(window, cx).auto_grow(1, max_rows);
4827 state.set_token_presentation(
4828 InlineTokenPresentation::default()
4829 .token(|_, _, _| div().w(px(200.)).h(px(120.))),
4830 );
4831 state
4832 });
4833 input = Some(state.clone());
4834 cx.new(|_| GrowingRoot(state))
4835 })
4836 .unwrap()
4837 });
4838 let mut visual = VisualTestContext::from_window(window.into(), cx);
4839 visual.update(|window, cx| window.draw(cx).clear(cx));
4840 (input.unwrap(), visual)
4841 }
4842
4843 fn draw_twice(visual: &mut VisualTestContext) {
4844 visual.update(|window, cx| window.draw(cx).clear(cx));
4845 visual.update(|window, cx| window.draw(cx).clear(cx));
4846 }
4847
4848 fn load_block_content(
4849 input: &Entity<InputBaseState<TextareaMode>>,
4850 visual: &mut VisualTestContext,
4851 before: &str,
4852 after: &str,
4853 ) {
4854 use crate::input::InlineToken;
4855 let before = before.to_owned();
4856 let after = after.to_owned();
4857 visual.update(|window, cx| {
4858 input.update(cx, |state, cx| {
4859 let text = format!("{before}[img]{after}");
4860 let range = before.len()..before.len() + 5;
4861 let content = crate::input::InputContent::new(text.clone())
4862 .with_token(range, InlineToken::new("img", "[img]").block())
4863 .unwrap();
4864 state.set_value(content, window, cx);
4865 state.set_selected_range(text.len()..text.len(), cx);
4866 })
4867 });
4868 draw_twice(visual);
4869 }
4870
4871 fn assert_cursor_row_in_view(
4872 input: &Entity<InputBaseState<TextareaMode>>,
4873 visual: &VisualTestContext,
4874 ) {
4875 input.read_with(visual, |state, _| {
4876 let line_height = state.line_height().unwrap();
4877 let content = state.display_map.content_height(line_height);
4878 let viewport = state.input_bounds.size.height;
4879 assert!(
4880 content > viewport,
4881 "content {content:?} viewport {viewport:?}"
4882 );
4883 assert_eq!(state.scroll_handle.offset().y, viewport - content);
4884 });
4885 }
4886
4887 #[gpui::test]
4888 fn test_typing_after_a_block_token_scrolls_the_cursor_row_into_view(cx: &mut TestAppContext) {
4889 let (input, mut visual) = build_growing_view(cx, 4);
4890 load_block_content(
4891 &input,
4892 &mut visual,
4893 "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4894 "",
4895 );
4896 for character in ["x", "y"] {
4897 visual.update(|window, cx| {
4898 input.update(cx, |state, cx| state.insert(character, window, cx))
4899 });
4900 }
4901 draw_twice(&mut visual);
4902 assert_cursor_row_in_view(&input, &visual);
4903 }
4904
4905 #[gpui::test]
4906 fn test_loading_content_with_a_block_token_scrolls_the_cursor_row_into_view(
4907 cx: &mut TestAppContext,
4908 ) {
4909 let (input, mut visual) = build_growing_view(cx, 4);
4910 load_block_content(
4911 &input,
4912 &mut visual,
4913 "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4914 "cd",
4915 );
4916 assert_cursor_row_in_view(&input, &visual);
4917 }
4918
4919 #[gpui::test]
4920 fn test_block_tokens_add_their_rows_on_top_of_max_rows_up_to_twice_of_it(
4921 cx: &mut TestAppContext,
4922 ) {
4923 let (input, mut visual) = build_growing_view(cx, 4);
4924 load_block_content(&input, &mut visual, "ab", "cd");
4925 let rows_with_one_image = input.read_with(&visual, |state, _| state.mode.rows());
4926 assert!(rows_with_one_image > 4, "{rows_with_one_image}");
4927 input.read_with(&visual, |state, _| {
4928 let line_height = state.line_height().unwrap();
4929 assert_eq!(
4930 state.input_bounds.size.height,
4931 line_height * rows_with_one_image as f32
4932 );
4933 assert!(
4934 state.display_map.content_height(line_height) <= state.input_bounds.size.height
4935 );
4936 });
4937 load_block_content(
4938 &input,
4939 &mut visual,
4940 "ab\ncd\nef\ngh\nij\nkl\nmn\nop\nqr\n",
4941 "cd",
4942 );
4943 assert_eq!(input.read_with(&visual, |state, _| state.mode.rows()), 8);
4944 }
4945
4946 #[gpui::test]
4947 fn test_block_token_caret_spans_the_row(cx: &mut TestAppContext) {
4948 let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
4949 view.input.read_with(&visual, |state, _| {
4950 let line_height = state.line_height().unwrap();
4951 let layout = state.last_layout.as_ref().unwrap();
4952 let line = &layout.lines[0];
4953 let before = line.position_for_index(2, layout, false).unwrap();
4954 let after = line.position_for_index(7, layout, true).unwrap();
4955 assert_eq!((before.x, after.x), (px(0.), px(200.)));
4956 assert_eq!(before.y, line.row_top(1, line_height));
4957 assert_eq!(after.y, before.y);
4958 });
4959 view.input
4960 .update(&mut visual, |state, cx| state.set_selected_range(2..2, cx));
4961 visual.update(|window, cx| window.draw(cx).clear(cx));
4962 let before = view
4963 .input
4964 .read_with(&visual, |state, _| state.cursor_layout().unwrap().0);
4965 assert_eq!(before.size.height, px(120.));
4966 view.input.update(&mut visual, |state, cx| {
4967 state.set_selected_range(7..7, cx);
4968 state.cursor_line_end_affinity = true;
4969 });
4970 visual.update(|window, cx| window.draw(cx).clear(cx));
4971 let after = view
4972 .input
4973 .read_with(&visual, |state, _| state.cursor_layout().unwrap().0);
4974 assert_eq!(after.size.height, px(120.));
4975 assert_eq!(after.origin.y, before.origin.y);
4976 assert_eq!(after.origin.x - before.origin.x, px(200.));
4977 }
4978
4979 #[gpui::test]
4980 fn test_block_token_click_beside_the_image_lands_on_its_edge(cx: &mut TestAppContext) {
4981 let (view, visual) = build_block_view(cx, "ab[img]cd", 2..7);
4982 view.input.read_with(&visual, |state, _| {
4983 let line_height = state.line_height().unwrap();
4984 let bounds = state.last_bounds.unwrap();
4985 let layout = state.last_layout.as_ref().unwrap();
4986 let row_top = layout.visible_top + layout.lines[0].row_top(1, line_height);
4987 let at =
4988 |x: f32| bounds.origin + point(layout.line_number_width + px(x), row_top + px(60.));
4989 assert_eq!(state.resolve_mouse_position(at(500.)).0, 7);
4990 assert_eq!(state.resolve_mouse_position(at(150.)).0, 7);
4991 assert_eq!(state.resolve_mouse_position(at(10.)).0, 2);
4992 });
4993 }
4994
4995 #[gpui::test]
4996 fn test_block_token_vertical_movement_visits_its_row(cx: &mut TestAppContext) {
4997 let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
4998 let row = |view: &InputView<TextareaMode>, visual: &VisualTestContext| {
4999 view.input.read_with(visual, |state, _| {
5000 state
5001 .display_map
5002 .offset_to_wrap_display_point_with_affinity(
5003 state.cursor(),
5004 state.cursor_line_end_affinity,
5005 )
5006 .row
5007 })
5008 };
5009 view.input
5010 .update(&mut visual, |state, _| state.set_cursor_to(0));
5011 for expected_row in [1, 2] {
5012 visual.update(|window, cx| {
5013 view.input
5014 .update(cx, |state, cx| state.down(&MoveDown, window, cx))
5015 });
5016 assert_eq!(row(&view, &visual), expected_row);
5017 }
5018 for expected_row in [1, 0] {
5019 visual.update(|window, cx| {
5020 view.input
5021 .update(cx, |state, cx| state.up(&MoveUp, window, cx))
5022 });
5023 assert_eq!(row(&view, &visual), expected_row);
5024 }
5025 }
5026
5027 #[gpui::test]
5028 fn test_block_token_scroll_to_brings_its_rows_into_view(cx: &mut TestAppContext) {
5029 let value: &'static str =
5030 Box::leak(format!("{}[img]cd", "x\n".repeat(60)).into_boxed_str());
5031 let token_start = 120;
5032 let (view, mut visual) = build_block_view(cx, value, token_start..token_start + 5);
5033 for (offset, row) in [(token_start, 60), (token_start + 5, 61)] {
5034 view.input.update(&mut visual, |state, cx| {
5035 state.scroll_to(offset, None, cx);
5036 let line_height = state.line_height().unwrap();
5037 let scrolled = -state.deferred_scroll_offset.unwrap().y;
5038 let top = state.display_map.row_top(row, line_height);
5039 let height = state.display_map.row_height(row, line_height);
5040 assert!(top >= scrolled, "row {row} top is above the viewport");
5041 assert!(
5042 top + height <= scrolled + state.input_bounds.size.height,
5043 "row {row} bottom is below the viewport"
5044 );
5045 });
5046 }
5047 }
5048
5049 #[gpui::test]
5050 fn test_block_token_undo_restores_uniform_rows(cx: &mut TestAppContext) {
5051 let (view, mut visual) = build_block_view(cx, "ab[img]cd", 2..7);
5052 visual.update(|window, cx| {
5053 view.input
5054 .update(cx, |state, cx| state.undo(&Undo, window, cx))
5055 });
5056 visual.update(|window, cx| window.draw(cx).clear(cx));
5057 view.input.read_with(&visual, |state, _| {
5058 let line_height = state.line_height().unwrap();
5059 assert!(state.tokens().is_empty());
5060 assert!(state.display_map.line(0).unwrap().blocks.is_empty());
5061 assert_eq!(
5062 state.display_map.content_height(line_height),
5063 line_height * state.display_map.wrap_row_count() as f32
5064 );
5065 assert_eq!(state.mode.rows(), state.display_map.wrap_row_count());
5066 });
5067 }
5068
5069 #[gpui::test]
5070 fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
5071 use crate::input::{InlineToken, InlineTokenPresentation};
5072 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5073 let target = view.input.clone();
5074 view.window_handle
5075 .update(cx, |_, window, cx| {
5076 view.input.update(cx, |state, cx| {
5077 state
5078 .replace_range_with_token(
5079 7..13,
5080 InlineToken::new("a", "@alice"),
5081 window,
5082 cx,
5083 )
5084 .unwrap();
5085 state.set_token_presentation(
5086 InlineTokenPresentation::default()
5087 .token(|_, _, _| div().w(px(100.)).h(px(20.)))
5088 .on_token_click(move |_, window, cx| {
5089 target.update(cx, |state, cx| {
5090 state.set_value("activated", window, cx)
5091 })
5092 }),
5093 );
5094 state.focus(window, cx);
5095 state.set_selected_range(7..13, cx);
5096 });
5097 })
5098 .unwrap();
5099 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5100 visual.update(|window, cx| window.draw(cx).clear(cx));
5101 visual.update(|window, cx| {
5102 let state = view.input.read(cx);
5103 let bounds = state.range_to_bounds(&(7..13)).unwrap();
5104 assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
5105 let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
5106 let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
5107 assert_eq!((left, right), (7, 13));
5108 window.dispatch_action(Box::new(ActivateToken), cx);
5109 });
5110 visual.run_until_parked();
5111 view.input.read_with(&visual, |state, _| {
5112 assert_eq!(state.value().as_ref(), "activated")
5113 });
5114 }
5115
5116 #[gpui::test]
5117 fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
5118 use crate::input::InlineToken;
5119 cx.update(crate::init);
5120 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
5121 view.window_handle
5122 .update(cx, |_, window, cx| {
5123 view.input.update(cx, |state, cx| {
5124 state
5125 .replace_range_with_token(
5126 7..13,
5127 InlineToken::new("a", "@alice"),
5128 window,
5129 cx,
5130 )
5131 .unwrap();
5132 state.set_selected_range(0..0, cx);
5133 });
5134 })
5135 .unwrap();
5136 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
5137 visual.update(|window, cx| window.draw(cx).clear(cx));
5138 let bounds = view
5139 .input
5140 .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
5141 visual.simulate_click(bounds.center(), gpui::Modifiers::default());
5142 visual.run_until_parked();
5143 view.input.read_with(&visual, |state, _| {
5144 assert_eq!(state.selected_range(), 7..13, "a click selects the token");
5145 });
5146 }
5147
5148 #[gpui::test]
5149 fn test_inline_token_h
5150… afgekapt