BlueGit

ict rusty-teams

Files

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

state.rs

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