1use gpui::TextAlign;
6use gpui::{
7 Action, App, AppContext, Bounds, ClipboardItem, Context, Edges, Entity, EntityInputHandler,
8 EventEmitter, FocusHandle, Focusable, Hsla, InteractiveElement as _, IntoElement, KeyBinding,
9 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Point,
10 Render, ScrollEvent, ScrollHandle, SharedString, StatefulInteractiveElement as _, Styled as _,
11 Subscription, UTF16Selection, WeakFocusHandle, Window, actions, div, point,
12 prelude::FluentBuilder as _, px,
13};
14use gpui::{Autocapitalize, TextInputAction, TextInputConfiguration};
15use ropey::{Rope, RopeSlice};
16use serde::Deserialize;
17use std::borrow::Cow;
18use std::cell::Cell;
19use std::ops::Range;
20use std::rc::Rc;
21use sum_tree::Bias;
22use unicode_segmentation::*;
23
24use super::{
25 DiagnosticSet, DisplayMap, FoldPlaceholderRenderer, GutterColumn, InputContextMenuCapabilities,
26 InputEditorStyle, InputHighlighterFactory, MASK_CHAR, MaskPattern, NativeMenu, NumberStep,
27 WrappingIndent,
28 blink_cursor::BlinkCursor,
29 change::Change,
30 cursor::{CursorSelection, Selections},
31 element::{
32 EditorScrollbar, EditorScrollbarSnapshot, LongestLineKey, OverviewRulerRows, TextElement,
33 clamp_horizontal_scroll_offset, line_number_digits_width, line_number_len,
34 },
35 kind::InputModeKind,
36 mask_pattern::normalize_number_input,
37 mode::LayoutMode,
38 undo_manager::{EditIntent, UndoManager},
39};
40use crate::ScrollbarPlacement;
41use crate::Side;
42use crate::actions::{SelectDown, SelectLeft, SelectRight, SelectUp};
43use crate::input::blink_cursor::CURSOR_WIDTH;
44use crate::input::movement::MoveDirection;
45use crate::input::rope_ext::{next_grapheme_boundary, previous_grapheme_boundary};
46use crate::input::{
47 EditorLineNumberRenderer, InputEdit, InputExtras as _, Position, RopeExt as _,
48 element::RIGHT_MARGIN,
49 layout::{InputHit, InputHitArea, LastLayout},
50};
51use crate::overscroll::Overscroll;
52use crate::{AutoScroll, StepAction, TestSupportExt as _};
53
54pub(super) const EDITOR_ELEMENT_ID: &str = "input-state";
55
56pub(crate) enum ScrollPadding {
58 Minimal,
59 SurroundingLines,
60}
61
62#[derive(Action, Clone, PartialEq, Eq, Deserialize)]
63#[action(namespace = input, no_json)]
64pub struct Enter {
65 pub secondary: bool,
67 pub shift: bool,
69}
70
71impl Enter {
72 pub fn is_primary(action: &dyn Action) -> bool {
75 action.partial_eq(&Enter {
76 secondary: false,
77 shift: false,
78 }) || action.partial_eq(&Enter {
79 secondary: false,
80 shift: true,
81 })
82 }
83}
84
85actions!(
86 input,
87 [
88 ActivateToken,
89 Backspace,
90 Delete,
91 DeleteToBeginningOfLine,
92 DeleteToEndOfLine,
93 DeleteToPreviousWordStart,
94 DeleteToNextWordEnd,
95 Indent,
96 Outdent,
97 IndentInline,
98 OutdentInline,
99 MoveUp,
100 MoveDown,
101 MoveLeft,
102 MoveRight,
103 MoveHome,
104 MoveEnd,
105 MovePageUp,
106 MovePageDown,
107 AddCursorAbove,
108 AddCursorBelow,
109 SelectAll,
110 SelectToStartOfLine,
111 SelectToEndOfLine,
112 SelectToStart,
113 SelectToEnd,
114 SelectToPreviousWordStart,
115 SelectToNextWordEnd,
116 ShowCharacterPalette,
117 Copy,
118 Cut,
119 Paste,
120 Undo,
121 Redo,
122 MoveToStartOfLine,
123 MoveToEndOfLine,
124 MoveToStart,
125 MoveToEnd,
126 MoveToPreviousWord,
127 MoveToNextWord,
128 Escape,
129 ToggleCodeActions,
130 ShowCompletions,
131 ShowHover,
132 Search,
133 Replace,
134 GoToDefinition,
135 ]
136);
137
138#[derive(Clone)]
144pub enum InputEvent {
145 Change,
146 PressEnter { secondary: bool, shift: bool },
147 Focus,
148 Blur,
149}
150
151#[derive(Clone)]
157pub struct InputEditsEvent {
158 edits: Vec<(InputEdit, Rope)>,
159}
160
161impl InputEditsEvent {
162 pub fn edits(&self) -> &[(InputEdit, Rope)] {
164 &self.edits
165 }
166}
167
168pub(super) const CONTEXT: &str = "Input";
169
170pub(crate) fn init(cx: &mut App) {
171 cx.bind_keys([
172 KeyBinding::new("backspace", Backspace, Some(CONTEXT)),
173 KeyBinding::new("shift-backspace", Backspace, Some(CONTEXT)),
174 #[cfg(target_os = "macos")]
175 KeyBinding::new("ctrl-backspace", Backspace, Some(CONTEXT)),
176 KeyBinding::new("delete", Delete, Some(CONTEXT)),
177 KeyBinding::new("shift-delete", Delete, Some(CONTEXT)),
178 #[cfg(target_os = "macos")]
179 KeyBinding::new("cmd-backspace", DeleteToBeginningOfLine, Some(CONTEXT)),
180 #[cfg(target_os = "macos")]
181 KeyBinding::new("cmd-delete", DeleteToEndOfLine, Some(CONTEXT)),
182 #[cfg(target_os = "macos")]
183 KeyBinding::new("alt-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
184 #[cfg(not(target_os = "macos"))]
185 KeyBinding::new("ctrl-backspace", DeleteToPreviousWordStart, Some(CONTEXT)),
186 #[cfg(target_os = "macos")]
187 KeyBinding::new("alt-delete", DeleteToNextWordEnd, Some(CONTEXT)),
188 #[cfg(not(target_os = "macos"))]
189 KeyBinding::new("ctrl-delete", DeleteToNextWordEnd, Some(CONTEXT)),
190 KeyBinding::new(
191 "enter",
192 Enter {
193 secondary: false,
194 shift: false,
195 },
196 Some(CONTEXT),
197 ),
198 KeyBinding::new(
199 "shift-enter",
200 Enter {
201 secondary: false,
202 shift: true,
203 },
204 Some(CONTEXT),
205 ),
206 KeyBinding::new(
207 if cx.platform_info().is_mac() {
208 "cmd-enter"
209 } else {
210 "ctrl-enter"
211 },
212 Enter {
213 secondary: true,
214 shift: false,
215 },
216 Some(CONTEXT),
217 ),
218 KeyBinding::new("escape", Escape, Some(CONTEXT)),
219 KeyBinding::new("up", MoveUp, Some(CONTEXT)),
220 KeyBinding::new("down", MoveDown, Some(CONTEXT)),
221 KeyBinding::new("left", MoveLeft, Some(CONTEXT)),
222 KeyBinding::new("right", MoveRight, Some(CONTEXT)),
223 KeyBinding::new("pageup", MovePageUp, Some(CONTEXT)),
224 KeyBinding::new("pagedown", MovePageDown, Some(CONTEXT)),
225 KeyBinding::new("tab", IndentInline, Some(CONTEXT)),
226 KeyBinding::new("shift-tab", OutdentInline, Some(CONTEXT)),
227 #[cfg(target_os = "macos")]
228 KeyBinding::new("cmd-]", Indent, Some(CONTEXT)),
229 #[cfg(not(target_os = "macos"))]
230 KeyBinding::new("ctrl-]", Indent, Some(CONTEXT)),
231 #[cfg(target_os = "macos")]
232 KeyBinding::new("cmd-[", Outdent, Some(CONTEXT)),
233 #[cfg(not(target_os = "macos"))]
234 KeyBinding::new("ctrl-[", Outdent, Some(CONTEXT)),
235 KeyBinding::new("shift-left", SelectLeft, Some(CONTEXT)),
236 KeyBinding::new("shift-right", SelectRight, Some(CONTEXT)),
237 KeyBinding::new("shift-up", SelectUp, Some(CONTEXT)),
238 KeyBinding::new("shift-down", SelectDown, Some(CONTEXT)),
239 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
240 KeyBinding::new("shift-alt-left", SelectLeft, Some(CONTEXT)),
241 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
242 KeyBinding::new("shift-alt-right", SelectRight, Some(CONTEXT)),
243 #[cfg(target_os = "macos")]
245 KeyBinding::new("cmd-alt-up", AddCursorAbove, Some(CONTEXT)),
246 #[cfg(target_os = "macos")]
247 KeyBinding::new("cmd-alt-down", AddCursorBelow, Some(CONTEXT)),
248 #[cfg(target_os = "windows")]
249 KeyBinding::new("ctrl-alt-up", AddCursorAbove, Some(CONTEXT)),
250 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
251 KeyBinding::new("shift-alt-up", AddCursorAbove, Some(CONTEXT)),
252 #[cfg(target_os = "windows")]
253 KeyBinding::new("ctrl-alt-down", AddCursorBelow, Some(CONTEXT)),
254 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
255 KeyBinding::new("shift-alt-down", AddCursorBelow, Some(CONTEXT)),
256 KeyBinding::new("home", MoveHome, Some(CONTEXT)),
257 KeyBinding::new("end", MoveEnd, Some(CONTEXT)),
258 #[cfg(not(target_os = "macos"))]
259 KeyBinding::new("ctrl-home", MoveToStart, Some(CONTEXT)),
260 #[cfg(not(target_os = "macos"))]
261 KeyBinding::new("ctrl-end", MoveToEnd, Some(CONTEXT)),
262 #[cfg(not(target_os = "macos"))]
263 KeyBinding::new("ctrl-shift-home", SelectToStart, Some(CONTEXT)),
264 #[cfg(not(target_os = "macos"))]
265 KeyBinding::new("ctrl-shift-end", SelectToEnd, Some(CONTEXT)),
266 KeyBinding::new("shift-home", SelectToStartOfLine, Some(CONTEXT)),
267 KeyBinding::new("shift-end", SelectToEndOfLine, Some(CONTEXT)),
268 #[cfg(target_os = "macos")]
269 KeyBinding::new("ctrl-shift-a", SelectToStartOfLine, Some(CONTEXT)),
270 #[cfg(target_os = "macos")]
271 KeyBinding::new("ctrl-shift-e", SelectToEndOfLine, Some(CONTEXT)),
272 #[cfg(target_os = "macos")]
273 KeyBinding::new("shift-cmd-left", SelectToStartOfLine, Some(CONTEXT)),
274 #[cfg(target_os = "macos")]
275 KeyBinding::new("shift-cmd-right", SelectToEndOfLine, Some(CONTEXT)),
276 #[cfg(any(target_os = "macos", target_os = "linux"))]
277 KeyBinding::new("alt-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
278 #[cfg(not(target_os = "macos"))]
279 KeyBinding::new("ctrl-shift-left", SelectToPreviousWordStart, Some(CONTEXT)),
280 #[cfg(any(target_os = "macos", target_os = "linux"))]
281 KeyBinding::new("alt-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
282 #[cfg(not(target_os = "macos"))]
283 KeyBinding::new("ctrl-shift-right", SelectToNextWordEnd, Some(CONTEXT)),
284 #[cfg(target_os = "macos")]
285 KeyBinding::new("ctrl-cmd-space", ShowCharacterPalette, Some(CONTEXT)),
286 #[cfg(target_os = "macos")]
287 KeyBinding::new("cmd-a", SelectAll, Some(CONTEXT)),
288 #[cfg(not(target_os = "macos"))]
289 KeyBinding::new("ctrl-a", SelectAll, Some(CONTEXT)),
290 #[cfg(target_os = "macos")]
291 KeyBinding::new("cmd-c", Copy, Some(CONTEXT)),
292 #[cfg(not(target_os = "macos"))]
293 KeyBinding::new("ctrl-c", Copy, Some(CONTEXT)),
294 #[cfg(target_os = "macos")]
295 KeyBinding::new("cmd-x", Cut, Some(CONTEXT)),
296 #[cfg(not(target_os = "macos"))]
297 KeyBinding::new("ctrl-x", Cut, Some(CONTEXT)),
298 #[cfg(target_os = "macos")]
299 KeyBinding::new("cmd-v", Paste, Some(CONTEXT)),
300 #[cfg(not(target_os = "macos"))]
301 KeyBinding::new("ctrl-v", Paste, Some(CONTEXT)),
302 #[cfg(target_os = "macos")]
303 KeyBinding::new("ctrl-a", MoveHome, Some(CONTEXT)),
304 #[cfg(target_os = "macos")]
305 KeyBinding::new("cmd-left", MoveHome, Some(CONTEXT)),
306 #[cfg(target_os = "macos")]
307 KeyBinding::new("ctrl-e", MoveEnd, Some(CONTEXT)),
308 #[cfg(target_os = "macos")]
309 KeyBinding::new("cmd-right", MoveEnd, Some(CONTEXT)),
310 #[cfg(target_os = "macos")]
311 KeyBinding::new("cmd-z", Undo, Some(CONTEXT)),
312 #[cfg(target_os = "macos")]
313 KeyBinding::new("cmd-shift-z", Redo, Some(CONTEXT)),
314 #[cfg(target_os = "macos")]
315 KeyBinding::new("cmd-up", MoveToStart, Some(CONTEXT)),
316 #[cfg(target_os = "macos")]
317 KeyBinding::new("cmd-down", MoveToEnd, Some(CONTEXT)),
318 #[cfg(target_os = "macos")]
319 KeyBinding::new("alt-left", MoveToPreviousWord, Some(CONTEXT)),
320 #[cfg(target_os = "macos")]
321 KeyBinding::new("alt-right", MoveToNextWord, Some(CONTEXT)),
322 #[cfg(not(target_os = "macos"))]
323 KeyBinding::new("ctrl-left", MoveToPreviousWord, Some(CONTEXT)),
324 #[cfg(not(target_os = "macos"))]
325 KeyBinding::new("ctrl-right", MoveToNextWord, Some(CONTEXT)),
326 #[cfg(target_os = "macos")]
327 KeyBinding::new("cmd-shift-up", SelectToStart, Some(CONTEXT)),
328 #[cfg(target_os = "macos")]
329 KeyBinding::new("cmd-shift-down", SelectToEnd, Some(CONTEXT)),
330 #[cfg(not(target_os = "macos"))]
331 KeyBinding::new("ctrl-z", Undo, Some(CONTEXT)),
332 #[cfg(not(target_os = "macos"))]
333 KeyBinding::new("ctrl-y", Redo, Some(CONTEXT)),
334 #[cfg(target_os = "macos")]
335 KeyBinding::new("cmd-.", ToggleCodeActions, Some(CONTEXT)),
336 #[cfg(not(target_os = "macos"))]
337 KeyBinding::new("ctrl-.", ToggleCodeActions, Some(CONTEXT)),
338 #[cfg(target_os = "macos")]
339 KeyBinding::new("cmd-f", Search, Some(CONTEXT)),
340 #[cfg(not(target_os = "macos"))]
341 KeyBinding::new("ctrl-f", Search, Some(CONTEXT)),
342 #[cfg(target_os = "macos")]
343 KeyBinding::new("cmd-shift-f", Replace, Some(CONTEXT)),
344 #[cfg(not(target_os = "macos"))]
345 KeyBinding::new("ctrl-h", Replace, Some(CONTEXT)),
346 ]);
347}
348
349#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub(super) struct ColumnarPoint {
357 offset: usize,
358 columns_past_line_end: usize,
359}
360
361impl ColumnarPoint {
362 pub(super) fn new(offset: usize, columns_past_line_end: usize) -> Self {
363 Self {
364 offset,
365 columns_past_line_end,
366 }
367 }
368}
369
370#[derive(Debug, PartialEq)]
374struct PasteTarget {
375 document_revision: u64,
376 selections: Vec<CursorSelection>,
377}
378
379#[derive(Clone, Copy, Debug)]
384#[doc(hidden)]
385pub struct PrepaintCaretGeometry {
386 cursor_bounds: Bounds<Pixels>,
387 line_height: Pixels,
388 input_bounds: Bounds<Pixels>,
389 scroll_offset: Point<Pixels>,
390 pub(super) scroll_y_f64: f64,
391 pub(super) resize_reveal_owned: bool,
393}
394
395impl PrepaintCaretGeometry {
396 pub(super) fn new(
397 cursor_bounds: Bounds<Pixels>,
398 line_height: Pixels,
399 input_bounds: Bounds<Pixels>,
400 scroll_offset: Point<Pixels>,
401 ) -> Self {
402 Self {
403 cursor_bounds,
404 line_height,
405 input_bounds,
406 scroll_offset,
407 scroll_y_f64: f64::from(f32::from(scroll_offset.y)),
408 resize_reveal_owned: false,
409 }
410 }
411
412 pub fn cursor_bounds(&self) -> Bounds<Pixels> {
414 self.cursor_bounds
415 }
416
417 pub fn line_height(&self) -> Pixels {
419 self.line_height
420 }
421
422 pub fn input_bounds(&self) -> Bounds<Pixels> {
424 self.input_bounds
425 }
426
427 pub fn scroll_offset(&self) -> Point<Pixels> {
430 self.scroll_offset
431 }
432}
433
434pub struct InputBaseState<M: InputModeKind> {
445 pub(crate) extras: M::Extras,
447 pub(super) focus_handle: FocusHandle,
448 selection_focus: Option<WeakFocusHandle>,
449 pub(super) mode: LayoutMode,
450 pub(super) text: Rope,
451 pub(super) display_map: DisplayMap,
452 pub(super) spacers_asked: Option<usize>,
455 pub(super) undo_manager: UndoManager,
456 pub(super) inline_tokens: Option<Box<super::inline_tokens::InlineTokenStore>>,
457 pub(super) pending_token: Option<super::InlineToken>,
458 pub(super) replaying_history: bool,
459 pub(super) validated_token_edit: bool,
460 pub(super) document_revision: u64,
461 pub(super) font_spans_key: Option<(u64, u64, bool)>,
464 pub(super) token_presentation: super::InlineTokenPresentation,
465 pub(super) token_layout_cache: Option<Box<super::token_presentation::TokenLayoutCache>>,
466 pub(super) token_bounds: std::collections::HashMap<usize, Bounds<Pixels>>,
469 pub(super) hovered_token: Option<super::token_presentation::HoverSnapshot>,
474 pub(super) pending_token_hover_exits: Vec<super::token_presentation::HoverSnapshot>,
475 pub(super) pressed_token: Option<(usize, u64, Point<Pixels>)>,
478 pub(super) search_session: super::SearchSession,
479 pub(super) search_activation_revision: u64,
482 pub(super) searchable: bool,
483 pub(super) replaceable: bool,
484 pub(super) soft_wrap: bool,
485 pub(super) wrapping_indent: WrappingIndent,
486 pub(super) scroll_beyond_last_line: Option<usize>,
487 pub(super) cursor_surrounding_lines: Option<usize>,
488 pub(super) blink_cursor: Entity<BlinkCursor>,
489 pub(super) loading: bool,
490 pub(super) selections: Selections,
494 pub(super) selected_word_range: Option<CursorSelection>,
496 pub(super) ime_marked_range: Option<CursorSelection>,
498 ime_original_text: Option<Rope>,
500 pub(super) last_layout: Option<LastLayout>,
501 pub(crate) prepaint_caret_geometry: Option<PrepaintCaretGeometry>,
506 pub(super) last_cursor: Option<usize>,
507 pub(super) ime_anchor: Option<(Point<Pixels>, Option<Bounds<Pixels>>)>,
509 pub(super) input_bounds: Bounds<Pixels>,
511 pub(super) last_bounds: Option<Bounds<Pixels>>,
513 pub(super) revealed_viewport: Option<Bounds<Pixels>>,
516 pub(super) last_gutter_bounds: Option<Bounds<Pixels>>,
518 pub(super) last_selected_range: Option<CursorSelection>,
519 pub(super) last_input_edits: Vec<(InputEdit, Rope)>,
521 pub(super) selecting: bool,
522 pub(super) column_select_start: Option<ColumnarPoint>,
524 pub(super) touch_selection: super::touch::TouchSelection,
526 pub(crate) disabled: bool,
527 pub(crate) readonly: bool,
528 pub(crate) text_align: TextAlign,
529 pub(super) masked: bool,
530 pub(super) clean_on_escape: bool,
531 pub(super) submit_on_enter: bool,
532 pub(super) input_action: Option<TextInputAction>,
534 pub(super) autocorrect: Option<bool>,
535 pub(super) autocapitalize: Option<Autocapitalize>,
536 pub(super) show_whitespaces: bool,
537 pub(crate) cursor_line_end_affinity: bool,
539 pub(super) pattern: Option<regex::Regex>,
540 pub(super) validate: Option<Box<dyn Fn(&str, &mut App) -> bool + 'static>>,
541 pub(crate) number_step: Option<NumberStep>,
544 pub(crate) number_min: Option<f64>,
546 pub(crate) number_max: Option<f64>,
548 pub(crate) scroll_handle: ScrollHandle,
549 scroll_bounce: bool,
551 pub(super) overscroll: Overscroll,
553 pub(crate) deferred_scroll_offset: Option<Point<Pixels>>,
555 pub(crate) scroll_y_f64: f64,
557 pub(crate) deferred_scroll_y_f64: Option<f64>,
558 pub(crate) last_synced_handle_y: Cell<Pixels>,
559 pub(crate) scroll_height_f64: f64,
561 pub(crate) scroll_size: gpui::Size<Pixels>,
563 pub(super) editor_scrollbar_snapshot: Cell<Option<EditorScrollbarSnapshot>>,
564 pub(super) overview_ruler_rows: std::cell::RefCell<OverviewRulerRows>,
566 pub(super) scrollbar_placement: ScrollbarPlacement,
567 pub(super) gutter_side: Side,
568 pub(super) gutter_order: [GutterColumn; 4],
569 pub(super) longest_line_width: Cell<Option<(LongestLineKey, Pixels)>>,
571 pub(super) editor_paddings: Edges<Pixels>,
572 pub(super) editor_style: InputEditorStyle,
577 projected_editor_style: InputEditorStyle,
582 pub(super) fold_placeholder_renderer: Option<FoldPlaceholderRenderer>,
583 pub(super) fold_background: Option<Hsla>,
584 pub(super) accessibility: Option<InputAccessibility>,
585 pub(super) scrollbar_renderer: Option<crate::input::EditorScrollbarRenderer>,
588
589 pub(crate) mask_pattern: MaskPattern,
591 pub(super) mask_pattern_set: bool,
595 pub(super) placeholder: SharedString,
596
597 pub(super) diagnostic_popover: Option<Rc<crate::input::DiagnosticEntry>>,
599
600 pub(super) spelling: Option<super::spelling::Spelling>,
602
603 context_menu_handler: Option<
604 Rc<dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App)>,
605 >,
606 pending_context_menu: Option<(Point<Pixels>, usize, Option<InputHit>)>,
607 context_menu_offset: Option<usize>,
608 context_menu_hit: Option<InputHit>,
609
610 pub(super) enable_context_menu: bool,
613
614 pub(super) completion_inserting: bool,
616 pub(super) overlay_action_handler: Option<
617 Rc<
618 dyn Fn(
619 super::InputOverlayKind,
620 Box<dyn Action>,
621 &mut Window,
622 &mut Context<InputBaseState<M>>,
623 ) -> bool,
624 >,
625 >,
626
627 _pending_update: bool,
631 pub(super) silent_replace_text: bool,
633 pub(super) emit_events: bool,
635
636 _subscriptions: Vec<Subscription>,
637
638 pub(super) auto_scroll: AutoScroll,
639}
640
641#[derive(Clone, Debug)]
648pub struct InputAccessibility {
649 role: Option<gpui::Role>,
650 label: Option<SharedString>,
651 placeholder: Option<SharedString>,
652 accessibility_id: Option<SharedString>,
653 value_exposed: bool,
654}
655
656impl InputAccessibility {
657 pub fn new(role: Option<gpui::Role>) -> Self {
658 Self {
659 role,
660 label: None,
661 placeholder: None,
662 accessibility_id: None,
663 value_exposed: true,
664 }
665 }
666
667 pub fn with_label(mut self, label: Option<SharedString>) -> Self {
668 self.label = label;
669 self
670 }
671
672 pub fn with_placeholder(mut self, placeholder: Option<SharedString>) -> Self {
673 self.placeholder = placeholder;
674 self
675 }
676
677 pub fn with_accessibility_id(mut self, id: Option<SharedString>) -> Self {
678 self.accessibility_id = id;
679 self
680 }
681
682 pub fn with_value_exposed(mut self, exposed: bool) -> Self {
684 self.value_exposed = exposed;
685 self
686 }
687
688 pub fn role(&self) -> Option<gpui::Role> {
689 self.role
690 }
691
692 pub fn label(&self) -> Option<&SharedString> {
693 self.label.as_ref()
694 }
695
696 pub fn placeholder(&self) -> Option<&SharedString> {
697 self.placeholder.as_ref()
698 }
699
700 pub fn accessibility_id(&self) -> Option<&SharedString> {
701 self.accessibility_id.as_ref()
702 }
703
704 pub fn value_exposed(&self) -> bool {
705 self.value_exposed
706 }
707}
708
709#[derive(Clone)]
714pub struct InputPresentation {
715 focus_handle: FocusHandle,
716 disabled: bool,
717 readonly: bool,
718 loading: bool,
719 masked: bool,
720 multi_line: bool,
721 code_editor: bool,
722 gutter_side: Side,
723 text_align: TextAlign,
724 placeholder: SharedString,
725 mask_placeholder: Option<String>,
726}
727
728impl InputPresentation {
729 pub fn focus_handle(&self) -> &FocusHandle {
730 &self.focus_handle
731 }
732
733 pub fn is_disabled(&self) -> bool {
734 self.disabled
735 }
736
737 pub fn is_readonly(&self) -> bool {
738 self.readonly
739 }
740
741 pub fn is_editable(&self) -> bool {
745 !self.disabled && !self.readonly
746 }
747
748 pub fn is_loading(&self) -> bool {
749 self.loading
750 }
751
752 pub fn is_masked(&self) -> bool {
753 self.masked
754 }
755
756 pub fn is_multi_line(&self) -> bool {
757 self.multi_line
758 }
759
760 pub fn is_code_editor(&self) -> bool {
761 self.code_editor
762 }
763
764 pub fn gutter_side(&self) -> Side {
765 self.gutter_side
766 }
767
768 pub fn text_align(&self) -> TextAlign {
769 self.text_align
770 }
771
772 pub fn placeholder(&self) -> &SharedString {
773 &self.placeholder
774 }
775
776 pub fn mask_placeholder(&self) -> Option<&str> {
778 self.mask_placeholder.as_deref()
779 }
780}
781
782impl<M: InputModeKind> EventEmitter<InputEvent> for InputBaseState<M> {}
783impl<M: InputModeKind> EventEmitter<InputEditsEvent> for InputBaseState<M> {}
784
785impl<M: InputModeKind> InputBaseState<M> {
786 #[doc(hidden)]
787 pub fn cursor_layout(&self) -> Option<(Bounds<Pixels>, Pixels)> {
788 let layout = self.last_layout.as_ref()?;
789 let mut bounds = layout.cursor_bounds?;
790 bounds.origin.y -= self.scroll_handle.offset().y;
791 Some((bounds, layout.line_height))
792 }
793
794 #[doc(hidden)]
799 pub fn prepaint_caret_geometry(&self) -> Option<PrepaintCaretGeometry> {
800 self.prepaint_caret_geometry
801 }
802
803 pub fn input_bounds(&self) -> Bounds<Pixels> {
804 self.input_bounds
805 }
806
807 pub fn text_bounds(&self) -> Option<Bounds<Pixels>> {
808 self.last_bounds
809 }
810
811 pub fn display_map(&self) -> &DisplayMap {
831 &self.display_map
832 }
833
834 pub fn prewrap(
845 &mut self,
846 font: gpui::Font,
847 font_size: Pixels,
848 width: Pixels,
849 cx: &mut Context<Self>,
850 ) {
851 if self.last_layout.is_some() {
852 return;
853 }
854 let wrap_width = (width - RIGHT_MARGIN).max(px(1.));
855 self.display_map.set_font(font, font_size, cx);
856 self.display_map
857 .set_tab_size(self.mode.tab_size().tab_size, cx);
858 self.display_map
859 .on_layout_changed(self.soft_wrap.then_some(wrap_width), cx);
860 self.display_map
861 .set_wrapping_indent(self.wrapping_indent, cx);
862 self.sync_font_spans(cx);
863 self.display_map.ensure_text_prepared(&self.text, cx);
864 }
865
866 pub fn diagnostic_popover(&self) -> Option<Rc<crate::input::DiagnosticEntry>> {
867 self.diagnostic_popover.clone()
868 }
869
870 pub fn presentation(&self) -> InputPresentation {
871 InputPresentation {
872 focus_handle: self.focus_handle.clone(),
873 disabled: self.disabled,
874 readonly: self.readonly,
875 loading: self.loading,
876 masked: self.masked,
877 multi_line: self.is_multi_line(),
878 code_editor: self.is_code_editor(),
879 gutter_side: self.gutter_side,
880 text_align: self.text_align,
881 placeholder: self.placeholder.clone(),
882 mask_placeholder: self.mask_pattern.placeholder(),
883 }
884 }
885
886 #[inline]
891 pub(crate) fn shows_scrollbar(&self) -> bool {
899 self.is_multi_line()
900 }
901
902 pub fn is_multi_line(&self) -> bool {
903 M::MULTI_LINE
904 }
905
906 #[inline]
908 pub fn is_single_line(&self) -> bool {
909 !M::MULTI_LINE
910 }
911
912 #[inline]
914 pub fn is_code_editor(&self) -> bool {
915 M::CODE_EDITOR
916 }
917
918 pub fn is_copyable(&self) -> bool {
922 self.selections.iter().any(|sel| !sel.is_empty()) && !self.masked
923 }
924
925 pub fn context_menu_capabilities(&self) -> InputContextMenuCapabilities {
926 let (go_to_definition, code_actions) = self.extras.context_menu_capabilities();
927 InputContextMenuCapabilities::new()
928 .disabled(self.disabled)
929 .readonly(self.readonly)
930 .code_editor(self.is_code_editor())
931 .selection(!self.active_selection().is_empty())
932 .masked(self.masked)
933 .go_to_definition(go_to_definition)
934 .code_actions(code_actions)
935 }
936
937 pub fn set_text_align(&mut self, text_align: TextAlign, cx: &mut Context<Self>) {
938 if !self.is_single_line() || self.text_align == text_align {
939 return;
940 }
941
942 self.text_align = text_align;
943 cx.notify();
944 }
945
946 pub fn toggle_masked(&mut self, _: &mut Window, cx: &mut Context<Self>) {
952 self.masked = !self.masked;
953 cx.notify();
954 }
955
956 pub fn on_context_menu(
957 &mut self,
958 handler: Rc<
959 dyn Fn(NativeMenu, InputContextMenuCapabilities, Point<Pixels>, &mut Window, &mut App),
960 >,
961 ) {
962 self.context_menu_handler = Some(handler);
963 }
964
965 pub fn set_selection_focus(&mut self, focus: Option<FocusHandle>, cx: &mut Context<Self>) {
970 self.selection_focus = focus.as_ref().map(FocusHandle::downgrade);
971 cx.notify();
972 }
973
974 pub fn has_selection_focus(&self, window: &Window, cx: &App) -> bool {
976 self.focus_handle.is_focused(window)
977 || self
978 .selection_focus
979 .as_ref()
980 .and_then(WeakFocusHandle::upgrade)
981 .is_some_and(|focus| focus.is_focused(window) || focus.contains_focused(window, cx))
982 }
983
984 fn new_in_mode(window: &mut Window, cx: &mut Context<Self>) -> Self {
986 let focus_handle = cx.focus_handle().tab_stop(true);
987 let blink_cursor = cx.new(BlinkCursor::new);
988 let undo_manager = UndoManager::new();
989
990 let _subscriptions = vec![
991 cx.intercept_keystrokes({
994 let focus_handle = focus_handle.clone();
995 let blink_cursor = blink_cursor.downgrade();
996 move |_, window, cx| {
997 if focus_handle.is_focused(window) {
998 _ = blink_cursor.update(cx, |cursor, cx| cursor.pause(cx));
999 }
1000 }
1001 }),
1002 cx.observe(&blink_cursor, |_, _, cx| cx.notify()),
1004 cx.observe_window_activation(window, |input, window, cx| {
1006 if !window.is_window_active() {
1007 input.cancel_mouse_gesture(cx);
1008 }
1009 if window.is_window_active() {
1010 let focus_handle = input.focus_handle.clone();
1011 if focus_handle.is_focused(window) {
1012 input.blink_cursor.update(cx, |blink_cursor, cx| {
1013 blink_cursor.start(cx);
1014 });
1015 }
1016 }
1017 }),
1018 cx.observe_window_bounds(window, |input, _, cx| input.cancel_mouse_gesture(cx)),
1019 cx.on_focus(&focus_handle, window, Self::on_focus),
1020 cx.on_blur(&focus_handle, window, Self::on_blur),
1021 ];
1022
1023 let text_style = window.text_style();
1024
1025 Self {
1026 extras: M::Extras::default(),
1027 focus_handle: focus_handle.clone(),
1028 selection_focus: None,
1029 text: "".into(),
1030 display_map: DisplayMap::new(text_style.font(), window.rem_size(), None),
1031 spacers_asked: None,
1032 search_session: super::SearchSession::default(),
1033 search_activation_revision: 0,
1034 searchable: false,
1035 replaceable: true,
1036 soft_wrap: true,
1037 wrapping_indent: WrappingIndent::default(),
1038 scroll_beyond_last_line: None,
1039 cursor_surrounding_lines: None,
1040 blink_cursor,
1041 undo_manager,
1042 inline_tokens: None,
1043 pending_token: None,
1044 replaying_history: false,
1045 validated_token_edit: false,
1046 document_revision: 0,
1047 font_spans_key: None,
1048 token_presentation: Default::default(),
1049 token_bounds: Default::default(),
1050 hovered_token: None,
1051 pending_token_hover_exits: Vec::new(),
1052 token_layout_cache: None,
1053 pressed_token: None,
1054 selections: Selections::default(),
1055 selected_word_range: None,
1056 ime_marked_range: None,
1057 ime_original_text: None,
1058 input_bounds: Bounds::default(),
1059 selecting: false,
1060 touch_selection: Default::default(),
1061 disabled: false,
1062 readonly: false,
1063 text_align: TextAlign::Left,
1064 masked: false,
1065 clean_on_escape: false,
1066 submit_on_enter: false,
1067 input_action: None,
1068 autocorrect: None,
1069 autocapitalize: None,
1070 show_whitespaces: false,
1071 loading: false,
1072 pattern: None,
1073 validate: None,
1074 number_step: Some(NumberStep::Fixed(1.)),
1075 number_min: None,
1076 number_max: None,
1077 mode: LayoutMode::default(),
1078 last_layout: None,
1079 prepaint_caret_geometry: None,
1080 last_bounds: None,
1081 revealed_viewport: None,
1082 last_gutter_bounds: None,
1083 last_selected_range: None,
1084 last_input_edits: Vec::new(),
1085 column_select_start: None,
1086 last_cursor: None,
1087 ime_anchor: None,
1088 scroll_handle: ScrollHandle::new(),
1089 scroll_bounce: crate::ScrollBounce::enabled_by_default(),
1090 overscroll: Overscroll::default(),
1091 scroll_size: gpui::size(px(0.), px(0.)),
1092 scroll_y_f64: 0.0,
1093 deferred_scroll_y_f64: None,
1094 last_synced_handle_y: Cell::new(px(0.)),
1095 scroll_height_f64: 0.0,
1096 editor_scrollbar_snapshot: Cell::new(None),
1097 overview_ruler_rows: Default::default(),
1098 scrollbar_placement: ScrollbarPlacement::default(),
1099 gutter_side: Side::Left,
1100 gutter_order: GutterColumn::DEFAULT_ORDER,
1101 longest_line_width: Cell::new(None),
1102 editor_paddings: Edges::default(),
1103 deferred_scroll_offset: None,
1104 placeholder: SharedString::default(),
1105 mask_pattern: MaskPattern::default(),
1106 mask_pattern_set: false,
1107 editor_style: InputEditorStyle::default(),
1108 projected_editor_style: InputEditorStyle::default(),
1109 fold_placeholder_renderer: None,
1110 fold_background: None,
1111 accessibility: None,
1112 scrollbar_renderer: None,
1113 diagnostic_popover: None,
1114 spelling: None,
1115 context_menu_handler: None,
1116 pending_context_menu: None,
1117 context_menu_offset: None,
1118 context_menu_hit: None,
1119 enable_context_menu: true,
1120 completion_inserting: false,
1121 overlay_action_handler: None,
1122 silent_replace_text: false,
1123 emit_events: true,
1124 _subscriptions,
1125 _pending_update: false,
1126 cursor_line_end_affinity: false,
1127 auto_scroll: AutoScroll::default(),
1128 }
1129 }
1130
1131 pub fn context_menu(mut self, enable: bool) -> Self {
1138 self.enable_context_menu = enable;
1139 self
1140 }
1141
1142 pub fn set_context_menu_enabled(&mut self, enabled: bool) {
1143 self.enable_context_menu = enabled;
1144 }
1145
1146 #[doc(hidden)]
1148 pub fn replaceable(mut self, allow: bool) -> Self {
1149 self.replaceable = allow;
1150 self
1151 }
1152
1153 pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
1155 self.placeholder = placeholder.into();
1156 self
1157 }
1158
1159 pub fn set_highlighter(
1161 &mut self,
1162 new_language: impl Into<SharedString>,
1163 cx: &mut Context<Self>,
1164 ) {
1165 match &mut self.mode {
1166 LayoutMode::CodeEditor {
1167 language,
1168 highlighter,
1169 ..
1170 } => {
1171 language.set_name(new_language.into());
1172 *highlighter.borrow_mut() = None;
1173 }
1174 _ => {}
1175 }
1176 self.refresh(cx);
1177 }
1178
1179 fn reset_highlighter(&mut self, cx: &mut Context<Self>) {
1180 match &mut self.mode {
1181 LayoutMode::CodeEditor { highlighter, .. } => {
1182 *highlighter.borrow_mut() = None;
1183 }
1184 _ => {}
1185 }
1186 cx.notify();
1187 }
1188
1189 pub fn set_highlighter_factory(
1191 &mut self,
1192 factory: InputHighlighterFactory,
1193 cx: &mut Context<Self>,
1194 ) {
1195 self.mode.set_highlighter_factory(factory);
1196 self._pending_update = true;
1197 self.token_layout_cache = None;
1198 cx.notify();
1199 }
1200
1201 pub fn ensure_highlighter_factory(&mut self, factory: InputHighlighterFactory) {
1203 self.mode.ensure_highlighter_factory(factory);
1204 }
1205
1206 pub fn set_editor_style(&mut self, style: InputEditorStyle) {
1207 self.editor_style = style.clone();
1208 self.projected_editor_style = style;
1209 }
1210
1211 pub fn set_fold_placeholder_renderer(
1214 &mut self,
1215 renderer: Option<FoldPlaceholderRenderer>,
1216 cx: &mut Context<Self>,
1217 ) {
1218 self.fold_placeholder_renderer = renderer;
1219 cx.notify();
1220 }
1221
1222 pub fn set_fold_background(&mut self, color: Option<Hsla>, cx: &mut Context<Self>) {
1225 self.fold_background = color;
1226 cx.notify();
1227 }
1228
1229 pub fn set_accessibility(&mut self, accessibility: InputAccessibility) {
1231 self.accessibility = Some(accessibility);
1232 }
1233
1234 fn handle_accessibility_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1235 if !self.disabled {
1236 self.focus(window, cx);
1237 }
1238 }
1239
1240 fn handle_accessibility_set_value(
1241 &mut self,
1242 data: Option<&gpui::accesskit::ActionData>,
1243 window: &mut Window,
1244 cx: &mut Context<Self>,
1245 ) {
1246 let Some(gpui::accesskit::ActionData::Value(value)) = data else {
1247 return;
1248 };
1249 if self.is_editable() && self.exposes_full_accessibility_text() {
1251 self.replace_all(value.to_string(), window, cx);
1252 }
1253 }
1254
1255 #[doc(hidden)]
1257 pub fn set_editor_paddings(&mut self, paddings: Edges<Pixels>) {
1258 self.editor_paddings = paddings;
1259 }
1260
1261 pub fn set_scrollbar_renderer(
1269 &mut self,
1270 renderer: Option<crate::input::EditorScrollbarRenderer>,
1271 ) {
1272 self.scrollbar_renderer = renderer;
1273 }
1274
1275 pub fn apply_highlighter_fold_candidates(
1276 &mut self,
1277 candidates: Vec<crate::input::FoldRange>,
1278 cx: &mut Context<Self>,
1279 ) {
1280 if self.mode.is_folding() {
1281 self.display_map.set_fold_candidates(candidates);
1282 }
1283 cx.notify();
1284 }
1285
1286 #[inline]
1287 pub fn diagnostics(&self) -> Option<&DiagnosticSet> {
1288 self.mode.diagnostics()
1289 }
1290
1291 #[inline]
1292 pub fn diagnostics_mut(&mut self) -> Option<&mut DiagnosticSet> {
1293 self.mode.diagnostics_mut()
1294 }
1295
1296 pub fn set_placeholder(
1298 &mut self,
1299 placeholder: impl Into<SharedString>,
1300 _: &mut Window,
1301 cx: &mut Context<Self>,
1302 ) {
1303 self.placeholder = placeholder.into();
1304 cx.notify();
1305 }
1306
1307 pub(super) fn line_and_position_for_offset(
1315 &self,
1316 offset: usize,
1317 ) -> (usize, usize, Option<Point<Pixels>>) {
1318 let Some(last_layout) = &self.last_layout else {
1319 return (0, 0, None);
1320 };
1321 let line_height = last_layout.line_height;
1322 let target_row = self.text.offset_to_point(offset.min(self.text.len())).row;
1323
1324 let mut y_offset = last_layout.visible_top;
1325 for (vi, line) in last_layout.lines.iter().enumerate() {
1326 let (spacer_above, spacer_below) = last_layout.spacers(vi);
1327 y_offset += spacer_above;
1328 let buffer_line = last_layout.visible_buffer_lines[vi];
1329 if buffer_line == target_row {
1330 let prev_lines_offset = last_layout.visible_line_byte_offsets[vi];
1331 let local_offset = offset.saturating_sub(prev_lines_offset).min(line.len());
1332 let pos = line
1333 .position_for_index(local_offset, last_layout, false)
1334 .unwrap_or_else(|| point(px(0.), px(0.)));
1335 let sub_line_index = (pos.y / line_height) as usize;
1336 let adjusted_pos = point(pos.x + last_layout.text_origin_x, pos.y + y_offset);
1337 return (vi, sub_line_index, Some(adjusted_pos));
1338 }
1339
1340 y_offset += line.size(line_height).height + spacer_below;
1341 }
1342 (0, 0, None)
1343 }
1344
1345 pub fn set_value(
1354 &mut self,
1355 value: impl Into<super::InputContent>,
1356 window: &mut Window,
1357 cx: &mut Context<Self>,
1358 ) {
1359 let content = value.into();
1360 self.inline_tokens = None;
1361 self.undo_manager.set_ignoring(true);
1362 self.emit_events = false;
1363 self.replace_text(content.text().clone(), window, cx);
1364 self.ime_original_text = None;
1365 self.install_tokens(content);
1366 self.undo_manager.set_ignoring(false);
1367 self.emit_events = true;
1368
1369 self.reset_selection();
1370 self.reset_lsp_state();
1371 self.reset_scroll_to_start();
1372
1373 self.undo_manager.clear();
1374 cx.notify();
1375 }
1376
1377 pub fn replace_all(
1387 &mut self,
1388 text: impl Into<SharedString>,
1389 window: &mut Window,
1390 cx: &mut Context<Self>,
1391 ) {
1392 self.replace_text(text, window, cx);
1393 self.reset_selection();
1394 self.reset_lsp_state();
1395 self.reset_scroll_to_start();
1396
1397 cx.notify();
1398 }
1399
1400 pub(super) fn with_edits_allowed(&mut self, f: impl FnOnce(&mut Self)) {
1405 let (was_disabled, was_readonly) = (self.disabled, self.readonly);
1406 (self.disabled, self.readonly) = (false, false);
1407 f(self);
1408 (self.disabled, self.readonly) = (was_disabled, was_readonly);
1409 }
1410
1411 pub fn insert(
1415 &mut self,
1416 text: impl Into<SharedString>,
1417 window: &mut Window,
1418 cx: &mut Context<Self>,
1419 ) {
1420 let text: SharedString = text.into();
1421 self.with_edits_allowed(|this| {
1422 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1423 let range_utf16 = this.range_to_utf16(&(this.cursor()..this.cursor()));
1424 this.replace_text_in_range_silent(Some(range_utf16), &text, window, cx);
1425 let end = this.active_selection().end;
1426 this.set_cursor_to(end);
1427 });
1428 }
1429
1430 pub fn replace(
1434 &mut self,
1435 text: impl Into<SharedString>,
1436 window: &mut Window,
1437 cx: &mut Context<Self>,
1438 ) {
1439 let text: SharedString = text.into();
1440 self.with_edits_allowed(|this| {
1441 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1442 this.replace_text_in_range_silent(None, &text, window, cx);
1443 let end = this.active_selection().end;
1444 this.set_cursor_to(end);
1445 });
1446 }
1447
1448 fn replace_text(
1449 &mut self,
1450 text: impl Into<SharedString>,
1451 window: &mut Window,
1452 cx: &mut Context<Self>,
1453 ) {
1454 let text: SharedString = text.into();
1455 self.with_edits_allowed(|this| {
1456 this.undo_manager.set_pending_intent(EditIntent::Atomic);
1457 let range = 0..this.text.len_utf16();
1458 this.replace_text_in_range_silent(Some(range), &text, window, cx);
1459 this.reset_highlighter(cx);
1460 });
1461 }
1462
1463 fn reset_selection(&mut self) {
1464 self.selections.remove_all_but_active();
1465
1466 if self.is_single_line() {
1470 let end = self.text.len();
1471 self.set_cursor_to(end);
1472 } else {
1473 self.active_selection_mut().clear();
1474 }
1475 }
1476
1477 fn reset_lsp_state(&mut self) {
1478 if self.is_code_editor() {
1479 self._pending_update = true;
1480 M::reset_language_features(self);
1481 }
1482 }
1483
1484 fn reset_scroll_to_start(&mut self) {
1485 self.scroll_handle.set_offset(point(px(0.), px(0.)));
1489 self.scroll_y_f64 = 0.0;
1490 self.last_synced_handle_y.set(px(0.));
1491 if self.is_single_line() {
1492 self.deferred_scroll_offset = Some(point(px(0.), px(0.)));
1493 self.deferred_scroll_y_f64 = Some(0.0);
1494 }
1495 }
1496
1497 #[allow(unused)]
1501 pub(crate) fn disabled(mut self, disabled: bool) -> Self {
1502 self.disabled = disabled;
1503 self
1504 }
1505
1506 pub fn set_disabled(&mut self, disabled: bool, cx: &mut Context<Self>) {
1507 if self.disabled == disabled {
1508 return;
1509 }
1510
1511 self.disabled = disabled;
1512 if disabled {
1513 M::hide_context_menu(self, cx);
1514 M::clear_inline_completion(self, cx);
1515 }
1516 cx.notify();
1517 }
1518
1519 #[allow(unused)]
1527 pub(crate) fn readonly(mut self, readonly: bool) -> Self {
1528 self.readonly = readonly;
1529 self
1530 }
1531
1532 pub fn set_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
1533 if self.readonly == readonly {
1534 return;
1535 }
1536
1537 self.readonly = readonly;
1538 if readonly {
1539 M::hide_context_menu(self, cx);
1540 M::clear_inline_completion(self, cx);
1541 self.search_session.replace_mode = false;
1542 }
1543 cx.notify();
1544 }
1545
1546 pub fn is_editable(&self) -> bool {
1551 !self.disabled && !self.readonly
1552 }
1553
1554 pub fn is_composing(&self) -> bool {
1556 self.ime_marked_range.is_some()
1557 }
1558
1559 pub fn clean_on_escape(mut self) -> Self {
1563 self.clean_on_escape = true;
1564 self
1565 }
1566
1567 pub fn set_clean_on_escape(&mut self, clean: bool) {
1568 self.clean_on_escape = clean;
1569 }
1570
1571 #[doc(hidden)]
1576 pub fn submit_on_enter(mut self, submit: bool) -> Self {
1577 self.submit_on_enter = submit;
1578 self
1579 }
1580
1581 pub fn set_submit_on_enter(&mut self, submit: bool, cx: &mut Context<Self>) {
1582 self.submit_on_enter = submit;
1583 cx.notify();
1584 }
1585
1586 pub fn input_action(mut self, action: TextInputAction) -> Self {
1593 self.input_action = Some(action);
1594 self
1595 }
1596
1597 pub fn autocorrect(mut self, autocorrect: bool) -> Self {
1603 self.autocorrect = Some(autocorrect);
1604 self
1605 }
1606
1607 pub fn autocapitalize(mut self, autocapitalize: Autocapitalize) -> Self {
1612 self.autocapitalize = Some(autocapitalize);
1613 self
1614 }
1615
1616 pub fn text_input_configuration(&self) -> TextInputConfiguration {
1620 let autocorrect = self.autocorrect.unwrap_or(false);
1624 let input_action =
1625 self.input_action
1626 .unwrap_or(if self.is_multi_line() && !self.submit_on_enter {
1627 TextInputAction::Enter
1628 } else {
1629 TextInputAction::Done
1630 });
1631 TextInputConfiguration {
1632 autocorrect,
1633 autocapitalize: self.autocapitalize.unwrap_or(Autocapitalize::None),
1634 suggestions: autocorrect,
1635 input_action,
1636 }
1637 }
1638
1639 #[doc(hidden)]
1641 pub fn show_whitespaces(mut self, show: bool) -> Self {
1642 self.show_whitespaces = show;
1643 self
1644 }
1645
1646 pub fn set_show_whitespaces(&mut self, show: bool, _: &mut Window, cx: &mut Context<Self>) {
1648 self.show_whitespaces = show;
1649 cx.notify();
1650 }
1651
1652 pub fn scroll_beyond_last_line(mut self, rows: Option<usize>) -> Self {
1662 self.scroll_beyond_last_line = rows;
1663 self
1664 }
1665
1666 pub fn set_scroll_beyond_last_line(
1668 &mut self,
1669 rows: Option<usize>,
1670 _: &mut Window,
1671 cx: &mut Context<Self>,
1672 ) {
1673 if self.scroll_beyond_last_line == rows {
1674 return;
1675 }
1676 self.scroll_beyond_last_line = rows;
1677 cx.notify();
1678 }
1679
1680 pub fn cursor_surrounding_lines(mut self, lines: Option<usize>) -> Self {
1694 self.cursor_surrounding_lines = lines;
1695 self
1696 }
1697
1698 pub fn set_cursor_surrounding_lines(
1700 &mut self,
1701 lines: Option<usize>,
1702 _: &mut Window,
1703 cx: &mut Context<Self>,
1704 ) {
1705 if self.cursor_surrounding_lines == lines {
1706 return;
1707 }
1708 self.cursor_surrounding_lines = lines;
1709 cx.notify();
1710 }
1711
1712 pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
1714 let text: SharedString = value.into();
1715 self.text = Rope::from(self.normalize_input(&text).as_ref());
1716 if let Some(diagnostics) = self.mode.diagnostics_mut() {
1717 diagnostics.reset(&self.text)
1718 }
1719 self._pending_update = true;
1722 self
1723 }
1724
1725 pub fn value(&self) -> SharedString {
1730 SharedString::new(self.text.to_string())
1731 }
1732
1733 pub fn selected_value(&self) -> SharedString {
1739 SharedString::new(self.selected_text().to_string())
1740 }
1741
1742 pub fn unmask_value(&self) -> SharedString {
1744 self.mask_pattern.unmask(&self.text.to_string()).into()
1745 }
1746
1747 #[doc(hidden)]
1753 pub fn prepare(&mut self, _: &mut Window, _: &mut Context<Self>) {}
1754
1755 pub fn text(&self) -> &Rope {
1760 &self.text
1761 }
1762
1763 fn emit_change(&mut self, cx: &mut Context<Self>) {
1765 if let Some(original) = self.ime_original_text.take() {
1766 self.last_input_edits = vec![(
1767 Self::full_input_edit(&original, &self.text),
1768 self.text.clone(),
1769 )];
1770 }
1771 cx.emit(InputEditsEvent {
1772 edits: self.last_input_edits.clone(),
1773 });
1774 cx.emit(InputEvent::Change);
1775 }
1776
1777 fn full_input_edit(old_text: &Rope, new_text: &Rope) -> InputEdit {
1778 InputEdit {
1779 start_byte: 0,
1780 old_end_byte: old_text.len(),
1781 new_end_byte: new_text.len(),
1782 start_position: old_text.offset_to_point(0),
1783 old_end_position: old_text.offset_to_point(old_text.len()),
1784 new_end_position: new_text.offset_to_point(new_text.len()),
1785 }
1786 }
1787
1788 pub fn cursor_position(&self) -> Position {
1790 let offset = self.cursor();
1791 self.text.offset_to_position(offset)
1792 }
1793
1794 pub fn set_cursor_position(
1798 &mut self,
1799 position: impl Into<Position>,
1800 window: &mut Window,
1801 cx: &mut Context<Self>,
1802 ) {
1803 let position: Position = position.into();
1804 let offset = self.text.position_to_offset(&position);
1805
1806 self.move_to(offset, None, cx);
1807 self.update_preferred_column();
1808 self.focus(window, cx);
1809 }
1810
1811 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1813 self.focus_handle.focus(window, cx);
1814 self.blink_cursor.update(cx, |cursor, cx| {
1815 cursor.start(cx);
1816 });
1817 }
1818
1819 pub fn refresh(&mut self, cx: &mut Context<Self>) {
1833 self._pending_update = true;
1834 cx.notify();
1835 }
1836
1837 pub(super) fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
1838 self.undo_manager.break_transaction_coalescing();
1839 let mirrored = self.arrows_mirrored(cx);
1840 self.select_all_cursors_to(
1841 move |s, sel| {
1842 if mirrored {
1843 s.next_boundary(sel.cursor_offset())
1844 } else {
1845 s.previous_boundary(sel.cursor_offset())
1846 }
1847 },
1848 cx,
1849 );
1850 }
1851
1852 pub(super) fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
1853 let mirrored = self.arrows_mirrored(cx);
1854 self.select_all_cursors_to(
1855 move |s, sel| {
1856 if mirrored {
1857 s.previous_boundary(sel.cursor_offset())
1858 } else {
1859 s.next_boundary(sel.cursor_offset())
1860 }
1861 },
1862 cx,
1863 );
1864 }
1865
1866 pub(super) fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
1867 if self.is_single_line() {
1868 return;
1869 }
1870 self.select_all_cursors_to_with_affinity(
1871 |s, sel| {
1872 s.vertical_selection_target(
1873 sel.cursor_offset(),
1874 sel.column_anchor,
1875 s.line_end_affinity_for(sel),
1876 -1,
1877 )
1878 },
1879 true,
1880 cx,
1881 );
1882 }
1883
1884 pub(super) fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
1885 if self.is_single_line() {
1886 return;
1887 }
1888 self.select_all_cursors_to_with_affinity(
1889 |s, sel| {
1890 s.vertical_selection_target(
1891 sel.cursor_offset(),
1892 sel.column_anchor,
1893 s.line_end_affinity_for(sel),
1894 1,
1895 )
1896 },
1897 true,
1898 cx,
1899 );
1900 }
1901
1902 pub(super) fn on_action_select_all(
1903 &mut self,
1904 _: &SelectAll,
1905 window: &mut Window,
1906 cx: &mut Context<Self>,
1907 ) {
1908 self.select_all(window, cx);
1909 }
1910
1911 pub(super) fn select_to_start(
1912 &mut self,
1913 _: &SelectToStart,
1914 _: &mut Window,
1915 cx: &mut Context<Self>,
1916 ) {
1917 self.undo_manager.break_transaction_coalescing();
1918 self.select_all_cursors_to(|_, _| 0, cx);
1919 }
1920
1921 pub(super) fn select_to_end(
1922 &mut self,
1923 _: &SelectToEnd,
1924 _: &mut Window,
1925 cx: &mut Context<Self>,
1926 ) {
1927 self.undo_manager.break_transaction_coalescing();
1928 let end = self.text.len();
1929 self.select_all_cursors_to(move |_, _| end, cx);
1930 }
1931
1932 pub(super) fn select_to_start_of_line(
1933 &mut self,
1934 _: &SelectToStartOfLine,
1935 _: &mut Window,
1936 cx: &mut Context<Self>,
1937 ) {
1938 self.undo_manager.break_transaction_coalescing();
1939 self.select_all_cursors_to(
1940 |s, sel| s.start_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1941 cx,
1942 );
1943 }
1944
1945 pub(super) fn select_to_end_of_line(
1946 &mut self,
1947 _: &SelectToEndOfLine,
1948 _: &mut Window,
1949 cx: &mut Context<Self>,
1950 ) {
1951 self.undo_manager.break_transaction_coalescing();
1952 self.select_all_cursors_to_with_affinity(
1953 |s, sel| {
1954 (
1955 s.end_of_line_at(sel.cursor_offset(), s.line_end_affinity_for(sel)),
1956 true,
1957 )
1958 },
1959 false,
1960 cx,
1961 );
1962 }
1963
1964 pub(super) fn select_to_previous_word(
1965 &mut self,
1966 _: &SelectToPreviousWordStart,
1967 _: &mut Window,
1968 cx: &mut Context<Self>,
1969 ) {
1970 self.undo_manager.break_transaction_coalescing();
1971 let mirrored = self.arrows_mirrored(cx);
1972 self.select_all_cursors_to(
1973 move |s, sel| {
1974 if mirrored {
1975 s.next_end_of_word_at(sel.cursor_offset())
1976 } else {
1977 s.previous_start_of_word_at(sel.cursor_offset())
1978 }
1979 },
1980 cx,
1981 );
1982 }
1983
1984 pub(super) fn select_to_next_word(
1985 &mut self,
1986 _: &SelectToNextWordEnd,
1987 _: &mut Window,
1988 cx: &mut Context<Self>,
1989 ) {
1990 self.undo_manager.break_transaction_coalescing();
1991 let mirrored = self.arrows_mirrored(cx);
1992 self.select_all_cursors_to(
1993 move |s, sel| {
1994 if mirrored {
1995 s.previous_start_of_word_at(sel.cursor_offset())
1996 } else {
1997 s.next_end_of_word_at(sel.cursor_offset())
1998 }
1999 },
2000 cx,
2001 );
2002 }
2003
2004 pub(super) fn previous_start_of_word_at(&self, offset: usize) -> usize {
2007 if self.masked {
2008 return 0;
2012 }
2013
2014 let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
2015 let left_part = self.text.slice(0..offset).to_string();
2017
2018 let target = UnicodeSegmentation::split_word_bound_indices(left_part.as_str())
2019 .rfind(|(_, s)| !s.trim_start().is_empty())
2020 .map(|(i, _)| i)
2021 .unwrap_or(0);
2022 self.token_boundary(target, Bias::Left)
2023 }
2024
2025 pub(super) fn next_end_of_word_at(&self, offset: usize) -> usize {
2027 if self.masked {
2028 return self.text.len();
2030 }
2031
2032 let offset = self.offset_from_utf16(self.offset_to_utf16(offset));
2033 let right_part = self.text.slice(offset..self.text.len()).to_string();
2034
2035 let target = UnicodeSegmentation::split_word_bound_indices(right_part.as_str())
2036 .find(|(_, s)| !s.trim_start().is_empty())
2037 .map(|(i, s)| offset + i + s.len())
2038 .unwrap_or(self.text.len());
2039 self.token_boundary(target, Bias::Right)
2040 }
2041
2042 pub(super) fn start_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2047 if self.is_single_line() {
2048 return 0;
2049 }
2050
2051 let row = self.text.offset_to_point(offset).row;
2052 let logical_start = self.text.line_start_offset(row);
2053
2054 if self.soft_wrap && self.is_code_editor() {
2055 let wrap_point = self
2056 .display_map
2057 .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2058 if let Some(line) = self.display_map.line(row)
2059 && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2060 {
2061 let visual_start = logical_start + range.start;
2062 if offset != visual_start {
2063 return visual_start;
2064 }
2065 }
2066 }
2067
2068 logical_start
2069 }
2070
2071 pub(super) fn end_of_line_at(&self, offset: usize, line_end_affinity: bool) -> usize {
2076 if self.is_single_line() {
2077 return self.text.len();
2078 }
2079
2080 let row = self.text.offset_to_point(offset).row;
2081 let logical_start = self.text.line_start_offset(row);
2082 let logical_end = self.text.line_end_offset(row);
2083
2084 if self.soft_wrap && self.is_code_editor() {
2085 let wrap_point = self
2089 .display_map
2090 .offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
2091 if let Some(line) = self.display_map.line(row)
2092 && let Some(range) = line.wrapped_lines.get(wrap_point.local_row)
2093 {
2094 let visual_end = logical_start + range.end;
2095 if offset != visual_end {
2096 return visual_end;
2097 }
2098 }
2099 }
2100
2101 logical_end
2102 }
2103
2104 pub(super) fn indent_of_next_line(&mut self) -> String {
2108 self.indent_of_next_line_at(self.cursor())
2109 }
2110
2111 pub(super) fn indent_of_next_line_at(&mut self, offset: usize) -> String {
2113 if self.is_single_line() {
2114 return "".into();
2115 }
2116
2117 let mut current_indent = String::new();
2118 let mut next_indent = String::new();
2119 let line_end_affinity = self.line_end_affinity_at(offset);
2120 let current_line_start_pos = self.start_of_line_at(offset, line_end_affinity);
2121 let next_line_start_pos = self.end_of_line_at(offset, line_end_affinity);
2122 for c in self.text.slice(current_line_start_pos..).chars() {
2123 if !c.is_whitespace() {
2124 break;
2125 }
2126 if c == '\n' || c == '\r' {
2127 break;
2128 }
2129 current_indent.push(c);
2130 }
2131
2132 for c in self.text.slice(next_line_start_pos..).chars() {
2133 if !c.is_whitespace() {
2134 break;
2135 }
2136 if c == '\n' || c == '\r' {
2137 break;
2138 }
2139 next_indent.push(c);
2140 }
2141
2142 if next_indent.len() > current_indent.len() {
2143 return next_indent;
2144 }
2145
2146 if let Some(rules) = self.mode.language_config() {
2149 if self.mode.is_smart_indent()
2150 && M::editing_syntax_context(self, offset) == crate::input::SyntaxContext::Code
2151 {
2152 let line_before: String = self
2153 .text
2154 .slice(current_line_start_pos..offset)
2155 .chars()
2156 .collect();
2157 if rules.opens_indent(line_before.trim_end()) {
2158 let tab = self.mode.tab_size();
2159 if tab.hard_tabs {
2160 current_indent.push('\t');
2161 } else {
2162 for _ in 0..tab.tab_size {
2163 current_indent.push(' ');
2164 }
2165 }
2166 } else {
2167 let line_after = self.text.slice(offset..next_line_start_pos).to_string();
2168 if rules.closes_indent(&line_after) {
2169 let tab = self.mode.tab_size();
2170 if current_indent.ends_with('\t') {
2171 current_indent.pop();
2172 } else {
2173 for _ in 0..tab.tab_size {
2174 if !current_indent.ends_with(' ') {
2175 break;
2176 }
2177 current_indent.pop();
2178 }
2179 }
2180 }
2181 }
2182 }
2183 }
2184
2185 current_indent
2186 }
2187
2188 fn delete_selections(
2196 &mut self,
2197 silent: bool,
2198 collapsed_intent: EditIntent,
2199 mut collapsed_target: impl FnMut(&mut Self, usize) -> Range<usize>,
2200 window: &mut Window,
2201 cx: &mut Context<Self>,
2202 ) {
2203 if !self.is_editable() {
2204 return;
2205 }
2206 let cursors: Vec<CursorSelection> = self.selections.iter().copied().collect();
2207 let intent = if cursors.iter().all(|sel| sel.is_empty()) {
2208 collapsed_intent
2209 } else {
2210 EditIntent::Atomic
2211 };
2212 let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(cursors.len());
2213 for sel in &cursors {
2214 let range = if sel.is_empty() {
2215 collapsed_target(self, sel.cursor_offset())
2216 } else {
2217 sel.start..sel.end
2218 };
2219 let (start, end) = (range.start.min(range.end), range.start.max(range.end));
2220 let mut selection = *sel;
2221 selection.start = start;
2222 selection.end = end;
2223 new_selections.push(selection);
2224 }
2225 self.undo_manager.begin_transaction_with(intent);
2228 self.undo_manager
2229 .record_selections(cursors.clone(), cursors.clone());
2230 self.selections.replace_all(new_selections);
2231 self.undo_manager.set_pending_intent(intent);
2232
2233 let was_silent = self.silent_replace_text;
2234 self.silent_replace_text = silent;
2235 self.replace_text_in_range(None, "", window, cx);
2236 self.silent_replace_text = was_silent;
2237 self.undo_manager
2238 .record_selections(cursors, self.selections.iter().copied().collect());
2239 self.undo_manager.commit_transaction();
2240 self.pause_blink_cursor(cx);
2241 }
2242
2243 fn auto_close_target(&self, range: &Range<usize>, text: &str) -> Option<(usize, SharedString)> {
2246 if self.silent_replace_text
2247 || self.ime_marked_range.is_some()
2248 || !self.selections.is_single()
2249 || !self.active_selection().is_empty()
2250 || !range.is_empty()
2251 || range.start != self.cursor()
2252 || text.chars().count() != 1
2253 || !self.mode.is_auto_close()
2254 {
2255 return None;
2256 }
2257 let rules = self.mode.language_config()?;
2258 if self
2259 .text
2260 .chars_at(range.start)
2261 .next()
2262 .is_some_and(|c| !c.is_whitespace() && !rules.auto_close_before.contains(c))
2263 {
2264 return None;
2265 }
2266 for (open, close, not_in) in rules.closing_pairs() {
2267 let Some(prefix) = open.strip_suffix(text) else {
2268 continue;
2269 };
2270 if !self.text_before_matches(range.start, prefix) {
2271 continue;
2272 }
2273 let start = range.start - prefix.len();
2274 if open == close
2275 && (self.is_escaped_at(start)
2276 || self
2277 .text
2278 .chars_at(start)
2279 .reversed()
2280 .next()
2281 .is_some_and(|c| c.is_alphanumeric() || c == '_'))
2282 {
2283 continue;
2284 }
2285 if not_in.contains(&M::editing_syntax_context(self, start)) {
2286 continue;
2287 }
2288 return Some((open.len(), close.into()));
2289 }
2290 None
2291 }
2292
2293 fn text_before_matches(&self, offset: usize, text: &str) -> bool {
2294 offset >= text.len()
2295 && self.text.is_char_boundary(offset - text.len())
2296 && self.text.slice(offset - text.len()..offset) == text
2297 }
2298
2299 fn text_after_matches(&self, offset: usize, text: &str) -> bool {
2300 offset + text.len() <= self.text.len()
2301 && self.text.is_char_boundary(offset + text.len())
2302 && self.text.slice(offset..offset + text.len()) == text
2303 }
2304
2305 fn is_escaped_at(&self, offset: usize) -> bool {
2306 self.text
2307 .chars_at(offset)
2308 .reversed()
2309 .take_while(|c| *c == '\\')
2310 .count()
2311 % 2
2312 == 1
2313 }
2314
2315 fn skip_over_target(&self, new_text: &str) -> Option<usize> {
2322 if !self.mode.is_auto_close() || new_text.chars().count() != 1 {
2323 return None;
2324 }
2325 let rules = self.mode.language_config()?;
2326 let cursor = self.cursor();
2327 for (open, close, not_in) in rules.closing_pairs() {
2328 for (index, _) in close.char_indices() {
2329 if !close[index..].starts_with(new_text)
2330 || !self.text_before_matches(cursor, &close[..index])
2331 || !self.text_after_matches(cursor, &close[index..])
2332 {
2333 continue;
2334 }
2335 let context = M::editing_syntax_context(self, cursor);
2336 let generated =
2337 self.mode
2338 .auto_closed_pairs()
2339 .contains_closer(cursor, index, close.len());
2340 if !generated
2341 && not_in.contains(&context)
2342 && !(context == crate::input::SyntaxContext::String && open == close)
2343 {
2344 continue;
2345 }
2346 if self.is_escaped_at(cursor - index) {
2347 continue;
2348 }
2349 return Some(cursor + new_text.len());
2350 }
2351 }
2352 None
2353 }
2354
2355 pub(super) fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
2356 if self.selections.is_single() && self.active_selection().is_empty() && self.cursor() == 0 {
2362 cx.propagate();
2363 return;
2364 }
2365
2366 if self.mode.is_auto_close()
2369 && self.selections.is_single()
2370 && self.active_selection().is_empty()
2371 {
2372 let off = self.cursor();
2373 let deletion = self.mode.language_config().and_then(|rules| {
2374 rules.closing_pairs().find_map(|(open, close, not_in)| {
2375 if !self.text_before_matches(off, open) || !self.text_after_matches(off, close)
2376 {
2377 return None;
2378 }
2379 let start = off - open.len();
2380 let generated = self
2381 .mode
2382 .auto_closed_pairs()
2383 .contains(start..off, off..off + close.len());
2384 if self.is_escaped_at(start)
2385 || (!generated && not_in.contains(&M::editing_syntax_context(self, start)))
2386 {
2387 return None;
2388 }
2389 Some(start..off + close.len())
2390 })
2391 });
2392 if let Some(range) = deletion {
2393 let utf16 = self.range_to_utf16(&range);
2394 self.replace_text_in_range_silent(Some(utf16), "", window, cx);
2395 return;
2396 }
2397 }
2398
2399 self.delete_selections(
2400 false,
2401 EditIntent::Backspace,
2402 |s, offset| s.previous_boundary(offset)..offset,
2403 window,
2404 cx,
2405 );
2406 }
2407
2408 pub(super) fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
2409 self.delete_selections(
2410 false,
2411 EditIntent::DeleteForward,
2412 |s, offset| offset..s.next_boundary(offset),
2413 window,
2414 cx,
2415 );
2416 }
2417
2418 pub(super) fn delete_to_beginning_of_line(
2419 &mut self,
2420 _: &DeleteToBeginningOfLine,
2421 window: &mut Window,
2422 cx: &mut Context<Self>,
2423 ) {
2424 self.delete_selections(
2425 true,
2426 EditIntent::Atomic,
2427 |s, offset| {
2428 let mut start = s.start_of_line_at(offset, s.line_end_affinity_at(offset));
2429 if start == offset {
2430 start = start.saturating_sub(1);
2431 }
2432 start..offset
2433 },
2434 window,
2435 cx,
2436 );
2437 }
2438
2439 pub(super) fn delete_to_end_of_line(
2440 &mut self,
2441 _: &DeleteToEndOfLine,
2442 window: &mut Window,
2443 cx: &mut Context<Self>,
2444 ) {
2445 self.delete_selections(
2446 true,
2447 EditIntent::Atomic,
2448 |s, offset| {
2449 let mut end = s.end_of_line_at(offset, s.line_end_affinity_at(offset));
2450 if end == offset {
2451 end = (end + 1).clamp(0, s.text.len());
2452 }
2453 offset..end
2454 },
2455 window,
2456 cx,
2457 );
2458 }
2459
2460 pub(super) fn delete_previous_word(
2461 &mut self,
2462 _: &DeleteToPreviousWordStart,
2463 window: &mut Window,
2464 cx: &mut Context<Self>,
2465 ) {
2466 self.delete_selections(
2467 true,
2468 EditIntent::Atomic,
2469 |s, offset| s.previous_start_of_word_at(offset)..offset,
2470 window,
2471 cx,
2472 );
2473 }
2474
2475 pub(super) fn delete_next_word(
2476 &mut self,
2477 _: &DeleteToNextWordEnd,
2478 window: &mut Window,
2479 cx: &mut Context<Self>,
2480 ) {
2481 self.delete_selections(
2482 true,
2483 EditIntent::Atomic,
2484 |s, offset| offset..s.next_word_delete_end_at(offset, !cfg!(target_os = "macos")),
2485 window,
2486 cx,
2487 );
2488 }
2489
2490 pub(super) fn next_word_delete_end_at(&self, offset: usize, stop_at_whitespace: bool) -> usize {
2497 if stop_at_whitespace && !self.masked {
2498 let mut chars = self.text.slice(offset..self.text.len()).chars();
2499 match chars.next() {
2500 Some('\r') => {
2501 let next = if chars.next() == Some('\n') { 2 } else { 1 };
2502 return offset + next;
2503 }
2504 Some('\n') => return offset + 1,
2505 Some(c) if c.is_whitespace() => {
2506 let mut end = offset + c.len_utf8();
2507 for c in chars {
2508 if c == '\n' || c == '\r' || !c.is_whitespace() {
2509 break;
2510 }
2511 end += c.len_utf8();
2512 }
2513 return end;
2514 }
2515 _ => {}
2516 }
2517 }
2518 self.next_end_of_word_at(offset)
2519 }
2520
2521 pub(super) fn enter(&mut self, action: &Enter, window: &mut Window, cx: &mut Context<Self>) {
2522 if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2523 return;
2524 }
2525
2526 if M::has_inline_completion(self) {
2528 M::clear_inline_completion(self, cx);
2529 }
2530
2531 let insert_newline =
2537 self.is_multi_line() && !action.secondary && (!self.submit_on_enter || action.shift);
2538
2539 if insert_newline {
2540 if !self.selections.is_single() {
2541 self.selections.merge_overlapping();
2543 let selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
2544 let mut edits: Vec<(Range<usize>, String)> = Vec::with_capacity(selections.len());
2545 for sel in &selections {
2546 let indent = if self.is_code_editor() {
2547 self.indent_of_next_line_at(sel.cursor_offset())
2548 } else {
2549 String::new()
2550 };
2551 edits.push((sel.start..sel.end, format!("\n{}", indent)));
2552 }
2553 edits.sort_by_key(|(range, _)| range.start);
2554 self.replace_text_in_ranges(&edits, window, cx);
2555 self.pause_blink_cursor(cx);
2556 } else {
2557 let mut split = false;
2563 if self.is_code_editor() && self.active_selection().is_empty() {
2564 if let Some(rules) = self.mode.language_config() {
2565 if self.mode.is_smart_indent()
2566 && M::editing_syntax_context(self, self.cursor())
2567 == crate::input::SyntaxContext::Code
2568 {
2569 let off = self.cursor();
2570 let is_pair = rules.brackets.iter().any(|p| {
2571 !p.open.is_empty()
2572 && !p.close.is_empty()
2573 && p.open != p.close
2574 && self.text_before_matches(off, p.open.as_ref())
2575 && self.text_after_matches(off, p.close.as_ref())
2576 });
2577 if is_pair {
2578 let line_end_affinity = self.line_end_affinity_at(off);
2580 let line_start = self.start_of_line_at(off, line_end_affinity);
2581 let mut indent = String::new();
2582 for c in self.text.slice(line_start..).chars() {
2583 if !c.is_whitespace() || c == '\n' || c == '\r' {
2584 break;
2585 }
2586 indent.push(c);
2587 }
2588 let mut inner = indent.clone();
2590 if self.mode.is_smart_indent() {
2591 let tab = self.mode.tab_size();
2592 if tab.hard_tabs {
2593 inner.push('\t');
2594 } else {
2595 for _ in 0..tab.tab_size {
2596 inner.push(' ');
2597 }
2598 }
2599 }
2600 let new_line_text = format!("\n{inner}\n{indent}");
2601 self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2602 self.set_cursor_to(off + 1 + inner.len());
2603 self.update_preferred_column();
2604 let cursors = self.selections.iter().copied().collect::<Vec<_>>();
2605 self.undo_manager
2606 .record_selections(cursors.clone(), cursors);
2607 self.pause_blink_cursor(cx);
2608 split = true;
2609 }
2610 }
2611 }
2612 }
2613 if !split {
2614 let indent = if self.is_code_editor() {
2616 self.indent_of_next_line()
2617 } else {
2618 "".to_string()
2619 };
2620
2621 let new_line_text = format!("\n{}", indent);
2623 self.replace_text_in_range_silent(None, &new_line_text, window, cx);
2624 self.pause_blink_cursor(cx);
2625 }
2626 }
2627 } else {
2628 self.undo_manager.break_transaction_coalescing();
2631 cx.propagate();
2632 }
2633
2634 cx.emit(InputEvent::PressEnter {
2635 secondary: action.secondary,
2636 shift: action.shift,
2637 });
2638 }
2639
2640 pub fn clean(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2641 self.replace_text("", window, cx);
2642 self.set_selection(0, 0);
2643 self.scroll_to(0, None, cx);
2644 }
2645
2646 pub(super) fn escape(&mut self, action: &Escape, window: &mut Window, cx: &mut Context<Self>) {
2647 if M::handle_context_menu_action(self, Box::new(action.clone()), window, cx) {
2648 return;
2649 }
2650
2651 let hover_open = self.extras.hover_symbol_range().is_some();
2652 M::hide_context_menu(self, cx);
2654 if hover_open {
2657 return;
2658 }
2659
2660 if !self.selections.is_single() {
2662 self.undo_manager.break_transaction_coalescing();
2663 self.selections.remove_all_but_active();
2664 cx.notify();
2665 return;
2666 }
2667
2668 if M::has_inline_completion(self) {
2670 M::clear_inline_completion(self, cx);
2671 return; }
2673 M::clear_inline_completion(self, cx);
2674
2675 if self.touch_selection().is_some() {
2677 self.dismiss_touch_selection(cx);
2678 return;
2679 }
2680
2681 if self.ime_marked_range.is_some() {
2682 self.unmark_text(window, cx);
2683 }
2684
2685 if self.clean_on_escape && !cfg!(target_os = "android") {
2688 return self.clean(window, cx);
2689 }
2690
2691 cx.propagate();
2692 }
2693
2694 pub(crate) fn handle_right_click_menu(
2696 &mut self,
2697 position: Point<Pixels>,
2698 offset: usize,
2699 hit: Option<InputHit>,
2700 window: &mut Window,
2701 cx: &mut Context<Self>,
2702 ) {
2703 if self.disabled {
2704 return;
2705 }
2706 if crate::GlobalState::is_in_deferred_context(cx) {
2707 return;
2708 }
2709
2710 self.context_menu_offset = Some(offset);
2711 self.context_menu_hit = hit;
2712 if !self.active_selection().contains(offset) {
2713 self.move_to(offset, None, cx);
2714 }
2715
2716 if self.is_code_editor() {
2717 M::on_hover_definition(self, offset, window, cx);
2718 }
2719
2720 if let Some(handler) = self.context_menu_handler.clone() {
2721 let capabilities = self.context_menu_capabilities();
2722 let input = cx.weak_entity();
2723 window.defer(cx, move |window, cx| {
2726 if input.upgrade().is_none() {
2727 return;
2728 }
2729 let previous_focus = window.focused(cx);
2730 handler(NativeMenu::new(), capabilities, position, window, cx);
2731 input
2734 .update(cx, |this, cx| {
2735 if window.focused(cx) == previous_focus
2736 && !this.focus_handle.is_focused(window)
2737 && this.has_selection_focus(window, cx)
2738 {
2739 return;
2741 }
2742 let menu_focus = window.focused(cx).filter(|focus| {
2743 Some(focus) != previous_focus.as_ref() && *focus != this.focus_handle
2744 });
2745 this.set_selection_focus(menu_focus, cx);
2746 })
2747 .ok();
2748 });
2749 }
2750 }
2751
2752 pub(super) fn add_cursor_above(
2753 &mut self,
2754 _: &AddCursorAbove,
2755 _: &mut Window,
2756 cx: &mut Context<Self>,
2757 ) {
2758 self.add_cursor_vertical(-1, cx);
2759 }
2760
2761 pub(super) fn add_cursor_below(
2762 &mut self,
2763 _: &AddCursorBelow,
2764 _: &mut Window,
2765 cx: &mut Context<Self>,
2766 ) {
2767 self.add_cursor_vertical(1, cx);
2768 }
2769
2770 fn add_cursor_vertical(&mut self, move_lines: isize, cx: &mut Context<Self>) {
2775 if !self.is_multi_line() {
2776 return;
2777 }
2778
2779 self.pause_blink_cursor(cx);
2780 self.undo_manager.break_transaction_coalescing();
2782
2783 let sources: Vec<(usize, Option<(Pixels, usize)>, bool)> = self
2784 .selections
2785 .iter()
2786 .map(|sel| {
2787 (
2788 sel.cursor_offset(),
2789 sel.column_anchor,
2790 self.line_end_affinity_for(sel),
2791 )
2792 })
2793 .collect();
2794 let mut offsets: std::collections::HashSet<usize> =
2795 sources.iter().map(|(offset, _, _)| *offset).collect();
2796
2797 let mut newest: Option<usize> = None;
2798 for (offset, anchor, line_end_affinity) in sources {
2799 let anchor = anchor.or_else(|| self.preferred_column_for(offset));
2800 let (target, _) = self.vertical_target(offset, anchor, line_end_affinity, move_lines);
2801 if target == offset || offsets.contains(&target) {
2802 continue;
2803 }
2804 offsets.insert(target);
2805 let id = self.selections.generate_id();
2806 let mut cursor = CursorSelection::new(id, target, target);
2807 cursor.column_anchor = anchor;
2808 self.selections.add(cursor);
2809 newest = Some(target);
2810 }
2811
2812 if let Some(newest) = newest {
2813 self.scroll_to(newest, None, cx);
2814 }
2815 cx.notify();
2816 }
2817
2818 pub(super) fn add_cursor_at(&mut self, offset: usize, cx: &mut Context<Self>) {
2823 if !self.is_multi_line() {
2824 return;
2825 }
2826
2827 for sel in self.selections.iter() {
2828 if sel.contains(offset) {
2829 return;
2830 }
2831 if sel.is_collapsed() && sel.cursor_offset() == offset {
2832 return;
2833 }
2834 }
2835
2836 self.undo_manager.break_transaction_coalescing();
2837 let id = self.selections.generate_id();
2838 let mut selection = CursorSelection::new(id, offset, offset);
2839 selection.column_anchor = self.preferred_column_for(offset);
2840 self.selections.add(selection);
2841 cx.notify();
2842 }
2843
2844 pub(super) fn build_columnar_selection(
2852 &mut self,
2853 start: ColumnarPoint,
2854 end: ColumnarPoint,
2855 cx: &mut Context<Self>,
2856 ) {
2857 if !self.is_multi_line() {
2858 return;
2859 }
2860
2861 self.undo_manager.break_transaction_coalescing();
2862
2863 let (start_row, start_col) = self.columnar_row_column(start);
2864 let (end_row, end_col) = self.columnar_row_column(end);
2865 let (start_row, end_row) = (start_row.min(end_row), start_row.max(end_row));
2866 let (start_col, end_col) = (start_col.min(end_col), start_col.max(end_col));
2867
2868 let mut new_selections = Vec::with_capacity(end_row - start_row + 1);
2869 for row in start_row..=end_row {
2870 if self.display_map.is_spacer_row(row) {
2871 continue;
2872 }
2873 let sel_start = self
2874 .display_map
2875 .display_row_column_to_offset(row, start_col);
2876 let sel_end = self.display_map.display_row_column_to_offset(row, end_col);
2877 let id = self.selections.generate_id();
2878 let sel_start = self.text.clip_offset(sel_start, Bias::Left);
2879 let sel_end = self.text.clip_offset(sel_end, Bias::Left);
2880 new_selections.push(CursorSelection::new(id, sel_start, sel_end));
2881 }
2882
2883 self.selections.replace_all(new_selections);
2884 cx.notify();
2885 }
2886
2887 fn columnar_row_column(&self, point: ColumnarPoint) -> (usize, usize) {
2890 let display_point = self.display_map.offset_to_wrap_display_point(point.offset);
2891 let row = self
2892 .display_map
2893 .wrap_row_to_display_row(display_point.row)
2894 .unwrap_or_else(|| {
2895 self.display_map
2896 .nearest_visible_display_row(display_point.row)
2897 });
2898
2899 (row, display_point.column + point.columns_past_line_end)
2900 }
2901
2902 pub(super) fn on_mouse_down(
2903 &mut self,
2904 event: &MouseDownEvent,
2905 window: &mut Window,
2906 cx: &mut Context<Self>,
2907 ) {
2908 if window.default_prevented() {
2911 return;
2912 }
2913 if event.button == MouseButton::Left
2916 && crate::GlobalState::is_touch_press(cx)
2917 && !self.disabled
2918 && !self.readonly
2919 {
2920 window.request_virtual_keyboard();
2921 }
2922 self.undo_manager.break_transaction_coalescing();
2923 if !self.disabled {
2927 self.focus(window, cx);
2928 self.pause_blink_cursor(cx);
2929 }
2930 crate::global_state::GlobalState::suppress_text_selection(cx);
2933
2934 M::clear_inline_completion(self, cx);
2936 if event.button == MouseButton::Left
2940 && event.click_count == 1
2941 && self.reopen_edit_menu_at(event.position, cx)
2942 {
2943 return;
2944 }
2945 self.dismiss_touch_selection(cx);
2946
2947 if let Some(ime_marked_range) = &self.ime_marked_range {
2950 if ime_marked_range.len() == 0 {
2951 self.ime_marked_range = None;
2952 }
2953 }
2954
2955 self.selecting = true;
2956 let (offset, line_end_affinity, columns_past_line_end) =
2957 self.resolve_mouse_position(event.position);
2958
2959 if M::on_click(self, event, offset, window, cx) {
2960 return;
2961 }
2962
2963 if event.button == MouseButton::Left && event.click_count >= 3 {
2965 self.select_line(offset, window, cx);
2966 return;
2967 }
2968
2969 if event.button == MouseButton::Left && event.click_count == 2 {
2971 self.select_word(offset, window, cx);
2972 if crate::GlobalState::is_touch_press(cx) {
2975 self.keep_touch_selection(cx);
2976 }
2977 return;
2978 }
2979
2980 if event.button == MouseButton::Right {
2982 if self.enable_context_menu {
2983 let hit = self.hit_test(event.position);
2984 if !self.active_selection().contains(offset) {
2985 self.move_to(offset, None, cx);
2986 }
2987 self.pending_context_menu = Some((event.position, offset, hit));
2988 }
2989 return;
2990 }
2991
2992 if self.is_multi_line() && event.button == MouseButton::Left {
2994 if event.modifiers.alt
2995 && (event.modifiers.shift || (cfg!(target_os = "linux") && event.modifiers.control))
2996 {
2997 self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
3000 self.selecting = true;
3001 self.move_to_with_affinity(offset, None, line_end_affinity, cx);
3002 return;
3003 } else if event.modifiers.alt {
3004 self.add_cursor_at(offset, cx);
3005 self.column_select_start = Some(ColumnarPoint::new(offset, columns_past_line_end));
3008 return;
3009 }
3010 }
3011
3012 if event.modifiers.shift {
3013 self.select_to_with_affinity(offset, line_end_affinity, cx);
3014 } else {
3015 self.move_to_with_affinity(offset, None, line_end_affinity, cx)
3016 }
3017 }
3018
3019 pub(super) fn on_mouse_up(
3020 &mut self,
3021 event: &MouseUpEvent,
3022 window: &mut Window,
3023 cx: &mut Context<Self>,
3024 ) {
3025 if event.button == MouseButton::Right {
3026 if let Some((position, offset, hit)) = self.pending_context_menu.take() {
3027 self.handle_right_click_menu(position, offset, hit, window, cx);
3028 }
3029 }
3030 if self.active_selection().is_empty() {
3031 self.active_selection_mut().reversed = false;
3032 }
3033 self.selecting = false;
3034 self.selected_word_range = None;
3035 self.column_select_start = None;
3036 self.auto_scroll.stop();
3037 }
3038
3039 pub(super) fn on_mouse_move(
3040 &mut self,
3041 event: &MouseMoveEvent,
3042 window: &mut Window,
3043 cx: &mut Context<Self>,
3044 ) {
3045 let within_bounds = self.input_bounds.contains(&event.position);
3047
3048 if !within_bounds {
3049 M::clear_hover_state(self, cx);
3051 return;
3052 }
3053
3054 let (offset, _) = self.index_for_mouse_position(event.position);
3056 M::on_mouse_move(self, offset, event, window, cx);
3057
3058 if self.is_code_editor() {
3059 match self
3063 .mode
3064 .diagnostics()
3065 .and_then(|set| set.for_offset(offset))
3066 {
3067 Some(diagnostic) => {
3068 if self.diagnostic_popover.as_deref() != Some(diagnostic) {
3069 self.diagnostic_popover = Some(Rc::new(diagnostic.clone()));
3070 cx.notify();
3071 }
3072 }
3073 None => {
3074 if self.diagnostic_popover.take().is_some() {
3075 cx.notify();
3076 }
3077 }
3078 }
3079 }
3080 }
3081
3082 pub(super) fn on_scroll_wheel(
3083 &mut self,
3084 event: &ScrollEvent,
3085 window: &mut Window,
3086 cx: &mut Context<Self>,
3087 ) {
3088 let line_height = self
3089 .last_layout
3090 .as_ref()
3091 .map(|layout| layout.line_height)
3092 .unwrap_or(window.line_height());
3093 let delta = event.delta.pixel_delta(line_height);
3094
3095 let old_offset = self.scroll_handle.offset();
3096 let old_y_f64 = self.effective_scroll_y_f64();
3097 let precise = matches!(event.delta, gpui::ScrollDelta::Pixels(_));
3098 if !precise || !self.scroll_bounce || cx.reduce_motion() || !self.overflows_vertically() {
3099 let displaced = self.overscroll.offset() != 0.;
3100 self.overscroll.reset();
3101 if displaced {
3102 cx.notify();
3103 }
3104 }
3105 let bounces = self.scroll_bounce
3106 && precise
3107 && !cx.reduce_motion()
3108 && delta.y.abs() >= delta.x.abs()
3109 && self.overflows_vertically();
3110 if bounces {
3111 let mut overscroll = std::mem::take(&mut self.overscroll);
3112 let stretched = overscroll.packet(
3113 delta.y.as_f32(),
3114 event.touch_phase,
3115 self.input_bounds.size.height.as_f32(),
3116 cx.background_executor().now(),
3117 |dy| {
3118 let before_x = self.scroll_handle.offset().x;
3119 let before_y = self.effective_scroll_y_f64();
3120 self.update_scroll_offset_parts(
3121 before_x + delta.x,
3122 before_y + f64::from(dy),
3123 cx,
3124 );
3125 (self.scroll_y_f64 - before_y) as f32
3126 },
3127 );
3128 self.overscroll = overscroll;
3129 if stretched {
3130 cx.notify();
3131 }
3132 } else {
3133 self.overscroll
3134 .touch_phase(event.touch_phase, cx.background_executor().now());
3135 if matches!(
3137 event.touch_phase,
3138 gpui::TouchPhase::Ended | gpui::TouchPhase::Cancelled
3139 ) && self.overscroll.offset() != 0.
3140 {
3141 self.overscroll.packet(
3142 0.,
3143 event.touch_phase,
3144 self.input_bounds.size.height.as_f32(),
3145 cx.background_executor().now(),
3146 |_| 0.,
3147 );
3148 cx.notify();
3149 }
3150 self.update_scroll_offset_parts(
3151 old_offset.x + delta.x,
3152 old_y_f64 + f64::from(f32::from(delta.y)),
3153 cx,
3154 );
3155 }
3156
3157 if self.scroll_handle.offset() != old_offset
3161 || (self.scroll_y_f64 - old_y_f64).abs() > f64::EPSILON
3162 || self.overflows_along(delta)
3163 {
3164 cx.stop_propagation();
3165 }
3166
3167 if self.diagnostic_popover.take().is_some() {
3168 cx.notify();
3169 }
3170 self.edit_menu_on_scroll(event.touch_phase, cx);
3173 }
3174
3175 pub(super) fn takes_scroll(&self, delta: Point<Pixels>) -> bool {
3181 if delta.y.abs() >= delta.x.abs() {
3182 self.overflows_vertically()
3183 } else {
3184 self.scroll_size.width > self.input_bounds.size.width
3185 }
3186 }
3187
3188 fn overflows_along(&self, delta: Point<Pixels>) -> bool {
3192 if delta.y.abs() >= delta.x.abs() {
3193 delta.y != px(0.) && self.overflows_vertically()
3194 } else {
3195 self.scroll_size.width > self.input_bounds.size.width
3196 }
3197 }
3198
3199 fn overflows_vertically(&self) -> bool {
3201 self.is_multi_line()
3202 && self.content_height_f64() > f64::from(f32::from(self.input_bounds.size.height))
3203 }
3204
3205 pub(super) fn effective_scroll_y_f64(&self) -> f64 {
3206 let handle_y = self.scroll_handle.offset().y;
3207 if handle_y != self.last_synced_handle_y.get() {
3208 f64::from(f32::from(handle_y))
3209 } else {
3210 self.scroll_y_f64
3211 }
3212 }
3213
3214 pub(super) fn update_scroll_offset_parts(
3215 &mut self,
3216 mut x: Pixels,
3217 mut y_f64: f64,
3218 cx: &mut Context<Self>,
3219 ) {
3220 let content_height_f64 = self.content_height_f64();
3221 let viewport_height_f64 = f64::from(f32::from(self.input_bounds.size.height));
3222 y_f64 = if self.is_single_line() {
3223 0.0
3224 } else {
3225 super::element::clamp_vertical_scroll_offset_f64(
3226 y_f64,
3227 content_height_f64,
3228 viewport_height_f64,
3229 )
3230 };
3231 x = clamp_horizontal_scroll_offset(
3232 x,
3233 self.scroll_size.width,
3234 self.input_bounds.size.width,
3235 self.text_align,
3236 );
3237 let handle_y = px(y_f64 as f32);
3238 let prev_handle = self.scroll_handle.offset();
3239 let y_changed = (self.scroll_y_f64 - y_f64).abs() > f64::EPSILON
3240 || self.last_synced_handle_y.get() != handle_y
3241 || prev_handle.y != handle_y;
3242 self.scroll_y_f64 = y_f64;
3243 self.last_synced_handle_y.set(handle_y);
3244 let next_handle = point(x, handle_y);
3245 if prev_handle != next_handle || y_changed {
3246 if prev_handle != next_handle {
3247 self.scroll_handle.set_offset(next_handle);
3248 }
3249 cx.notify();
3250 }
3251 }
3252
3253 #[allow(dead_code)]
3254 pub(super) fn update_scroll_offset(
3255 &mut self,
3256 offset: Option<Point<Pixels>>,
3257 cx: &mut Context<Self>,
3258 ) {
3259 let (x, y_f64) = match offset {
3260 Some(offset) => (offset.x, f64::from(f32::from(offset.y))),
3261 None => (self.scroll_handle.offset().x, self.effective_scroll_y_f64()),
3262 };
3263 self.update_scroll_offset_parts(x, y_f64, cx);
3264 }
3265
3266 pub(crate) fn scroll_to(
3270 &mut self,
3271 offset: usize,
3272 direction: Option<MoveDirection>,
3273 cx: &mut Context<Self>,
3274 ) {
3275 let padding = if direction.is_some() {
3276 ScrollPadding::SurroundingLines
3277 } else {
3278 ScrollPadding::Minimal
3279 };
3280 self.scroll_to_with_padding(offset, direction, padding, cx);
3281 }
3282
3283 pub(crate) fn scroll_to_with_padding(
3286 &mut self,
3287 offset: usize,
3288 direction: Option<MoveDirection>,
3289 padding: ScrollPadding,
3290 cx: &mut Context<Self>,
3291 ) {
3292 let Some(last_layout) = self.last_layout.as_ref() else {
3293 return;
3294 };
3295 let Some(bounds) = self.last_bounds.as_ref() else {
3296 return;
3297 };
3298
3299 let mut scroll_offset = self.scroll_handle.offset();
3300 let was_y_f64 = self.effective_scroll_y_f64();
3301 let line_height = last_layout.line_height;
3302
3303 let point = self.text.offset_to_point(offset);
3304
3305 let row = point.row;
3306
3307 let display_row = self
3309 .display_map
3310 .offset_to_display_row(offset, self.line_end_affinity_at(offset));
3311 let line_height_f64 = f64::from(f32::from(line_height));
3312 let row_offset_y_f64 = line_height_f64 * (display_row as f64);
3313
3314 let safety_margin = match last_layout.text_align {
3317 TextAlign::Left => RIGHT_MARGIN,
3318 TextAlign::Right => px(0.),
3319 TextAlign::Center => CURSOR_WIDTH,
3320 };
3321 if let Some(vi) = last_layout
3322 .visible_buffer_lines
3323 .iter()
3324 .position(|&line| line == row)
3325 {
3326 let line = &last_layout.lines[vi];
3327 let local_offset = offset.saturating_sub(last_layout.visible_line_byte_offsets[vi]);
3328 if let Some(pos) = line.position_for_index(local_offset, last_layout, false) {
3329 let bounds_width = last_layout.text_width;
3330 let col_offset_x = pos.x;
3331 if col_offset_x - safety_margin < -scroll_offset.x {
3332 scroll_offset.x = -col_offset_x + safety_margin;
3334 } else if col_offset_x + safety_margin > -scroll_offset.x + bounds_width {
3335 scroll_offset.x = -(col_offset_x - bounds_width + safety_margin);
3336 }
3337 }
3338 }
3339
3340 let edge_height =
3345 if matches!(padding, ScrollPadding::SurroundingLines) && self.is_code_editor() {
3346 super::element::cursor_surrounding_padding(
3347 self.mode.is_auto_grow(),
3348 self.cursor_surrounding_lines,
3349 super::element::viewport_visible_lines(bounds.size.height, line_height),
3350 line_height,
3351 )
3352 } else {
3353 px(0.)
3354 };
3355 let mut target_y_f64 = super::element::reveal_row_f64(
3356 was_y_f64,
3357 row_offset_y_f64,
3358 line_height_f64,
3359 f64::from(f32::from(bounds.size.height)),
3360 f64::from(f32::from(edge_height)),
3361 );
3362
3363 if direction == Some(MoveDirection::Up) {
3365 target_y_f64 = target_y_f64.max(was_y_f64);
3366 } else if direction == Some(MoveDirection::Down) {
3367 target_y_f64 = target_y_f64.min(was_y_f64);
3368 }
3369
3370 target_y_f64 = super::element::clamp_vertical_scroll_offset_f64(
3374 target_y_f64,
3375 self.content_height_f64(),
3376 f64::from(f32::from(self.input_bounds.size.height)),
3377 );
3378 scroll_offset.x = scroll_offset.x.min(px(0.));
3379 scroll_offset.y = px(target_y_f64 as f32);
3380 self.deferred_scroll_offset = Some(scroll_offset);
3381 self.deferred_scroll_y_f64 = Some(target_y_f64);
3382 cx.notify();
3383 }
3384
3385 pub(super) fn show_character_palette(
3386 &mut self,
3387 _: &ShowCharacterPalette,
3388 window: &mut Window,
3389 _: &mut Context<Self>,
3390 ) {
3391 window.show_character_palette();
3392 }
3393
3394 fn selected_texts(&self) -> Vec<String> {
3396 let mut selections: Vec<CursorSelection> = self
3397 .selections
3398 .iter()
3399 .copied()
3400 .filter(|sel| !sel.is_empty())
3401 .collect();
3402 selections.sort_by_key(|sel| sel.start);
3403 selections
3404 .iter()
3405 .map(|sel| self.text.slice(*sel).to_string())
3406 .collect()
3407 }
3408
3409 pub(super) fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
3410 if self.selections.iter().all(|sel| sel.is_empty()) {
3411 cx.propagate();
3413 return;
3414 }
3415 if !self.is_copyable() {
3416 return;
3417 }
3418
3419 let texts = self.selected_texts();
3420
3421 cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3422 }
3423
3424 pub(super) fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
3425 if !self.is_copyable() {
3426 return;
3427 }
3428
3429 let texts = self.selected_texts();
3430
3431 cx.write_to_clipboard(ClipboardItem::new_string(texts.join("\n")));
3432
3433 self.undo_manager.set_pending_intent(EditIntent::Atomic);
3434 self.replace_text_in_range_silent(None, "", window, cx);
3435 }
3436
3437 pub(super) fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
3438 if !self.is_editable() {
3439 return;
3440 }
3441 if let Some(clipboard) = cx.read_from_clipboard() {
3442 self.insert_clipboard(clipboard, window, cx);
3443 return;
3444 }
3445 let read = cx.read_from_clipboard_async();
3450 let target = self.paste_target();
3451 cx.spawn_in(window, async move |this, cx| match read.await {
3452 Ok(Some(clipboard)) => {
3453 this.update_in(cx, |this, window, cx| {
3454 if this.is_editable()
3461 && this.focus_handle.is_focused(window)
3462 && this.paste_target() == target
3463 {
3464 this.insert_clipboard(clipboard, window, cx);
3465 }
3466 })
3467 .ok();
3468 }
3469 Ok(None) => {}
3470 Err(error) => tracing::warn!("failed to read the clipboard for paste: {error}"),
3471 })
3472 .detach();
3473 }
3474
3475 fn paste_target(&self) -> PasteTarget {
3479 PasteTarget {
3480 document_revision: self.document_revision,
3481 selections: self.selections.iter().copied().collect(),
3482 }
3483 }
3484
3485 fn insert_clipboard(
3491 &mut self,
3492 clipboard: ClipboardItem,
3493 window: &mut Window,
3494 cx: &mut Context<Self>,
3495 ) {
3496 let Some(mut new_text) = clipboard.text().filter(|text| !text.is_empty()) else {
3497 return;
3498 };
3499 self.undo_manager.set_pending_intent(EditIntent::Atomic);
3501
3502 if !self.is_multi_line() {
3503 new_text = new_text.replace('\n', "");
3504 self.replace_text_in_range_silent(None, &new_text, window, cx);
3505 return;
3506 }
3507
3508 if !self.selections.is_single() {
3511 self.selections.merge_overlapping();
3512 }
3513 let lines: Vec<String> = new_text.split('\n').map(|s| s.to_string()).collect();
3514 let count = self.selections.len();
3515 if count > 1 && lines.len() == count {
3516 let mut selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
3517 selections.sort_by_key(|sel| sel.start);
3518 let edits: Vec<(Range<usize>, String)> = selections
3519 .iter()
3520 .zip(lines)
3521 .map(|(sel, line)| (sel.start..sel.end, line))
3522 .collect();
3523 self.replace_text_in_ranges(&edits, window, cx);
3524 } else {
3525 self.replace_text_in_range_silent(None, &new_text, window, cx);
3526 }
3527 self.scroll_to(self.cursor(), None, cx);
3528 }
3529
3530 fn typing_intent(&self, edits: &[(Range<usize>, String)], new_text: &str) -> EditIntent {
3533 if !new_text.is_empty()
3534 && !new_text.contains(['\n', '\r'])
3535 && edits.iter().all(|(range, _)| range.is_empty())
3536 {
3537 EditIntent::Typing
3538 } else {
3539 EditIntent::Atomic
3540 }
3541 }
3542
3543 fn collapse_for_intent(
3549 intent: EditIntent,
3550 mut selection: CursorSelection,
3551 range: &Range<usize>,
3552 ) -> CursorSelection {
3553 match intent {
3554 EditIntent::Backspace => selection.place_at(range.end, None),
3555 EditIntent::DeleteForward => selection.place_at(range.start, None),
3556 EditIntent::Typing | EditIntent::Atomic => {}
3557 }
3558 selection
3559 }
3560
3561 fn rewrites_typed_char(
3564 &self,
3565 selection: CursorSelection,
3566 range: &Range<usize>,
3567 old_text: &str,
3568 new_text: &str,
3569 ) -> bool {
3570 !self.silent_replace_text
3571 && selection.is_collapsed()
3572 && selection.cursor_offset() == range.end
3573 && old_text.chars().count() == 1
3574 && !old_text.contains(['\n', '\r'])
3575 && !new_text.contains(['\n', '\r'])
3576 }
3577
3578 fn push_history(
3579 &mut self,
3580 text: &Rope,
3581 range: &Range<usize>,
3582 new_text: &str,
3583 requested_intent: Option<EditIntent>,
3584 selection_before: CursorSelection,
3585 selection_after: Option<CursorSelection>,
3586 ) -> bool {
3587 self.document_revision = self.document_revision.wrapping_add(1);
3588 let token_delta = self.edit_tokens(range, new_text.len());
3589 if self.undo_manager.is_ignoring() {
3590 return false;
3591 }
3592
3593 let range =
3594 text.clip_offset(range.start, Bias::Left)..text.clip_offset(range.end, Bias::Right);
3595 let old_text = text.slice(range.clone()).to_string();
3596 let new_range = range.start..range.start + new_text.len();
3597
3598 let intent = requested_intent.unwrap_or_else(|| {
3599 if range.is_empty()
3600 && old_text.is_empty()
3601 && !new_text.is_empty()
3602 && !new_text.contains(['\n', '\r'])
3603 || self.rewrites_typed_char(selection_before, &range, &old_text, new_text)
3604 {
3605 EditIntent::Typing
3606 } else {
3607 EditIntent::Atomic
3608 }
3609 });
3610
3611 let selection_before = Self::collapse_for_intent(intent, selection_before, &range);
3612 let selection_after =
3613 selection_after.unwrap_or_else(|| (new_range.end..new_range.end).into());
3614
3615 let open_transaction = self.undo_manager.has_open_transaction();
3616 let mut change = Change::new(range, &old_text, new_range, new_text);
3617 change.token_delta = token_delta;
3618 let recorded = self.undo_manager.record_transaction(change, intent);
3619 if recorded && !open_transaction {
3622 self.undo_manager
3623 .record_selections(vec![selection_before], vec![selection_after]);
3624 }
3625 recorded
3626 }
3627
3628 pub(super) fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
3629 self.replay_history(true, window, cx);
3630 }
3631
3632 pub(super) fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
3633 self.replay_history(false, window, cx);
3634 }
3635
3636 fn replay_history(&mut self, undo: bool, window: &mut Window, cx: &mut Context<Self>) {
3637 if !self.is_editable() {
3638 return;
3639 }
3640 let replay = if undo {
3641 self.undo_manager.undo()
3642 } else {
3643 self.undo_manager.redo()
3644 };
3645 let Some(replay) = replay else {
3646 return;
3647 };
3648 let token_aware = self.inline_tokens.is_some()
3649 || replay
3650 .changes
3651 .iter()
3652 .any(|change| change.token_delta.is_some());
3653 let emit_events = self.emit_events;
3654 if token_aware {
3655 self.emit_events = false;
3656 self.last_input_edits.clear();
3657 }
3658 self.replaying_history = token_aware;
3659 self.undo_manager.set_ignoring(true);
3660 for change in &replay.changes {
3661 let (range, text) = if undo {
3662 (change.new_range.into(), &change.old_text)
3663 } else {
3664 (change.old_range.into(), &change.new_text)
3665 };
3666 let range_utf16 = self.range_to_utf16(&range);
3667 self.replace_text_in_range_silent(Some(range_utf16), text, window, cx);
3668 self.replay_tokens(&range, text.len(), change.token_delta.as_deref(), undo);
3669 }
3670 self.restore_selections(replay.selections);
3671 self.mode
3672 .restore_auto_closed_pairs(replay.auto_closed_pairs.unwrap_or_default());
3673 if token_aware {
3674 self.ime_marked_range = None;
3677 }
3678 self.undo_manager.set_ignoring(false);
3679 self.replaying_history = false;
3680 self.emit_events = emit_events;
3681 if token_aware {
3682 if emit_events {
3683 self.emit_change(cx);
3684 } else {
3685 self.last_input_edits.clear();
3686 }
3687 }
3688 cx.notify();
3689 }
3690
3691 fn restore_selections(&mut self, selections: Option<Vec<CursorSelection>>) {
3695 let Some(selections) = selections else {
3696 return;
3697 };
3698
3699 let len = self.text.len();
3700 let restored: Vec<CursorSelection> = selections
3701 .into_iter()
3702 .map(|mut sel| {
3703 let (start, end) = (sel.start.min(len), sel.end.min(len));
3704 let start_bias = if start == end {
3705 Bias::Right
3706 } else {
3707 Bias::Left
3708 };
3709 sel.start = self.token_boundary(start, start_bias);
3710 sel.end = self.token_boundary(end, Bias::Right);
3711 sel
3712 })
3713 .collect();
3714 self.selections.replace_all(restored);
3715 self.selections.merge_overlapping();
3716 }
3717
3718 pub fn context_menu_offset(&self) -> Option<usize> {
3725 self.context_menu_offset
3726 }
3727
3728 pub fn context_menu_hit(&self) -> Option<InputHit> {
3734 self.context_menu_hit
3735 }
3736
3737 pub fn cursor(&self) -> usize {
3741 if let Some(ime_marked_range) = &self.ime_marked_range {
3742 return ime_marked_range.end;
3743 }
3744
3745 self.selections.active().cursor_offset()
3746 }
3747
3748 pub(super) fn active_selection(&self) -> &CursorSelection {
3750 self.selections.active()
3751 }
3752
3753 pub(super) fn active_selection_mut(&mut self) -> &mut CursorSelection {
3755 self.selections.active_mut()
3756 }
3757
3758 pub(super) fn set_selection(&mut self, start: usize, end: usize) {
3761 let range = self.normalize_token_range(start..end);
3762 let (start, end) = (range.start, range.end);
3763 let active = self.active_selection_mut();
3764 active.start = start;
3765 active.end = end;
3766 }
3767
3768 pub(super) fn set_cursor_to(&mut self, offset: usize) {
3771 let offset = self.token_boundary(offset, Bias::Right);
3772 let active = self.active_selection_mut();
3773 active.start = offset;
3774 active.end = offset;
3775 active.reversed = false;
3776 }
3777
3778 pub fn visible_row_range(&self) -> Option<std::ops::Range<usize>> {
3780 self.last_layout.as_ref().map(|l| l.visible_range.clone())
3781 }
3782
3783 pub fn scroll_offset(&self) -> gpui::Point<gpui::Pixels> {
3785 let mut offset = self.scroll_handle.offset();
3786 offset.y = px(self.effective_scroll_y_f64() as f32);
3787 offset
3788 }
3789
3790 pub fn set_scroll_offset(&mut self, offset: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) {
3794 self.deferred_scroll_offset = Some(offset);
3795 self.deferred_scroll_y_f64 = Some(f64::from(f32::from(offset.y)));
3796 cx.notify();
3797 }
3798
3799 pub fn scroll_y_f64(&self) -> f64 {
3801 self.effective_scroll_y_f64()
3802 }
3803
3804 pub fn set_scroll_y_f64(&mut self, y: f64, cx: &mut Context<Self>) {
3806 let x = self
3807 .deferred_scroll_offset
3808 .map_or_else(|| self.scroll_handle.offset().x, |offset| offset.x);
3809 self.deferred_scroll_offset = Some(point(x, px(y as f32)));
3810 self.deferred_scroll_y_f64 = Some(y);
3811 cx.notify();
3812 }
3813
3814 pub fn scroll_by_y_f64(&mut self, delta_y: f64, cx: &mut Context<Self>) {
3816 let current_x = self.scroll_handle.offset().x;
3817 let next_y = self.effective_scroll_y_f64() + delta_y;
3818 self.update_scroll_offset_parts(current_x, next_y, cx);
3819 }
3820
3821 pub fn content_height_f64(&self) -> f64 {
3823 if self.scroll_height_f64 > 0.0 {
3824 self.scroll_height_f64
3825 } else {
3826 f64::from(f32::from(self.scroll_size.height))
3827 }
3828 }
3829
3830 pub fn line_height(&self) -> Option<gpui::Pixels> {
3832 self.last_layout.as_ref().map(|l| l.line_height)
3833 }
3834
3835 pub fn selected_range(&self) -> std::ops::Range<usize> {
3843 (*self.selections.active()).into()
3844 }
3845
3846 pub fn is_selection_reversed(&self) -> bool {
3851 let selection = self.selections.active();
3852 !selection.is_empty() && selection.reversed
3853 }
3854
3855 pub fn select_all(&mut self, _: &mut Window, cx: &mut Context<Self>) {
3856 self.undo_manager.break_transaction_coalescing();
3857 self.selections.remove_all_but_active();
3858 self.set_selection(0, self.text.len());
3859 cx.notify();
3860 }
3861
3862 pub fn set_selected_range(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3867 self.set_selected_range_with_direction(range, false, cx);
3868 }
3869
3870 pub fn set_selected_range_with_direction(
3877 &mut self,
3878 range: Range<usize>,
3879 reversed: bool,
3880 cx: &mut Context<Self>,
3881 ) {
3882 let range = self.normalize_token_range(range);
3883 let end_bias = if range.start == range.end {
3884 Bias::Left
3885 } else {
3886 Bias::Right
3887 };
3888 let start = self.text.clip_offset(range.start, Bias::Left);
3889 let end = self.text.clip_offset(range.end, end_bias);
3890
3891 let (anchor, head) = if reversed { (end, start) } else { (start, end) };
3892 self.move_to(anchor, None, cx);
3893 self.active_selection_mut().reversed = false;
3894 self.selected_word_range = None;
3895 self.select_to(head, cx);
3896 }
3897
3898 pub fn add_selection(&mut self, range: Range<usize>, cx: &mut Context<Self>) {
3909 if !self.is_multi_line() {
3910 self.set_selected_range(range, cx);
3911 return;
3912 }
3913
3914 let range = self.normalize_token_range(range);
3915 let end_bias = if range.start == range.end {
3916 Bias::Left
3917 } else {
3918 Bias::Right
3919 };
3920 let start = self.cursor_boundary(range.start, Bias::Left);
3921 let end = self.cursor_boundary(self.text.clip_offset(range.end, end_bias), Bias::Left);
3924
3925 for sel in self.selections.iter() {
3926 if sel.start <= start && end <= sel.end {
3927 return;
3928 }
3929 }
3930
3931 self.undo_manager.break_transaction_coalescing();
3932 self.selected_word_range = None;
3933 self.pause_blink_cursor(cx);
3934 M::hide_context_menu(self, cx);
3935 M::clear_inline_completion(self, cx);
3936 let id = self.selections.generate_id();
3937 let mut selection = CursorSelection::new(id, start, end);
3938 selection.column_anchor = self.preferred_column_for(end);
3939 self.selections.add(selection);
3940 self.selections.merge_overlapping();
3941 self.scroll_to(end, None, cx);
3942 cx.notify();
3943 }
3944
3945 pub(crate) fn index_for_mouse_position(&self, position: Point<Pixels>) -> (usize, bool) {
3953 let (offset, line_end_affinity, _) = self.resolve_mouse_position(position);
3954 (offset, line_end_affinity)
3955 }
3956
3957 pub(super) fn resolve_mouse_position(&self, position: Point<Pixels>) -> (usize, bool, usize) {
3964 if self.text.len() == 0 {
3966 return (0, false, 0);
3967 }
3968
3969 let (Some(bounds), Some(last_layout)) =
3970 (self.last_bounds.as_ref(), self.last_layout.as_ref())
3971 else {
3972 return (0, false, 0);
3973 };
3974
3975 let line_height = last_layout.line_height;
3976 let text_origin_x = last_layout.text_origin_x;
3977
3978 let inner_position = position - bounds.origin - point(text_origin_x, px(0.));
3989
3990 let mut y_offset = last_layout.visible_top;
3991 let mut last_line_pos = None;
3994
3995 for (vi, (line_layout, &buffer_line)) in last_layout
3997 .lines
3998 .iter()
3999 .zip(last_layout.visible_buffer_lines.iter())
4000 .enumerate()
4001 {
4002 let line_start_offset = last_layout.visible_line_byte_offsets[vi];
4003 let (spacer_above, spacer_below) = last_layout.spacers(vi);
4004 y_offset += spacer_above;
4005 let height = line_layout.size(line_height).height;
4006 let ghost_height = match last_layout.ghost_lines {
4007 Some((ghost_row, ghost_height)) if ghost_row == buffer_line => ghost_height,
4008 _ => px(0.),
4009 };
4010
4011 let line_origin = point(px(0.), y_offset);
4013 let mut pos = inner_position - line_origin;
4014 if pos.y < px(0.) && pos.y >= -spacer_above {
4017 pos.y = px(0.);
4018 } else if pos.y >= height && pos.y < height + ghost_height + spacer_below {
4019 pos.y = height - line_height;
4020 }
4021
4022 if self.is_single_line() {
4024 let local_index = line_layout.closest_index_for_x(pos.x, last_layout);
4025 return (
4027 self.resolve_index(line_start_offset + local_index),
4028 false,
4029 0,
4030 );
4031 }
4032
4033 if let Some((local_index, line_end_affinity)) =
4035 line_layout.closest_index_for_position(pos, last_layout)
4036 {
4037 return (
4038 self.resolve_index(line_start_offset + local_index),
4039 line_end_affinity,
4040 line_layout.columns_past_line_end(pos, last_layout),
4041 );
4042 } else if pos.y < px(0.) {
4043 return (self.resolve_index(line_start_offset), false, 0);
4045 }
4046
4047 y_offset += height + ghost_height + spacer_below;
4048 last_line_pos = Some(pos);
4049 }
4050
4051 let last_position = last_layout
4054 .lines
4055 .last()
4056 .zip(last_line_pos)
4057 .zip(last_layout.visible_line_byte_offsets.last())
4058 .map(|((line_layout, pos), line_start)| {
4059 let last_row_top = (line_layout.size(line_height).height - line_height).max(px(0.));
4060 let pos = point(pos.x, last_row_top);
4061 (
4062 self.resolve_index(line_start + line_layout.len()),
4063 false,
4064 line_layout.columns_past_line_end(pos, last_layout),
4065 )
4066 });
4067
4068 last_position.unwrap_or((self.text.len(), false, 0))
4069 }
4070
4071 fn resolve_index(&self, index: usize) -> usize {
4074 if self.masked {
4075 self.text.char_index_to_offset(index / MASK_CHAR.len_utf8())
4076 } else {
4077 index.min(self.text.len())
4078 }
4079 }
4080
4081 fn extend_selection(
4091 sel: &mut CursorSelection,
4092 offset: usize,
4093 word_range: Option<CursorSelection>,
4094 ) {
4095 if sel.reversed {
4096 sel.start = offset;
4097 } else {
4098 sel.end = offset;
4099 }
4100
4101 if sel.end < sel.start {
4102 sel.reversed = !sel.reversed;
4103 std::mem::swap(&mut sel.start, &mut sel.end);
4104 }
4105
4106 if let Some(word_range) = word_range {
4107 if sel.start > word_range.start {
4108 sel.start = word_range.start;
4109 }
4110 if sel.end < word_range.end {
4111 sel.end = word_range.end;
4112 }
4113 }
4114 }
4115
4116 pub(crate) fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
4118 self.select_to_with_affinity(offset, false, cx);
4119 }
4120
4121 pub(crate) fn select_to_with_affinity(
4128 &mut self,
4129 offset: usize,
4130 line_end_affinity: bool,
4131 cx: &mut Context<Self>,
4132 ) {
4133 M::clear_inline_completion(self, cx);
4134
4135 self.cursor_line_end_affinity = line_end_affinity;
4136 let offset = self.cursor_boundary(offset, Bias::Left);
4137 let word_range = self.selected_word_range;
4138 Self::extend_selection(self.active_selection_mut(), offset, word_range);
4139 let range = self.normalize_token_range(self.selected_range());
4140 self.set_selection(range.start, range.end);
4141
4142 if self.active_selection().is_empty() {
4143 self.update_preferred_column();
4144 }
4145 cx.notify()
4146 }
4147
4148 fn select_all_cursors_to(
4151 &mut self,
4152 f: impl Fn(&Self, &CursorSelection) -> usize,
4153 cx: &mut Context<Self>,
4154 ) {
4155 self.select_all_cursors_to_with_affinity(|s, sel| (f(s, sel), false), false, cx);
4156 }
4157
4158 fn select_all_cursors_to_with_affinity(
4161 &mut self,
4162 f: impl Fn(&Self, &CursorSelection) -> (usize, bool),
4163 preserve_column: bool,
4164 cx: &mut Context<Self>,
4165 ) {
4166 self.pause_blink_cursor(cx);
4167 self.undo_manager.break_transaction_coalescing();
4168 M::clear_inline_completion(self, cx);
4169
4170 let mut active_affinity = false;
4171 let new_selections: Vec<CursorSelection> = self
4172 .selections
4173 .iter()
4174 .map(|sel| {
4175 let (offset, affinity) = f(self, sel);
4176 if sel.id == self.active_selection().id {
4177 active_affinity = affinity;
4178 }
4179 let offset = self.cursor_boundary(offset, Bias::Left);
4180 let mut new_sel = *sel;
4181 Self::extend_selection(&mut new_sel, offset, None);
4182 let range = self.normalize_token_range(new_sel.start..new_sel.end);
4183 new_sel.start = range.start;
4184 new_sel.end = range.end;
4185 if !preserve_column {
4186 new_sel.column_anchor =
4187 self.preferred_column_for_with_affinity(new_sel.cursor_offset(), affinity);
4188 } else if new_sel.column_anchor.is_none() {
4189 new_sel.column_anchor = self.preferred_column_for_with_affinity(
4190 sel.cursor_offset(),
4191 self.line_end_affinity_for(sel),
4192 );
4193 }
4194 new_sel
4195 })
4196 .collect();
4197 self.cursor_line_end_affinity = active_affinity;
4198 self.selections.replace_all(new_selections);
4199 self.selections.merge_overlapping();
4200
4201 self.scroll_to(self.cursor(), None, cx);
4202 cx.notify()
4203 }
4204
4205 pub fn unselect(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4207 self.undo_manager.break_transaction_coalescing();
4208 let offset = self.cursor();
4209 self.set_cursor_to(offset);
4210 cx.notify()
4211 }
4212
4213 #[inline]
4214 pub(super) fn offset_from_utf16(&self, offset: usize) -> usize {
4215 self.text.offset_utf16_to_offset(offset)
4216 }
4217
4218 #[inline]
4219 pub(super) fn offset_to_utf16(&self, offset: usize) -> usize {
4220 self.text.offset_to_offset_utf16(offset)
4221 }
4222
4223 #[inline]
4224 pub(crate) fn range_to_utf16(&self, range: &Range<usize>) -> Range<usize> {
4225 self.offset_to_utf16(range.start)..self.offset_to_utf16(range.end)
4226 }
4227
4228 #[inline]
4229 pub(super) fn range_from_utf16(&self, range_utf16: &Range<usize>) -> Range<usize> {
4230 self.offset_from_utf16(range_utf16.start)..self.offset_from_utf16(range_utf16.end)
4231 }
4232
4233 fn clamp_offset_to_visible_backward(&self, offset: usize) -> usize {
4236 let line = self.text.offset_to_point(offset).row;
4237 if self.display_map.is_buffer_line_hidden(line) {
4238 for fold in self.display_map.folded_ranges() {
4239 if line > fold.start_line && line <= fold.end_line {
4240 return self.text.line_end_offset(fold.start_line);
4241 }
4242 }
4243 }
4244 offset
4245 }
4246
4247 fn clamp_offset_to_visible_forward(&self, offset: usize) -> usize {
4250 let line = self.text.offset_to_point(offset).row;
4251 if self.display_map.is_buffer_line_hidden(line) {
4252 for fold in self.display_map.folded_ranges() {
4253 if line > fold.start_line && line <= fold.end_line {
4254 return self.text.line_start_offset(fold.end_line);
4255 }
4256 }
4257 }
4258 offset
4259 }
4260
4261 pub(super) fn cursor_boundary(&self, offset: usize, bias: Bias) -> usize {
4264 let offset = self.token_boundary(self.text.clip_offset(offset, bias), bias);
4265 if offset > 0
4266 && self.text.char_at(offset - 1) == Some('\r')
4267 && self.text.char_at(offset) == Some('\n')
4268 {
4269 if bias == Bias::Left {
4270 offset - 1
4271 } else {
4272 offset + 1
4273 }
4274 } else {
4275 offset
4276 }
4277 }
4278
4279 pub(super) fn previous_boundary(&self, offset: usize) -> usize {
4280 let offset =
4281 self.cursor_boundary(previous_grapheme_boundary(&self.text, offset), Bias::Left);
4282 self.clamp_offset_to_visible_backward(offset)
4283 }
4284
4285 pub(super) fn next_boundary(&self, offset: usize) -> usize {
4286 let offset = self.cursor_boundary(next_grapheme_boundary(&self.text, offset), Bias::Right);
4287 self.clamp_offset_to_visible_forward(offset)
4288 }
4289
4290 pub(crate) fn show_cursor(&self, window: &Window, cx: &App) -> bool {
4292 (self.focus_handle.is_focused(window) || M::is_context_menu_open(self, cx))
4293 && !self.disabled
4294 && self.blink_cursor.read(cx).visible()
4295 && window.is_window_active()
4296 }
4297
4298 fn on_focus(&mut self, _: &mut Window, cx: &mut Context<Self>) {
4299 self.blink_cursor.update(cx, |cursor, cx| {
4300 cursor.start(cx);
4301 });
4302 cx.emit(InputEvent::Focus);
4303 }
4304
4305 fn on_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4306 self.cancel_mouse_gesture(cx);
4307 self.revealed_viewport = None;
4308 if M::is_context_menu_open(self, cx) {
4309 return;
4310 }
4311
4312 M::hide_context_menu(self, cx);
4313 self.undo_manager.break_transaction_coalescing();
4314
4315 M::clear_hover_state(self, cx);
4319 self.diagnostic_popover = None;
4320 M::clear_inline_completion(self, cx);
4321 self.dismiss_touch_selection(cx);
4322 self.blink_cursor.update(cx, |cursor, cx| {
4323 cursor.stop(cx);
4324 });
4325 self.clamp_number_value(window, cx);
4326 cx.emit(InputEvent::Blur);
4327 cx.notify();
4328 }
4329
4330 fn clamp_number_value(&mut self, window: &mut Window, cx: &mut Context<Self>) {
4335 if !self.is_single_line() {
4336 return;
4337 }
4338 if !matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4339 return;
4340 }
4341 if self.number_min.is_none() && self.number_max.is_none() {
4342 return;
4343 }
4344
4345 let Ok(value) = self.unmask_value().parse::<f64>() else {
4346 return;
4347 };
4348
4349 let clamped = match (self.number_min, self.number_max) {
4350 (Some(min), _) if value < min => min,
4351 (_, Some(max)) if value > max => max,
4352 _ => return,
4353 };
4354
4355 let new_text = clamped.to_string();
4358 if !self.is_valid_input(&new_text, cx) {
4359 return;
4360 }
4361
4362 let range = self.range_to_utf16(&(0..self.text.len()));
4363 self.replace_text_in_range_silent(Some(range), &new_text, window, cx);
4364 }
4365
4366 pub(super) fn pause_blink_cursor(&mut self, cx: &mut Context<Self>) {
4367 self.blink_cursor.update(cx, |cursor, cx| {
4368 cursor.pause(cx);
4369 });
4370 }
4371
4372 pub(super) fn cancel_mouse_gesture(&mut self, cx: &mut Context<Self>) {
4373 let was_dragging = self.selecting || self.column_select_start.is_some();
4374 self.selecting = false;
4375 self.column_select_start = None;
4376 self.auto_scroll.stop();
4377 if was_dragging {
4378 cx.notify();
4379 }
4380 }
4381
4382 pub(super) fn on_drag_move(
4383 &mut self,
4384 event: &MouseMoveEvent,
4385 window: &mut Window,
4386 cx: &mut Context<Self>,
4387 ) {
4388 if event.pressed_button != Some(MouseButton::Left) {
4389 self.cancel_mouse_gesture(cx);
4390 return;
4391 }
4392 if self.text.len() == 0 {
4393 return;
4394 }
4395
4396 if self.last_layout.is_none() {
4397 return;
4398 }
4399
4400 if !self.focus_handle.is_focused(window) {
4401 return;
4402 }
4403
4404 if !self.selecting {
4405 return;
4406 }
4407
4408 self.auto_scroll.last_drag_position = Some(event.position);
4409 let (offset, line_end_affinity, columns_past_line_end) =
4410 self.resolve_mouse_position(event.position);
4411 if let Some(start) = self.column_select_start {
4412 let end = ColumnarPoint::new(offset, columns_past_line_end);
4413 self.build_columnar_selection(start, end, cx);
4414 } else {
4415 self.select_to_with_affinity(offset, line_end_affinity, cx);
4416 }
4417
4418 if !self.is_single_line() {
4419 let delta = AutoScroll::compute_delta(event.position.y, self.input_bounds);
4420 let scroll_delta = delta.map(|d| -d);
4422 self.auto_scroll.set(scroll_delta, cx, |delta, state, cx| {
4423 state.scroll_by_y_f64(f64::from(f32::from(delta)), cx);
4424 if let Some(pos) = state.auto_scroll.last_drag_position {
4425 let (offset, line_end_affinity, columns_past_line_end) =
4426 state.resolve_mouse_position(pos);
4427 if let Some(start) = state.column_select_start {
4428 let end = ColumnarPoint::new(offset, columns_past_line_end);
4429 state.build_columnar_selection(start, end, cx);
4430 } else {
4431 state.select_to_with_affinity(offset, line_end_affinity, cx);
4432 }
4433 }
4434 });
4435 }
4436 }
4437
4438 pub(super) fn normalize_input<'a>(&self, new_text: &'a str) -> Cow<'a, str> {
4447 let normalized = if matches!(self.mask_pattern, MaskPattern::Number { .. }) {
4448 normalize_number_input(new_text)
4449 } else {
4450 Cow::Borrowed(new_text)
4451 };
4452
4453 if self.is_single_line() && normalized.contains(['\n', '\r', '\t']) {
4454 Cow::Owned(normalized.replace(['\n', '\r', '\t'], ""))
4455 } else {
4456 normalized
4457 }
4458 }
4459
4460 pub(crate) fn is_valid_input(&self, new_text: &str, cx: &mut Context<Self>) -> bool {
4461 if new_text.is_empty() {
4462 return true;
4463 }
4464
4465 if let Some(validate) = &self.validate {
4466 if !validate(new_text, cx) {
4467 return false;
4468 }
4469 }
4470
4471 if !self.mask_pattern.is_valid(new_text) {
4472 return false;
4473 }
4474
4475 let Some(pattern) = &self.pattern else {
4476 return true;
4477 };
4478
4479 pattern.is_match(new_text)
4480 }
4481
4482 pub fn mask_pattern(mut self, pattern: impl Into<MaskPattern>) -> Self {
4492 self.mask_pattern = pattern.into();
4493 self.mask_pattern_set = true;
4494 if let Some(placeholder) = self.mask_pattern.placeholder() {
4495 self.placeholder = placeholder.into();
4496 }
4497 self
4498 }
4499
4500 pub fn set_mask_pattern(
4501 &mut self,
4502 pattern: impl Into<MaskPattern>,
4503 _: &mut Window,
4504 cx: &mut Context<Self>,
4505 ) {
4506 self.mask_pattern = pattern.into();
4507 self.mask_pattern_set = true;
4508 if let Some(placeholder) = self.mask_pattern.placeholder() {
4509 self.placeholder = placeholder.into();
4510 }
4511 cx.notify();
4512 }
4513
4514 pub fn ensure_number_mask(&mut self) {
4516 if self.mask_pattern_set {
4517 return;
4518 }
4519 self.mask_pattern = MaskPattern::Number {
4520 separator: None,
4521 fraction: None,
4522 };
4523 }
4524
4525 pub(super) fn set_input_bounds(&mut self, new_bounds: Bounds<Pixels>, cx: &mut Context<Self>) {
4526 let wrap_width_changed = self.input_bounds.size.width != new_bounds.size.width;
4527 self.input_bounds = new_bounds;
4528
4529 if let Some(last_layout) = self.last_layout.as_ref() {
4531 if wrap_width_changed {
4532 let wrap_width = if !self.soft_wrap {
4533 None
4535 } else {
4536 last_layout.wrap_width
4537 };
4538
4539 self.display_map.on_layout_changed(wrap_width, cx);
4540 if self.is_multi_line() {
4541 self.mode.update_auto_grow(&self.display_map);
4542 }
4543 cx.notify();
4544 }
4545 }
4546 }
4547
4548 pub fn selected_text(&self) -> RopeSlice<'_> {
4553 let range_utf16 = self.range_to_utf16(&self.selected_range());
4554 let range = self.range_from_utf16(&range_utf16);
4555 self.text.slice(range)
4556 }
4557
4558 pub fn range_to_bounds(&self, range: &Range<usize>) -> Option<Bounds<Pixels>> {
4562 let Some(last_layout) = self.last_layout.as_ref() else {
4563 return None;
4564 };
4565
4566 let Some(last_bounds) = self.last_bounds else {
4567 return None;
4568 };
4569
4570 let (_, _, start_pos) = self.line_and_position_for_offset(range.start);
4571 let (_, _, end_pos) = self.line_and_position_for_offset(range.end);
4572
4573 let Some(start_pos) = start_pos else {
4574 return None;
4575 };
4576 let Some(end_pos) = end_pos else {
4577 return None;
4578 };
4579
4580 Some(Bounds::from_corners(
4581 last_bounds.origin + start_pos,
4582 last_bounds.origin + end_pos + point(px(0.), last_layout.line_height),
4583 ))
4584 }
4585
4586 pub fn row_bounds(&self, row: usize) -> Option<Bounds<Pixels>> {
4592 let last_layout = self.last_layout.as_ref()?;
4593 let last_bounds = self.last_bounds?;
4594 let ix = last_layout.visible_buffer_lines.binary_search(&row).ok()?;
4595 let (top, height) = last_layout.row_extents().nth(ix)?;
4596
4597 Some(Bounds::new(
4598 point(self.input_bounds.origin.x, last_bounds.origin.y + top),
4599 gpui::size(self.input_bounds.size.width, height),
4600 ))
4601 }
4602
4603 pub fn hit_test(&self, position: Point<Pixels>) -> Option<InputHit> {
4608 let last_layout = self.last_layout.as_ref()?;
4609 let last_bounds = self.last_bounds?;
4610 let beside = last_layout.row_at(position.y - last_bounds.origin.y);
4611 let spacer = beside.is_some_and(|(_, spacer)| spacer);
4612
4613 if self
4614 .last_gutter_bounds
4615 .is_some_and(|gutter| gutter.contains(&position))
4616 {
4617 let folding = self.mode.is_folding();
4618 let column = last_layout.gutter_order.iter().copied().find(|&column| {
4619 let (x, width) = super::element::gutter_column(last_layout, folding, column);
4620 let left = self.input_bounds.origin.x + x;
4621 position.x >= left && position.x < left + width
4622 });
4623 return Some(InputHit {
4624 area: InputHitArea::Gutter { column },
4625 row: beside.map(|(row, _)| row),
4626 spacer,
4627 });
4628 }
4629
4630 let paddings = self.editor_paddings;
4631 let ghost_height = last_layout.ghost_lines.map_or(px(0.), |(_, height)| height);
4632 let outer = Bounds::from_corners(
4633 self.input_bounds.origin - point(paddings.left, paddings.top),
4634 self.input_bounds.bottom_right()
4635 + point(paddings.right, paddings.bottom + ghost_height),
4636 );
4637 if !outer.contains(&position) {
4638 return None;
4639 }
4640 let (offset, _) = self.index_for_mouse_position(position);
4641 Some(InputHit {
4642 area: InputHitArea::Text { offset },
4643 row: Some(self.text.offset_to_point(offset).row),
4644 spacer,
4645 })
4646 }
4647
4648 pub(crate) fn replace_text_in_range_silent(
4652 &mut self,
4653 range_utf16: Option<Range<usize>>,
4654 new_text: &str,
4655 window: &mut Window,
4656 cx: &mut Context<Self>,
4657 ) {
4658 self.silent_replace_text = true;
4659 self.replace_text_in_range(range_utf16, new_text, window, cx);
4660 self.silent_replace_text = false;
4661 }
4662
4663 pub(crate) fn replace_text_in_ranges(
4668 &mut self,
4669 edits: &[(Range<usize>, String)],
4670 window: &mut Window,
4671 cx: &mut Context<Self>,
4672 ) {
4673 if !self.is_editable() || edits.is_empty() {
4674 return;
4675 }
4676
4677 M::hide_context_menu(self, cx);
4680 M::clear_inline_completion(self, cx);
4681
4682 let mut sorted: Vec<(Range<usize>, &str)> = edits
4685 .iter()
4686 .map(|(range, text)| (self.normalize_token_range(range.clone()), text.as_str()))
4687 .collect();
4688 sorted.sort_by_key(|edit| std::cmp::Reverse(edit.0.start));
4689 if !self.token_spans().is_empty() {
4690 let mut merged: Vec<(Range<usize>, &str)> = Vec::with_capacity(sorted.len());
4691 for (range, text) in sorted {
4692 if let Some(last) = merged
4693 .last_mut()
4694 .filter(|last| range.end > last.0.start || range == last.0)
4695 {
4696 last.0.start = range.start.min(last.0.start);
4697 last.0.end = range.end.max(last.0.end);
4698 } else {
4699 merged.push((range, text));
4700 }
4701 }
4702 sorted = merged;
4703 }
4704
4705 #[cfg(debug_assertions)]
4706 for pair in sorted.windows(2) {
4707 debug_assert!(
4708 pair[1].0.end <= pair[0].0.start,
4709 "replace_text_in_ranges requires disjoint ranges"
4710 );
4711 }
4712
4713 let requested_intent = self.undo_manager.take_pending_intent();
4717 let selection_before = *self.active_selection();
4718 let original_selections: Vec<CursorSelection> = self.selections.iter().copied().collect();
4719 let selections_before: Vec<CursorSelection> = self
4723 .selections
4724 .iter()
4725 .map(|selection| {
4726 Self::collapse_for_intent(
4727 requested_intent.unwrap_or(EditIntent::Atomic),
4728 *selection,
4729 &(selection.start..selection.end),
4730 )
4731 })
4732 .collect();
4733 let group = sorted.len() > 1;
4734 if group {
4735 self.undo_manager.begin_transaction();
4736 }
4737
4738 let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
4739 let mut recorded = false;
4740 let mut highlighter_edits = Vec::new();
4743 let accumulate_replay_edits = self.replaying_history && !self.emit_events;
4747 if !accumulate_replay_edits {
4748 self.last_input_edits.clear();
4749 }
4750 for (range, new_text) in &sorted {
4751 let old_text = self.text.clone();
4752 self.mode.adjust_auto_closed_pair(range, new_text.len());
4753 self.text.replace(range.clone(), new_text);
4754
4755 M::adjust_annotations(self, range, new_text.len());
4756 recorded |= self.push_history(
4757 &old_text,
4758 range,
4759 new_text,
4760 requested_intent,
4761 selection_before,
4762 None,
4763 );
4764
4765 self.display_map
4767 .adjust_folds_for_edit(&old_text, range, new_text);
4768 if *range == (0..old_text.len()) {
4769 self.adopt_gutter_wrap_width(&old_text, window);
4770 }
4771 self.display_map
4772 .on_text_changed(&self.text, range, &Rope::from(*new_text), cx);
4773
4774 let edit = super::mode::replacement_input_edit(&old_text, &self.text, range, new_text);
4775 if self.emit_events || self.replaying_history {
4776 self.last_input_edits.push((edit, self.text.clone()));
4777 }
4778
4779 if group {
4780 if self.is_code_editor() {
4781 highlighter_edits.push((edit, self.text.clone()));
4782 }
4783 } else {
4784 self.mode.update_highlighter(
4785 super::mode::HighlighterUpdate {
4786 selected_range: range,
4787 old_text: &old_text,
4788 new_text: &self.text,
4789 change_text: new_text,
4790 force: true,
4791 input_edit: Some(edit),
4792 },
4793 window,
4794 cx,
4795 );
4796
4797 self.update_fold_candidates_incremental(range, new_text);
4798 }
4799 }
4800
4801 if group {
4802 self.mode
4803 .update_highlighter_batch::<M>(&highlighter_edits, window, cx);
4804
4805 let mut shift = 0isize;
4809 for (range, new_text) in sorted.iter().rev() {
4810 let start = (range.start as isize + shift) as usize;
4811 self.update_fold_candidates_incremental(&(start..start), new_text);
4812 shift += new_text.len() as isize - range.len() as isize;
4813 }
4814
4815 self.undo_manager.commit_transaction();
4816 }
4817
4818 if let Some(diagnostics) = self.mode.diagnostics_mut() {
4820 diagnostics.reset(&self.text)
4821 }
4822 M::refresh_language_features(self, window, cx);
4823 self.update_search(cx);
4824
4825 let mut ascending: Vec<(Range<usize>, &str)> = sorted.clone();
4828 ascending.sort_by_key(|edit| edit.0.start);
4829 let text_len = self.text.len();
4830 let mut delta: isize = 0;
4831 let mut edit_results = Vec::with_capacity(ascending.len());
4832 for (range, new_text) in &ascending {
4833 let offset = ((range.start as isize + delta) as usize + new_text.len()).min(text_len);
4834 edit_results.push((range.clone(), offset));
4835 delta += new_text.len() as isize - (range.end as isize - range.start as isize);
4836 }
4837
4838 let mut used = vec![false; edit_results.len()];
4839 let mut new_selections: Vec<CursorSelection> = Vec::with_capacity(ascending.len());
4840 for selection in original_selections {
4841 if let Ok(index) = edit_results
4842 .binary_search_by_key(&(selection.start, selection.end), |(range, _)| {
4843 (range.start, range.end)
4844 })
4845 && !used[index]
4846 {
4847 let offset = edit_results[index].1;
4848 used[index] = true;
4849 let mut selection = selection;
4850 selection.place_at(offset, None);
4851 new_selections.push(selection);
4852 }
4853 }
4854 for (index, (_, offset)) in edit_results.into_iter().enumerate() {
4855 if !used[index] {
4856 new_selections.push(CursorSelection::new(
4857 self.selections.generate_id(),
4858 offset,
4859 offset,
4860 ));
4861 }
4862 }
4863 self.selections.replace_all(new_selections);
4864 self.selections.merge_overlapping();
4865
4866 let selections_after: Vec<CursorSelection> = self.selections.iter().copied().collect();
4868 if recorded {
4869 self.undo_manager.record_auto_closed_pairs(
4870 auto_closed_pairs_before,
4871 self.mode.auto_closed_pairs().clone(),
4872 );
4873 self.undo_manager
4874 .record_selections(selections_before, selections_after);
4875 }
4876
4877 self.ime_marked_range.take();
4878 self.update_preferred_column();
4879 self.dismiss_touch_selection(cx);
4880 if self.is_multi_line() {
4881 self.mode.update_auto_grow(&self.display_map);
4882 }
4883 if self.emit_events {
4884 self.emit_change(cx);
4885 }
4886 cx.notify();
4887 }
4888
4889 fn adopt_gutter_wrap_width(&mut self, old_text: &Rope, window: &mut Window) {
4893 let Some(wrap_width) = self.display_map.wrap_width() else {
4894 return;
4895 };
4896 let old_digits = line_number_len(old_text.lines_len());
4897 let new_digits = line_number_len(self.text.lines_len());
4898 if !self.mode.line_number() || old_digits == new_digits {
4899 return;
4900 }
4901 let (font, font_size) = self.display_map.font();
4902 let font = font.clone();
4903 let old_width = line_number_digits_width(old_digits, font.clone(), font_size, window);
4904 let new_width = line_number_digits_width(new_digits, font, font_size, window);
4905 self.display_map
4906 .prepare_wrap_width(wrap_width - (new_width - old_width));
4907 }
4908
4909 fn update_fold_candidates(&mut self) {
4912 if !self.mode.is_folding() {
4913 return;
4914 }
4915
4916 let Some(highlighter_rc) = self.mode.highlighter() else {
4917 return;
4918 };
4919
4920 let highlighter = highlighter_rc.borrow();
4921 let Some(highlighter) = highlighter.as_ref() else {
4922 return;
4923 };
4924
4925 let fold_ranges = highlighter.fold_ranges(&self.text);
4926 self.display_map.set_fold_candidates(fold_ranges);
4927 }
4928
4929 fn update_fold_candidates_incremental(&mut self, edit_range: &Range<usize>, new_text: &str) {
4932 if !self.mode.is_folding() {
4933 return;
4934 }
4935
4936 let Some(highlighter_rc) = self.mode.highlighter() else {
4937 return;
4938 };
4939
4940 let highlighter = highlighter_rc.borrow();
4941 let Some(highlighter) = highlighter.as_ref() else {
4942 return;
4943 };
4944
4945 let new_end = edit_range.start + new_text.len();
4947 self.display_map.update_fold_candidates_for_edit(
4948 |range, text| highlighter.fold_ranges_for_edit(range, text),
4949 edit_range.start..new_end,
4950 &self.text,
4951 );
4952 }
4953}
4954
4955impl<M: InputModeKind> EntityInputHandler for InputBaseState<M> {
4956 fn accepts_text_input(&self, window: &mut Window, _cx: &mut Context<Self>) -> bool {
4957 self.focus_handle.is_focused(window)
4958 }
4959
4960 fn text_for_range(
4961 &mut self,
4962 range_utf16: Range<usize>,
4963 adjusted_range: &mut Option<Range<usize>>,
4964 _window: &mut Window,
4965 _cx: &mut Context<Self>,
4966 ) -> Option<String> {
4967 let range = self.range_from_utf16(&range_utf16);
4968 let range_utf16 = self.range_to_utf16(&range);
4969 let utf16_len = range_utf16.len();
4970 adjusted_range.replace(range_utf16);
4971 if self.masked {
4972 return Some(MASK_CHAR.to_string().repeat(utf16_len));
4974 }
4975 Some(self.text.slice(range).to_string())
4976 }
4977
4978 fn selected_text_range(
4979 &mut self,
4980 _ignore_disabled_input: bool,
4981 _window: &mut Window,
4982 _cx: &mut Context<Self>,
4983 ) -> Option<UTF16Selection> {
4984 Some(UTF16Selection {
4985 range: self.range_to_utf16(&self.selected_range()),
4986 reversed: self.active_selection().reversed,
4987 })
4988 }
4989
4990 fn text_length_utf16(
4996 &mut self,
4997 _window: &mut Window,
4998 _cx: &mut Context<Self>,
4999 ) -> Option<usize> {
5000 Some(self.offset_to_utf16(self.text.len()))
5001 }
5002
5003 fn set_selected_text_range(
5010 &mut self,
5011 range_utf16: Range<usize>,
5012 _window: &mut Window,
5013 cx: &mut Context<Self>,
5014 ) {
5015 let previous = self.selected_range();
5016 let was_reversed = self.active_selection().reversed;
5017 let range = self.range_from_utf16(&range_utf16);
5018 let range = range.start.min(range.end)..range.start.max(range.end);
5019 self.set_selected_range(range, cx);
5020
5021 let range = self.selected_range();
5022 let reversed = if range == previous {
5023 was_reversed
5024 } else if !range.is_empty() && range.end == previous.start {
5025 true
5026 } else if !range.is_empty() && range.start == previous.end {
5027 false
5028 } else {
5029 !range.is_empty() && range.start != previous.start && range.end == previous.end
5030 };
5031 self.active_selection_mut().reversed = reversed;
5032 self.scroll_to(self.cursor(), None, cx);
5033 cx.notify();
5034 }
5035
5036 fn marked_text_range(
5037 &self,
5038 _window: &mut Window,
5039 _cx: &mut Context<Self>,
5040 ) -> Option<Range<usize>> {
5041 self.ime_marked_range
5042 .map(|range| self.range_to_utf16(&range.into()))
5043 }
5044
5045 fn unmark_text(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
5046 let had_marked_range = self.ime_marked_range.take().is_some();
5047 self.undo_manager.commit_transaction();
5048 if self.ime_original_text.as_ref() == Some(&self.text) {
5052 self.ime_original_text = None;
5053 } else if self.ime_original_text.is_some() && self.emit_events {
5054 self.emit_change(cx);
5055 }
5056 if had_marked_range {
5057 cx.notify();
5058 }
5059 }
5060
5061 fn replace_text_in_range(
5066 &mut self,
5067 range_utf16: Option<Range<usize>>,
5068 new_text: &str,
5069 window: &mut Window,
5070 cx: &mut Context<Self>,
5071 ) {
5072 let requested_intent = self.undo_manager.take_pending_intent();
5073 if !self.is_editable() {
5074 return;
5075 }
5076 let selection_before = *self.active_selection();
5077 let ends_composition = self.ime_marked_range.is_some();
5080
5081 self.pause_blink_cursor(cx);
5082
5083 let new_text = if self.replaying_history {
5087 Cow::Borrowed(new_text)
5088 } else {
5089 self.normalize_input(new_text)
5090 };
5091 let new_text: &str = &new_text;
5092
5093 let range = range_utf16
5094 .as_ref()
5095 .map(|range_utf16| self.range_from_utf16(range_utf16))
5096 .or(self.ime_marked_range.map(|range| {
5097 let range = self.range_to_utf16(&(range.start..range.end));
5098 self.range_from_utf16(&range)
5099 }))
5100 .unwrap_or(self.selected_range());
5101 let range = self.normalize_token_range(range);
5102
5103 if range.is_empty()
5109 && range.start == self.cursor()
5110 && self.ime_marked_range.is_none()
5111 && !self.silent_replace_text
5112 && self.is_code_editor()
5113 && self.selections.is_single()
5114 && self.active_selection().is_empty()
5115 {
5116 if let Some(target) = self.skip_over_target(new_text) {
5117 self.set_cursor_to(target);
5118 self.update_preferred_column();
5119 cx.notify();
5120 return;
5121 }
5122 }
5123
5124 if self.is_multi_line() {
5125 let multi_cursor = range_utf16.is_none()
5126 && self.ime_marked_range.is_none()
5127 && !self.selections.is_single();
5128 if multi_cursor {
5129 self.selections.merge_overlapping();
5130 let mut edits: Vec<(Range<usize>, String)> = self
5131 .selections
5132 .iter()
5133 .map(|sel| (sel.start..sel.end, new_text.to_string()))
5134 .collect();
5135 edits.sort_by_key(|(range, _)| range.start);
5136 let intent =
5140 requested_intent.unwrap_or_else(|| self.typing_intent(&edits, new_text));
5141 self.undo_manager.begin_transaction_with(intent);
5142 self.undo_manager.set_pending_intent(intent);
5143 self.replace_text_in_ranges(&edits, window, cx);
5144 self.undo_manager.commit_transaction();
5145 } else {
5146 if range_utf16.is_some() {
5147 self.selections.remove_all_but_active();
5148 }
5149 if let Some(intent) = requested_intent {
5150 self.undo_manager.set_pending_intent(intent);
5151 }
5152 if let Some((open_len, closer)) = self.auto_close_target(&range, new_text) {
5153 let replacement = format!("{new_text}{closer}");
5155 self.replace_text_in_ranges(&[(range.clone(), replacement)], window, cx);
5156 let cursor = range.start + new_text.len();
5157 self.mode.track_auto_closed_pair(
5158 cursor - open_len..cursor,
5159 cursor..cursor + closer.len(),
5160 );
5161 self.undo_manager
5162 .record_auto_closed_pairs_after(self.mode.auto_closed_pairs().clone());
5163 self.set_cursor_to(cursor);
5164 self.update_preferred_column();
5165 self.undo_manager.record_selections(
5166 vec![selection_before],
5167 self.selections.iter().copied().collect(),
5168 );
5169 } else {
5170 self.replace_text_in_ranges(
5171 &[(range.clone(), new_text.to_string())],
5172 window,
5173 cx,
5174 );
5175 }
5176 }
5177 if ends_composition {
5178 self.undo_manager.commit_transaction();
5179 }
5180
5181 if !self.silent_replace_text {
5182 M::on_text_typed(self, &range, new_text, window, cx);
5183 }
5184 return;
5185 }
5186
5187 let old_text = self.text.clone();
5189 let accumulate_replay_edits = self.replaying_history && !self.emit_events;
5193 if !accumulate_replay_edits {
5194 self.last_input_edits.clear();
5195 }
5196 self.mode.adjust_auto_closed_pair(&range, new_text.len());
5197 self.text.replace(range.clone(), new_text);
5198
5199 let mut new_offset = (range.start + new_text.len()).min(self.text.len());
5200
5201 let mut mask_changed = false;
5204
5205 if self.is_single_line() {
5206 let pending_text = self.text.to_string();
5207 if !self.replaying_history
5213 && !self.validated_token_edit
5214 && !self.is_valid_input(&pending_text, cx)
5215 && self.is_valid_input(&old_text.to_string(), cx)
5216 {
5217 self.text = old_text;
5218 return;
5219 }
5220
5221 if !self.replaying_history && !self.mask_pattern.is_none() {
5222 let mask_text = self.mask_pattern.mask(&pending_text);
5223 mask_changed = mask_text.as_str() != pending_text;
5224 self.text = Rope::from(mask_text.as_str());
5225 let new_text_len =
5226 (new_text.len() + mask_text.len()).saturating_sub(pending_text.len());
5227 new_offset = (range.start + new_text_len).min(mask_text.len());
5228 }
5229 }
5230
5231 if mask_changed {
5232 M::reset_annotations(self);
5235 } else {
5236 M::adjust_annotations(self, &range, new_text.len());
5237 }
5238 if mask_changed {
5239 self.push_history(
5243 &old_text,
5244 &(0..old_text.len()),
5245 &self.text.to_string(),
5246 Some(EditIntent::Atomic),
5247 selection_before,
5248 Some((new_offset..new_offset).into()),
5249 );
5250 } else {
5251 self.push_history(
5252 &old_text,
5253 &range,
5254 &new_text,
5255 requested_intent,
5256 selection_before,
5257 None,
5258 );
5259 }
5260 if let Some(diagnostics) = self.mode.diagnostics_mut() {
5261 diagnostics.reset(&self.text)
5262 }
5263 self.display_map
5265 .adjust_folds_for_edit(&old_text, &range, new_text);
5266 self.display_map
5267 .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5268
5269 let edit = if mask_changed {
5270 Self::full_input_edit(&old_text, &self.text)
5271 } else {
5272 super::mode::replacement_input_edit(&old_text, &self.text, &range, new_text)
5273 };
5274 if self.emit_events || self.replaying_history {
5275 self.last_input_edits.push((edit, self.text.clone()));
5276 }
5277
5278 self.mode.update_highlighter::<M>(
5279 super::mode::HighlighterUpdate {
5280 selected_range: &range,
5281 old_text: &old_text,
5282 new_text: &self.text,
5283 change_text: &new_text,
5284 force: true,
5285 input_edit: Some(edit),
5286 },
5287 window,
5288 cx,
5289 );
5290
5291 self.update_fold_candidates_incremental(&range, new_text);
5292 M::refresh_language_features(self, window, cx);
5293 self.set_cursor_to(new_offset);
5294 self.ime_marked_range.take();
5295 if ends_composition {
5301 self.undo_manager
5302 .record_selections(vec![selection_before], vec![*self.active_selection()]);
5303 self.undo_manager.commit_transaction();
5304 }
5305 self.update_preferred_column();
5306 self.update_search(cx);
5307 self.dismiss_touch_selection(cx);
5308 if self.is_multi_line() {
5309 self.mode.update_auto_grow(&self.display_map);
5310 }
5311 if !self.silent_replace_text {
5312 M::on_text_typed(self, &range, &new_text, window, cx);
5313 }
5314 if self.emit_events {
5315 self.emit_change(cx);
5316 }
5317 cx.notify();
5318 }
5319
5320 fn replace_and_mark_text_in_range(
5322 &mut self,
5323 range_utf16: Option<Range<usize>>,
5324 new_text: &str,
5325 new_selected_range_utf16: Option<Range<usize>>,
5326 window: &mut Window,
5327 cx: &mut Context<Self>,
5328 ) {
5329 let requested_intent = self.undo_manager.take_pending_intent();
5330 if !self.is_editable() {
5331 return;
5332 }
5333 let selection_before = *self.active_selection();
5334
5335 let starts_composition = self.ime_marked_range.is_none();
5336 if starts_composition {
5337 self.undo_manager.break_transaction_coalescing();
5340 self.undo_manager.begin_transaction();
5341 }
5342
5343 self.selections.remove_all_but_active();
5345
5346 M::reset_language_features(self);
5347
5348 let new_text = if self.replaying_history {
5350 Cow::Borrowed(new_text)
5351 } else {
5352 self.normalize_input(new_text)
5353 };
5354 let new_text: &str = &new_text;
5355
5356 let range = range_utf16
5357 .as_ref()
5358 .map(|range_utf16| self.range_from_utf16(range_utf16))
5359 .or(self.ime_marked_range.map(|range| {
5360 let range = self.range_to_utf16(&(range.start..range.end));
5361 self.range_from_utf16(&range)
5362 }))
5363 .unwrap_or(self.selected_range());
5364 let range = self.normalize_token_range(range);
5365
5366 let auto_closed_pairs_before = self.mode.auto_closed_pairs().clone();
5367 let old_text = self.text.clone();
5368 self.last_input_edits.clear();
5371 self.mode.adjust_auto_closed_pair(&range, new_text.len());
5372 self.text.replace(range.clone(), new_text);
5373
5374 if self.is_single_line() {
5375 let pending_text = self.text.to_string();
5376 if !self.replaying_history
5378 && !self.validated_token_edit
5379 && !self.is_valid_input(&pending_text, cx)
5380 && self.is_valid_input(&old_text.to_string(), cx)
5381 {
5382 self.text = old_text;
5383 if starts_composition {
5384 self.undo_manager.commit_transaction();
5385 }
5386 return;
5387 }
5388 }
5389
5390 if self.ime_original_text.is_none() {
5391 self.ime_original_text = Some(old_text.clone());
5392 }
5393 M::adjust_annotations(self, &range, new_text.len());
5394 if let Some(diagnostics) = self.mode.diagnostics_mut() {
5395 diagnostics.reset(&self.text)
5396 }
5397 self.display_map
5399 .adjust_folds_for_edit(&old_text, &range, new_text);
5400 self.display_map
5401 .on_text_changed(&self.text, &range, &Rope::from(new_text), cx);
5402
5403 self.mode.update_highlighter::<M>(
5404 super::mode::HighlighterUpdate {
5405 selected_range: &range,
5406 old_text: &old_text,
5407 new_text: &self.text,
5408 change_text: &new_text,
5409 force: true,
5410 input_edit: None,
5411 },
5412 window,
5413 cx,
5414 );
5415
5416 self.update_fold_candidates_incremental(&range, new_text);
5417 M::refresh_language_features(self, window, cx);
5418 if new_text.is_empty() {
5419 self.set_cursor_to(range.start);
5421 self.ime_marked_range = None;
5422 } else {
5423 self.ime_marked_range = Some((range.start..range.start + new_text.len()).into());
5424 let new_range = new_selected_range_utf16
5425 .as_ref()
5426 .map(|range_utf16| {
5427 let new_text = Rope::from(new_text);
5428 range.start + new_text.offset_utf16_to_offset(range_utf16.start)
5429 ..range.start + new_text.offset_utf16_to_offset(range_utf16.end)
5430 })
5431 .unwrap_or_else(|| range.start + new_text.len()..range.start + new_text.len());
5432 self.set_selection(new_range.start, new_range.end);
5433 }
5434 if self.is_multi_line() {
5435 self.mode.update_auto_grow(&self.display_map);
5436 }
5437 if self.push_history(
5438 &old_text,
5439 &range,
5440 new_text,
5441 requested_intent,
5442 selection_before,
5443 Some(*self.active_selection()),
5444 ) {
5445 self.undo_manager
5446 .record_selections(vec![selection_before], vec![*self.active_selection()]);
5447 self.undo_manager.record_auto_closed_pairs(
5448 auto_closed_pairs_before,
5449 self.mode.auto_closed_pairs().clone(),
5450 );
5451 }
5452 if new_text.is_empty() {
5453 self.undo_manager.commit_transaction();
5454 }
5455 cx.notify();
5456 }
5457
5458 fn bounds_for_range(
5460 &mut self,
5461 range_utf16: Range<usize>,
5462 bounds: Bounds<Pixels>,
5463 _window: &mut Window,
5464 _cx: &mut Context<Self>,
5465 ) -> Option<Bounds<Pixels>> {
5466 let last_layout = self.last_layout.as_ref()?;
5467 let line_height = last_layout.line_height;
5468 let range = self.range_from_utf16(&range_utf16);
5469
5470 let mut start_origin = None;
5471 let mut end_origin = None;
5472 let text_origin = point(last_layout.text_origin_x, px(0.));
5473 let mut y_offset = last_layout.visible_top;
5474
5475 let start_row = self
5476 .text
5477 .offset_to_point(range.start.min(self.text.len()))
5478 .row;
5479 let end_row = self
5480 .text
5481 .offset_to_point(range.end.min(self.text.len()))
5482 .row;
5483
5484 for (vi, line) in last_layout.lines.iter().enumerate() {
5485 if start_origin.is_some() && end_origin.is_some() {
5486 break;
5487 }
5488
5489 let (spacer_above, spacer_below) = last_layout.spacers(vi);
5490 y_offset += spacer_above;
5491 let buffer_line = last_layout.visible_buffer_lines[vi];
5492 let index_offset = last_layout.visible_line_byte_offsets[vi];
5493
5494 if start_origin.is_none() && buffer_line == start_row {
5495 let local_offset = range.start.saturating_sub(index_offset).min(line.len());
5496 let p = line
5497 .position_for_index(local_offset, last_layout, false)
5498 .unwrap_or_else(|| point(px(0.), px(0.)));
5499 start_origin = Some(p + point(px(0.), y_offset));
5500 }
5501
5502 if end_origin.is_none() && buffer_line == end_row {
5503 let local_offset = range.end.saturating_sub(index_offset).min(line.len());
5504 let p = line
5505 .position_for_index(local_offset, last_layout, false)
5506 .unwrap_or_else(|| point(px(0.), px(0.)));
5507 end_origin = Some(p + point(px(0.), y_offset));
5508 }
5509
5510 y_offset += line.size(line_height).height + spacer_below;
5511 }
5512
5513 let start_origin = start_origin.or_else(|| {
5514 let offset = self.last_cursor.or(Some(self.cursor()))?;
5515 let (_, _, origin) = self.line_and_position_for_offset(offset);
5516 origin.map(|origin| origin - text_origin)
5517 })?;
5518 let mut end_origin = end_origin.unwrap_or(start_origin);
5519 end_origin.y = start_origin.y;
5521 if end_origin.x <= start_origin.x {
5522 end_origin.x = start_origin.x + px(1.);
5523 }
5524
5525 Some(Bounds::from_corners(
5526 bounds.origin + text_origin + start_origin,
5527 bounds.origin + text_origin + point(end_origin.x, end_origin.y + line_height),
5529 ))
5530 }
5531
5532 fn character_index_for_point(
5533 &mut self,
5534 point: gpui::Point<Pixels>,
5535 _window: &mut Window,
5536 _cx: &mut Context<Self>,
5537 ) -> Option<usize> {
5538 let last_layout = self.last_layout.as_ref()?;
5539 let inner_point = self.last_bounds?.localize(&point)?
5542 - gpui::point(last_layout.text_origin_x, last_layout.visible_top);
5543
5544 let mut line_top = px(0.);
5545 for (vi, line) in last_layout.lines.iter().enumerate() {
5546 let (spacer_above, spacer_below) = last_layout.spacers(vi);
5547 line_top += spacer_above;
5548 let offset = last_layout.visible_line_byte_offsets[vi];
5549 let line_point = inner_point - gpui::point(px(0.), line_top);
5550 if let Some(utf8_index) = line.index_for_position(line_point, last_layout) {
5551 return Some(self.offset_to_utf16(self.resolve_index(offset + utf8_index)));
5552 }
5553 line_top += line.size(last_layout.line_height).height + spacer_below;
5554 }
5555
5556 None
5557 }
5558
5559 fn text_input_configuration(
5560 &mut self,
5561 _window: &mut Window,
5562 _cx: &mut Context<Self>,
5563 ) -> TextInputConfiguration {
5564 InputBaseState::text_input_configuration(self)
5565 }
5566}
5567
5568impl<M: InputModeKind> Focusable for InputBaseState<M> {
5569 fn focus_handle(&self, _cx: &App) -> FocusHandle {
5570 self.focus_handle.clone()
5571 }
5572}
5573
5574impl<M: InputModeKind> Render for InputBaseState<M> {
5575 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
5576 self.render_with_line_numbers((), window, cx)
5577 }
5578}
5579
5580impl<M: InputModeKind> InputBaseState<M> {
5581 pub(crate) fn render_with_line_numbers<R: EditorLineNumberRenderer>(
5582 &mut self,
5583 line_number_renderer: R,
5584 window: &mut Window,
5585 cx: &mut Context<Self>,
5586 ) -> impl IntoElement {
5587 self.editor_style = self
5590 .projected_editor_style
5591 .resolved(&crate::Theme::global(cx).tokens);
5592 let entity = cx.entity();
5593 let expose_full_text = self.exposes_full_accessibility_text();
5594 let exposed_text = self
5595 .accessibility
5596 .as_ref()
5597 .is_some_and(|accessibility| {
5598 expose_full_text
5599 && accessibility.value_exposed
5600 && !self.masked
5601 && (window.is_a11y_active() || cfg!(feature = "test-support"))
5602 })
5603 .then(|| self.text.to_string());
5604 let text_runs = self.accessibility_text_runs(exposed_text.as_deref(), window);
5605 if self._pending_update {
5606 self.mode.update_highlighter::<M>(
5607 super::mode::HighlighterUpdate {
5608 selected_range: &(0..0),
5609 old_text: &self.text,
5610 new_text: &self.text,
5611 change_text: "",
5612 force: false,
5613 input_edit: None,
5614 },
5615 window,
5616 cx,
5617 );
5618
5619 self.update_fold_candidates();
5620 M::refresh_language_features(self, window, cx);
5621 self._pending_update = false;
5622 }
5623
5624 let element = div()
5625 .id(EDITOR_ELEMENT_ID)
5626 .key_context(CONTEXT)
5627 .when_some(self.accessibility.as_ref(), |this, accessibility| {
5628 this.when_some(accessibility.role, |this, role| this.role(role))
5629 .when_some(accessibility.label.clone(), |this, label| {
5630 this.aria_label(label)
5631 })
5632 .when_some(accessibility.placeholder.clone(), |this, placeholder| {
5633 this.aria_placeholder(placeholder)
5634 })
5635 .when_some(accessibility.accessibility_id.clone(), |this, id| {
5636 this.accessibility_id(id)
5637 })
5638 .when_some(exposed_text, |this, text| this.aria_value(text))
5639 .when_some(text_runs, |this, runs| {
5640 this.a11y_synthetic_children(move |builder| runs.push(builder))
5641 })
5642 .on_a11y_action(gpui::AccessibleAction::Focus, {
5643 let entity = entity.clone();
5644 move |_, window, cx| {
5645 entity.update(cx, |state, cx| {
5646 state.handle_accessibility_focus(window, cx)
5647 });
5648 }
5649 })
5650 .when(self.is_editable() && expose_full_text, |this| {
5651 this.on_a11y_action(gpui::AccessibleAction::SetValue, {
5652 let entity = entity.clone();
5653 move |data, window, cx| {
5654 entity.update(cx, |state, cx| {
5655 state.handle_accessibility_set_value(data, window, cx)
5656 });
5657 }
5658 })
5659 })
5660 })
5661 .when(self.is_editable(), |this| {
5662 this.on_action(window.listener_for(&entity, InputBaseState::backspace))
5663 .on_action(window.listener_for(&entity, InputBaseState::delete))
5664 .on_action(
5665 window.listener_for(&entity, InputBaseState::delete_to_beginning_of_line),
5666 )
5667 .on_action(window.listener_for(&entity, InputBaseState::delete_to_end_of_line))
5668 .on_action(window.listener_for(&entity, InputBaseState::delete_previous_word))
5669 .on_action(window.listener_for(&entity, InputBaseState::delete_next_word))
5670 .on_action(window.listener_for(&entity, InputBaseState::enter))
5671 .on_action(window.listener_for(&entity, InputBaseState::escape))
5672 .on_action(window.listener_for(&entity, InputBaseState::paste))
5673 .on_action(window.listener_for(&entity, InputBaseState::cut))
5674 .on_action(window.listener_for(&entity, InputBaseState::correct_spelling))
5675 .on_action(window.listener_for(&entity, InputBaseState::learn_spelling))
5676 .on_action(window.listener_for(&entity, InputBaseState::undo))
5677 .on_action(window.listener_for(&entity, InputBaseState::redo))
5678 .when(self.is_multi_line(), |this| {
5679 this.on_action(window.listener_for(&entity, InputBaseState::indent_inline))
5680 .on_action(window.listener_for(&entity, InputBaseState::outdent_inline))
5681 .on_action(window.listener_for(&entity, InputBaseState::indent_block))
5682 .on_action(window.listener_for(&entity, InputBaseState::outdent_block))
5683 })
5684 })
5685 .on_action(window.listener_for(&entity, InputBaseState::left))
5686 .on_action(window.listener_for(&entity, InputBaseState::right))
5687 .on_action(window.listener_for(&entity, InputBaseState::select_left))
5688 .on_action(window.listener_for(&entity, InputBaseState::select_right))
5689 .when(self.is_multi_line(), |this| {
5690 this.on_action(window.listener_for(&entity, InputBaseState::up))
5691 .on_action(window.listener_for(&entity, InputBaseState::down))
5692 .on_action(window.listener_for(&entity, InputBaseState::select_up))
5693 .on_action(window.listener_for(&entity, InputBaseState::select_down))
5694 .on_action(window.listener_for(&entity, InputBaseState::page_up))
5695 .on_action(window.listener_for(&entity, InputBaseState::page_down))
5696 .on_action(window.listener_for(&entity, InputBaseState::add_cursor_above))
5697 .on_action(window.listener_for(&entity, InputBaseState::add_cursor_below))
5698 })
5699 .on_action(window.listener_for(&entity, InputBaseState::on_action_select_all))
5700 .on_action(window.listener_for(&entity, InputBaseState::select_to_start_of_line))
5701 .on_action(window.listener_for(&entity, InputBaseState::select_to_end_of_line))
5702 .on_action(window.listener_for(&entity, InputBaseState::select_to_previous_word))
5703 .on_action(window.listener_for(&entity, InputBaseState::select_to_next_word))
5704 .on_action(window.listener_for(&entity, InputBaseState::home))
5705 .on_action(window.listener_for(&entity, InputBaseState::end))
5706 .on_action(window.listener_for(&entity, InputBaseState::move_to_start))
5707 .on_action(window.listener_for(&entity, InputBaseState::move_to_end))
5708 .on_action(window.listener_for(&entity, InputBaseState::move_to_previous_word))
5709 .on_action(window.listener_for(&entity, InputBaseState::move_to_next_word))
5710 .on_action(window.listener_for(&entity, InputBaseState::select_to_start))
5711 .on_action(window.listener_for(&entity, InputBaseState::select_to_end))
5712 .on_action(window.listener_for(&entity, InputBaseState::show_character_palette))
5713 .on_action({
5714 let entity = entity.clone();
5715 move |_: &ActivateToken, window, cx| {
5716 let state = entity.read(cx);
5717 let activation = state
5718 .token_spans()
5719 .iter()
5720 .find(|span| span.range() == state.selected_range())
5721 .and_then(|span| {
5722 state.range_to_bounds(&span.range()).and_then(|bounds| {
5723 state.token_activation(
5724 span.range().start,
5725 bounds,
5726 gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
5727 bounds,
5728 ..Default::default()
5729 }),
5730 )
5731 })
5732 });
5733 if let Some((listener, event)) = activation {
5734 listener(&event, window, cx);
5735 }
5736 }
5737 })
5738 .on_action(window.listener_for(&entity, InputBaseState::copy))
5739 .on_action(window.listener_for(&entity, InputBaseState::on_action_search))
5740 .on_action(window.listener_for(&entity, InputBaseState::on_action_replace))
5741 .on_mouse_down(
5742 MouseButton::Left,
5743 window.listener_for(&entity, InputBaseState::on_mouse_down),
5744 )
5745 .on_mouse_down(
5746 MouseButton::Right,
5747 window.listener_for(&entity, InputBaseState::on_mouse_down),
5748 )
5749 .on_mouse_up(
5750 MouseButton::Left,
5751 window.listener_for(&entity, InputBaseState::on_mouse_up),
5752 )
5753 .on_mouse_up(
5754 MouseButton::Right,
5755 window.listener_for(&entity, InputBaseState::on_mouse_up),
5756 )
5757 .on_mouse_move(window.listener_for(&entity, InputBaseState::on_mouse_move))
5758 .on_scroll(window.listener_for(&entity, InputBaseState::on_scroll_wheel))
5759 .when(self.is_multi_line() && !self.disabled, |this| {
5760 this.on_modifiers_changed(cx.listener(|_, _, _, cx| cx.notify()))
5761 })
5762 .when(!self.disabled, |this| {
5763 if self.is_multi_line() && window.modifiers().alt {
5764 this.cursor_crosshair()
5765 } else {
5766 this.cursor_text()
5767 }
5768 })
5769 .flex_1()
5770 .map(|this| {
5776 if self.is_multi_line() {
5777 this.h_full()
5778 } else {
5779 this.min_h_full().flex().items_center()
5780 }
5781 })
5782 .flex_grow_1()
5783 .overflow_x_hidden()
5784 .when(self.is_multi_line(), |this| {
5785 this.pt(self.editor_paddings.top)
5786 .pr(self.editor_paddings.right)
5787 .pb(self.editor_paddings.bottom)
5788 .pl(self.editor_paddings.left)
5789 })
5790 .child(
5791 TextElement::new(entity.clone())
5792 .with_line_number_renderer(line_number_renderer)
5793 .placeholder(self.placeholder.clone()),
5794 )
5795 .when(self.shows_scrollbar(), |this| {
5796 this.child(EditorScrollbar::new(entity.clone()))
5797 });
5798
5799 M::register_actions(element, &entity, window)
5802 .test_support()
5803 .track_focus(&self.focus_handle)
5804 }
5805}
5806
5807#[cfg(test)]
5808mod tests {
5809 use super::*;
5810
5811 #[gpui::test]
5812 fn test_set_value_waits_for_the_first_layout(cx: &mut TestAppContext) {
5813 cx.update(crate::init);
5814 let (state, cx) = cx.add_window_view(|window, cx| {
5815 let mut state = crate::input::InputState::new(window, cx);
5816 state.set_value("hello", window, cx);
5817 assert_eq!(state.display_map().wrap_row_count(), 0);
5819 state
5820 });
5821 cx.update(|window, cx| window.draw(cx).clear(cx));
5822 state.read_with(cx, |state, _| {
5823 assert_eq!(state.value(), "hello");
5824 assert_eq!(state.display_map().wrap_row_count(), 1);
5825 });
5826 }
5827
5828 #[gpui::test]
5829 fn accessibility_actions_recheck_live_editability(cx: &mut TestAppContext) {
5830 cx.update(crate::init);
5831 let (state, cx) = cx.add_window_view(|window, cx| {
5832 crate::input::InputState::new(window, cx).default_value("initial")
5833 });
5834 let changes = Rc::new(Cell::new(0));
5835 let observed = changes.clone();
5836 let _subscription = cx.update(|_, cx| {
5837 cx.subscribe(&state, move |_, event: &InputEvent, _| {
5838 if matches!(event, InputEvent::Change) {
5839 observed.set(observed.get() + 1);
5840 }
5841 })
5842 });
5843 cx.update(|window, cx| {
5844 state.update(cx, |state, cx| {
5845 state.handle_accessibility_set_value(None, window, cx);
5846 state.handle_accessibility_focus(window, cx);
5847 assert!(state.focus_handle.is_focused(window));
5848 });
5849 window.draw(cx).clear(cx);
5850 });
5851 assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5852 assert_eq!(changes.get(), 0);
5853
5854 let action = gpui::accesskit::ActionData::Value("updated🦀".into());
5855 cx.update(|window, cx| {
5856 state.update(cx, |state, cx| {
5857 state.handle_accessibility_set_value(Some(&action), window, cx)
5858 });
5859 });
5860 assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5861 assert_eq!(changes.get(), 1);
5862 for disabled in [false, true] {
5863 cx.update(|window, cx| {
5864 window.blur(cx);
5865 state.update(cx, |state, cx| {
5866 state.set_disabled(disabled, cx);
5867 state.set_readonly(!disabled, cx);
5868 state.handle_accessibility_focus(window, cx);
5869 assert_eq!(state.focus_handle.is_focused(window), !disabled);
5870 let rejected = gpui::accesskit::ActionData::Value("rejected".into());
5871 state.handle_accessibility_set_value(Some(&rejected), window, cx);
5872 });
5873 });
5874 assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5875 assert_eq!(changes.get(), 1);
5876 }
5877 cx.update(|window, cx| {
5878 state.update(cx, |state, cx| {
5879 state.set_disabled(false, cx);
5880 state.set_readonly(false, cx);
5881 state.handle_accessibility_focus(window, cx);
5882 });
5883 window.draw(cx).clear(cx);
5884 window.dispatch_action(Box::new(Undo), cx);
5885 });
5886 assert_eq!(state.read_with(cx, |state, _| state.value()), "initial");
5887 cx.update(|window, cx| {
5888 state.update(cx, |state, cx| {
5889 state.set_masked(true, window, cx);
5890 state.handle_accessibility_set_value(Some(&action), window, cx);
5891 });
5892 });
5893 assert_eq!(state.read_with(cx, |state, _| state.value()), "updated🦀");
5894 }
5895
5896 #[gpui::test]
5897 fn accessibility_set_value_preserves_exact_editor_text(cx: &mut TestAppContext) {
5898 cx.update(crate::init);
5899 let (editor, cx) = cx.add_window_view(|window, cx| {
5900 crate::input::EditorState::new(window, cx).language("rust")
5901 });
5902 let action = gpui::accesskit::ActionData::Value("(".into());
5903 cx.update(|window, cx| {
5904 editor.update(cx, |editor, cx| {
5905 editor.handle_accessibility_set_value(Some(&action), window, cx)
5906 });
5907 });
5908 assert_eq!(editor.read_with(cx, |editor, _| editor.value()), "(");
5909 }
5910
5911 #[gpui::test]
5912 fn accessibility_set_value_cannot_replace_a_bounded_document(cx: &mut TestAppContext) {
5913 cx.update(crate::init);
5914 let (editor, cx) = cx.add_window_view(|window, cx| {
5915 crate::input::EditorState::new(window, cx).default_value(
5916 "x".repeat(super::super::a11y_text::FULL_ACCESSIBILITY_TEXT_LIMIT + 1),
5917 )
5918 });
5919 let action = gpui::accesskit::ActionData::Value("replacement".into());
5920 cx.update(|window, cx| {
5921 editor.update(cx, |editor, cx| {
5922 editor.handle_accessibility_set_value(Some(&action), window, cx)
5923 });
5924 });
5925 assert!(editor.read_with(cx, |editor, _| editor.value().starts_with('x')));
5926 }
5927
5928 #[gpui::test]
5929 fn revealing_a_password_keeps_text_assistance_disabled(cx: &mut TestAppContext) {
5930 cx.update(crate::init);
5931 cx.open_window(size(px(400.), px(100.)), |window, cx| {
5932 let state = cx.new(|cx| crate::input::InputState::new(window, cx).masked(true));
5933 let hidden = state.read(cx).text_input_configuration();
5934 assert!(!hidden.autocorrect && !hidden.suggestions);
5935 assert_eq!(hidden.autocapitalize, Autocapitalize::None);
5936
5937 state.update(cx, |state, cx| state.toggle_masked(window, cx));
5939 assert_eq!(state.read(cx).text_input_configuration(), hidden);
5940 state.update(cx, |state, cx| state.toggle_masked(window, cx));
5941 assert_eq!(state.read(cx).text_input_configuration(), hidden);
5942 gpui::EmptyView
5943 });
5944 }
5945
5946 #[gpui::test]
5947 fn text_input_configuration_follows_the_input(cx: &mut TestAppContext) {
5948 use crate::input::{InputState, TextareaState};
5949
5950 cx.update(crate::init);
5951 let mut states = None;
5952 cx.open_window(size(px(400.), px(100.)), |window, cx| {
5953 states = Some((
5954 cx.new(|cx| InputState::new(window, cx)),
5955 cx.new(|cx| InputState::new(window, cx).masked(true)),
5956 cx.new(|cx| TextareaState::new(window, cx)),
5957 cx.new(|cx| {
5958 InputState::new(window, cx)
5959 .input_action(TextInputAction::Search)
5960 .autocorrect(true)
5961 .autocapitalize(Autocapitalize::Words)
5962 }),
5963 ));
5964 gpui::EmptyView
5965 });
5966 let (plain, masked, textarea, search) = states.unwrap();
5967
5968 cx.read(|cx| {
5969 assert_eq!(
5970 plain.read(cx).text_input_configuration(),
5971 TextInputConfiguration {
5972 input_action: TextInputAction::Done,
5973 ..Default::default()
5974 }
5975 );
5976 assert_eq!(
5977 masked.read(cx).text_input_configuration(),
5978 TextInputConfiguration {
5979 input_action: TextInputAction::Done,
5980 ..Default::default()
5981 }
5982 );
5983 assert_eq!(
5984 textarea.read(cx).text_input_configuration(),
5985 TextInputConfiguration {
5986 input_action: TextInputAction::Enter,
5987 ..Default::default()
5988 }
5989 );
5990 let search = search.read(cx).text_input_configuration();
5991 assert_eq!(search.input_action, TextInputAction::Search);
5992 assert_eq!(search.autocapitalize, Autocapitalize::Words);
5993 assert!(search.autocorrect);
5994 assert!(search.suggestions);
5995 });
5996 }
5997
5998 #[gpui::test]
5999 fn test_multicursor_unicode_completion_uses_post_edit_start(cx: &mut TestAppContext) {
6000 use crate::input::{CompletionProvider, EditorState};
6001 use gpui::Task;
6002 use lsp_types::{CompletionContext, CompletionResponse};
6003 use std::cell::RefCell;
6004
6005 #[derive(Default)]
6006 struct Provider {
6007 starts: RefCell<Vec<usize>>,
6008 queries: RefCell<Vec<(usize, String)>>,
6009 }
6010
6011 impl CompletionProvider for Provider {
6012 fn is_completion_trigger(&self, offset: usize, _: &str, _: &mut App) -> bool {
6013 self.starts.borrow_mut().push(offset);
6014 true
6015 }
6016
6017 fn completions(
6018 &self,
6019 _: &Rope,
6020 offset: usize,
6021 trigger: CompletionContext,
6022 _: &mut Window,
6023 _: &mut App,
6024 ) -> Task<anyhow::Result<CompletionResponse>> {
6025 self.queries
6026 .borrow_mut()
6027 .push((offset, trigger.trigger_character.unwrap()));
6028 Task::ready(Ok(CompletionResponse::Array(vec![])))
6029 }
6030 }
6031
6032 cx.update(crate::init);
6033 let mut editor = None;
6034 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
6035 editor = Some(cx.new(|cx| EditorState::new(window, cx).default_value("aa")));
6036 gpui::EmptyView
6037 });
6038 let editor = editor.unwrap();
6039 let provider = Rc::new(Provider::default());
6040 window
6041 .update(cx, |_, window, cx| {
6042 editor.update(cx, |state, cx| {
6043 state.extras.lsp.completion_provider = Some(provider.clone());
6044 state
6045 .extras
6046 .context_menu_content
6047 .completion
6048 .trigger_start_offset = Some(0);
6049 state.extras.context_menu_content.completion.query = "aa".into();
6050 state.set_cursor_to(1);
6051 state.add_cursor_at(0, cx);
6052
6053 state.replace_text_in_range(None, "中", window, cx);
6054
6055 assert_eq!(state.value(), "中a中a");
6056 assert_eq!(provider.starts.borrow().as_slice(), &[4]);
6057 assert_eq!(provider.queries.borrow().as_slice(), &[(7, "中".into())]);
6058 });
6059 })
6060 .unwrap();
6061 }
6062
6063 #[gpui::test]
6064 fn selected_range_restores_unicode_direction_without_splitting_characters(
6065 cx: &mut TestAppContext,
6066 ) {
6067 use crate::input::EditorState;
6068 cx.update(crate::init);
6069 cx.open_window(size(px(400.), px(100.)), |window, cx| {
6070 let _state = cx.new(|cx| {
6071 let mut state = EditorState::new(window, cx).default_value("中😀a");
6072 state.set_selected_range_with_direction(3..8, true, cx);
6073 let selected = state.selected_text_range(false, window, cx).unwrap();
6074 assert_eq!(selected.range, 1..4);
6075 assert!(selected.reversed);
6076 assert_eq!(state.selected_range(), 3..8);
6077 assert!(state.is_selection_reversed());
6078 let range = state.selected_range();
6079 let reversed = state.is_selection_reversed();
6080 state.set_selected_range_with_direction(range, reversed, cx);
6081 assert!(state.is_selection_reversed());
6082 state.set_selected_range(3..8, cx);
6083 let selected = state.selected_text_range(false, window, cx).unwrap();
6084 assert_eq!(selected.range, 1..4);
6085 assert!(!selected.reversed);
6086 assert!(!state.is_selection_reversed());
6087 state.set_selected_range(Range { start: 8, end: 3 }, cx);
6089 assert_eq!(state.selected_range(), 8..8);
6090 assert!(!state.is_selection_reversed());
6091 state.set_selected_range_with_direction(4..4, true, cx);
6092 assert!(!state.is_selection_reversed());
6093 assert_eq!(
6094 state.selected_text_range(false, window, cx).unwrap().range,
6095 1..1
6096 );
6097 state
6098 });
6099 gpui::EmptyView
6100 });
6101 }
6102
6103 #[gpui::test]
6104 fn test_set_tokens_keeps_text_selection_and_history(cx: &mut TestAppContext) {
6105 use crate::input::{InlineToken, InlineTokenError, InputContent};
6106 let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
6107 let bold = |text: &str| {
6108 InputContent::new(text.to_string())
6109 .with_token(2..7, InlineToken::new("bold", "**b**"))
6110 .unwrap()
6111 };
6112 view.window_handle
6113 .update(cx, |_, window, cx| {
6114 view.input.update(cx, |state, cx| {
6115 state.set_selected_range(9..9, cx);
6116 state.insert("!", window, cx);
6117 state.set_selected_range(9..9, cx);
6118 state.set_tokens(bold("a **b** c!"), cx).unwrap();
6119 assert_eq!(state.value(), "a **b** c!");
6120 assert_eq!(state.selected_range(), 9..9);
6121 assert_eq!(state.tokens().len(), 1);
6122
6123 assert_eq!(
6124 state.set_tokens(bold("a **b** c"), cx),
6125 Err(InlineTokenError::TextMismatch)
6126 );
6127 state
6128 .set_tokens(InputContent::new("a **b** c!"), cx)
6129 .unwrap();
6130 assert!(state.tokens().is_empty());
6131 state.set_selected_range(4..4, cx);
6132 assert_eq!(
6133 state.set_tokens(bold("a **b** c!"), cx),
6134 Err(InlineTokenError::SplitsSelection)
6135 );
6136 state.undo(&Undo, window, cx);
6137 assert_eq!(state.value(), "a **b** c");
6138 });
6139 })
6140 .unwrap();
6141 }
6142
6143 #[gpui::test]
6144 fn test_set_tokens_rejects_a_token_through_any_cursor(cx: &mut TestAppContext) {
6145 use crate::input::{InlineToken, InlineTokenError, InputContent};
6146 let view = InputView::build_textarea(cx, |state| state.default_value("a **b** c"));
6147 view.window_handle
6148 .update(cx, |_, _, cx| {
6149 view.input.update(cx, |state, cx| {
6150 state.set_selected_range(9..9, cx);
6151 let id = state.selections.generate_id();
6152 state.selections.add(CursorSelection::new(id, 4, 4));
6153 let content = InputContent::new("a **b** c")
6154 .with_token(2..7, InlineToken::new("bold", "**b**"))
6155 .unwrap();
6156 assert_eq!(
6157 state.set_tokens(content, cx),
6158 Err(InlineTokenError::SplitsSelection)
6159 );
6160 assert!(state.tokens().is_empty());
6161 });
6162 })
6163 .unwrap();
6164 }
6165
6166 #[gpui::test]
6167 fn test_set_tokens_undo_redo_replays_edits_inside_and_before_a_token(cx: &mut TestAppContext) {
6168 use crate::input::{InlineToken, InputContent};
6169 let view = InputView::build_textarea(cx, |state| state.default_value("a **** c"));
6170 let bold = |text: &str, range: Range<usize>| {
6171 InputContent::new(text.to_string())
6172 .with_token(range, InlineToken::new("bold", "**b**"))
6173 .unwrap()
6174 };
6175 view.window_handle
6176 .update(cx, |_, window, cx| {
6177 view.input.update(cx, |state, cx| {
6178 state.set_selected_range(4..4, cx);
6179 state.insert("b", window, cx);
6180 state.set_selected_range(9..9, cx);
6181 state.set_tokens(bold("a **b** c", 2..7), cx).unwrap();
6182
6183 state.undo(&Undo, window, cx);
6184 assert_eq!(state.value(), "a **** c");
6185 assert!(state.tokens().is_empty());
6186 state.redo(&Redo, window, cx);
6187 assert_eq!(state.value(), "a **b** c");
6188 assert!(state.tokens().is_empty());
6189 assert_eq!(state.selected_range(), 5..5);
6190
6191 state.set_selected_range(0..0, cx);
6192 state.insert("z", window, cx);
6193 state.set_selected_range(10..10, cx);
6194 state.set_tokens(bold("za **b** c", 3..8), cx).unwrap();
6195
6196 state.undo(&Undo, window, cx);
6197 assert_eq!(state.value(), "a **b** c");
6198 let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
6199 assert_eq!(ranges, vec![2..7]);
6200 state.redo(&Redo, window, cx);
6201 assert_eq!(state.value(), "za **b** c");
6202 let ranges: Vec<_> = state.tokens().iter().map(|s| s.range()).collect();
6203 assert_eq!(ranges, vec![3..8]);
6204 });
6205 })
6206 .unwrap();
6207 }
6208
6209 #[gpui::test]
6210 fn test_set_tokens_refreshes_the_token_layout(cx: &mut TestAppContext) {
6211 use crate::input::{InlineToken, InputContent};
6212 let view = InputView::build_textarea(cx, |state| state.default_value("@a x @a y"));
6213 let mention = || InlineToken::new("a", "@a");
6214 view.window_handle
6215 .update(cx, |_, _, cx| {
6216 view.input.update(cx, |state, cx| {
6217 let content = InputContent::new("@a x @a y")
6218 .with_token(0..2, mention())
6219 .and_then(|content| content.with_token(5..7, mention()))
6220 .unwrap();
6221 state.set_tokens(content, cx).unwrap();
6222 });
6223 })
6224 .unwrap();
6225 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6226 visual.update(|window, cx| window.draw(cx).clear(cx));
6227 view.input.update(&mut visual, |state, cx| {
6228 let content = InputContent::new("@a x @a y")
6229 .with_token(5..7, mention())
6230 .unwrap();
6231 state.set_tokens(content, cx).unwrap();
6232 });
6233 visual.update(|window, cx| window.draw(cx).clear(cx));
6234 view.input.read_with(&visual, |state, _| {
6235 let cache = state.token_layout_cache.as_ref().unwrap();
6236 let ranges: Vec<_> = cache
6237 .metrics
6238 .iter()
6239 .map(|(range, _)| range.clone())
6240 .collect();
6241 assert_eq!(ranges, vec![5..7]);
6242 });
6243 }
6244
6245 #[gpui::test]
6246 fn test_inline_token_wrap_and_size_refresh(cx: &mut TestAppContext) {
6247 use crate::input::{InlineToken, InlineTokenPresentation};
6248 let width = Rc::new(Cell::new(4000.));
6249 let render_width = width.clone();
6250 let view = InputView::build_textarea(cx, |state| state.rows(4).default_value("@a@b"));
6251 view.window_handle
6252 .update(cx, |_, window, cx| {
6253 view.input.update(cx, |state, cx| {
6254 state
6255 .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6256 .unwrap();
6257 state
6258 .replace_range_with_token(2..4, InlineToken::new("b", "@b"), window, cx)
6259 .unwrap();
6260 state.set_token_presentation(
6261 InlineTokenPresentation::default()
6262 .token(move |_, _, _| div().w(px(render_width.get()))),
6263 );
6264 });
6265 })
6266 .unwrap();
6267 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6268 visual.update(|window, cx| window.draw(cx).clear(cx));
6269 view.input.read_with(&visual, |state, _| {
6270 assert_eq!(state.display_map.wrap_row_count(), 2);
6271 let first = state.range_to_bounds(&(0..2)).unwrap();
6272 let second = state.range_to_bounds(&(2..4)).unwrap();
6273 assert!(second.origin.y > first.origin.y);
6274 assert_eq!(
6275 state.last_layout.as_ref().unwrap().lines[0].wrapped_lines[0].len,
6276 2
6277 );
6278 });
6279 width.set(100.);
6280 view.input.update(&mut visual, |_, cx| cx.notify());
6281 visual.update(|window, cx| window.draw(cx).clear(cx));
6282 view.input.read_with(&visual, |state, _| {
6283 assert_eq!(state.display_map.wrap_row_count(), 1)
6284 });
6285 }
6286
6287 #[gpui::test]
6288 fn test_inline_token_geometry_and_reentrant_activation(cx: &mut TestAppContext) {
6289 use crate::input::{InlineToken, InlineTokenPresentation};
6290 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6291 let target = view.input.clone();
6292 view.window_handle
6293 .update(cx, |_, window, cx| {
6294 view.input.update(cx, |state, cx| {
6295 state
6296 .replace_range_with_token(
6297 7..13,
6298 InlineToken::new("a", "@alice"),
6299 window,
6300 cx,
6301 )
6302 .unwrap();
6303 state.set_token_presentation(
6304 InlineTokenPresentation::default()
6305 .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6306 .on_token_click(move |_, window, cx| {
6307 target.update(cx, |state, cx| {
6308 state.set_value("activated", window, cx)
6309 })
6310 }),
6311 );
6312 state.focus(window, cx);
6313 state.set_selected_range(7..13, cx);
6314 });
6315 })
6316 .unwrap();
6317 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6318 visual.update(|window, cx| window.draw(cx).clear(cx));
6319 visual.update(|window, cx| {
6320 let state = view.input.read(cx);
6321 let bounds = state.range_to_bounds(&(7..13)).unwrap();
6322 assert!((bounds.size.width - px(100.)).abs() < px(1.), "{bounds:?}");
6323 let (left, _) = state.index_for_mouse_position(bounds.origin + point(px(10.), px(5.)));
6324 let (right, _) = state.index_for_mouse_position(bounds.origin + point(px(90.), px(5.)));
6325 assert_eq!((left, right), (7, 13));
6326 window.dispatch_action(Box::new(ActivateToken), cx);
6327 });
6328 visual.run_until_parked();
6329 view.input.read_with(&visual, |state, _| {
6330 assert_eq!(state.value().as_ref(), "activated")
6331 });
6332 }
6333
6334 #[gpui::test]
6335 fn test_inline_token_click_selects_it(cx: &mut TestAppContext) {
6336 use crate::input::InlineToken;
6337 cx.update(crate::init);
6338 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6339 view.window_handle
6340 .update(cx, |_, window, cx| {
6341 view.input.update(cx, |state, cx| {
6342 state
6343 .replace_range_with_token(
6344 7..13,
6345 InlineToken::new("a", "@alice"),
6346 window,
6347 cx,
6348 )
6349 .unwrap();
6350 state.set_selected_range(0..0, cx);
6351 });
6352 })
6353 .unwrap();
6354 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6355 visual.update(|window, cx| window.draw(cx).clear(cx));
6356 let bounds = view
6357 .input
6358 .read_with(&visual, |state, _| state.range_to_bounds(&(7..13)).unwrap());
6359 visual.simulate_click(bounds.center(), gpui::Modifiers::default());
6360 visual.run_until_parked();
6361 view.input.read_with(&visual, |state, _| {
6362 assert_eq!(state.selected_range(), 7..13, "a click selects the token");
6363 });
6364 }
6365
6366 #[gpui::test]
6367 fn test_inline_token_hover_reports_presence_without_selecting(cx: &mut TestAppContext) {
6368 use crate::input::{InlineToken, InlineTokenPresentation};
6369 use gpui::{Bounds, point, px, size};
6370 cx.update(crate::init);
6371 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6372 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6373 view.window_handle
6374 .update(cx, |_, window, cx| {
6375 view.input.update(cx, |state, cx| {
6376 state
6377 .replace_range_with_token(
6378 7..13,
6379 InlineToken::new("a", "@alice"),
6380 window,
6381 cx,
6382 )
6383 .unwrap();
6384 state.set_token_presentation(
6385 InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6386 );
6387 state.set_selected_range(0..0, cx);
6388 });
6389 })
6390 .unwrap();
6391 view.window_handle
6392 .update(cx, |_, _, cx| {
6393 view.input.update(cx, |state, _| {
6394 let (_, entered) = state
6395 .token_hover(7, bounds, true, None)
6396 .expect("hover enters an enabled token");
6397 assert!(entered.is_hovered());
6398 assert_eq!(entered.token().id().as_ref(), "a");
6399 assert_eq!(entered.range(), 7..13);
6400 assert_eq!(entered.bounds(), bounds);
6401 let (_, left) = state
6402 .token_hover(7, bounds, false, None)
6403 .expect("hover leaves the same token");
6404 assert!(!left.is_hovered());
6405 assert_eq!(state.selected_range(), 0..0, "hover never selects");
6406 assert!(state.token_hover(99, bounds, true, None).is_none());
6407 });
6408 })
6409 .unwrap();
6410
6411 view.window_handle
6413 .update(cx, |_, _, cx| {
6414 view.input.update(cx, |state, cx| {
6415 state.set_disabled(true, cx);
6416 });
6417 })
6418 .unwrap();
6419 view.window_handle
6420 .update(cx, |_, _, cx| {
6421 view.input.update(cx, |state, _| {
6422 assert!(state.token_hover(7, bounds, true, None).is_none())
6423 })
6424 })
6425 .unwrap();
6426 view.window_handle
6427 .update(cx, |_, _, cx| {
6428 view.input.update(cx, |state, cx| {
6429 state.set_disabled(false, cx);
6430 state.set_readonly(true, cx);
6431 });
6432 })
6433 .unwrap();
6434 view.window_handle
6435 .update(cx, |_, _, cx| {
6436 view.input.update(cx, |state, _| {
6437 assert!(state.token_hover(7, bounds, true, None).is_some())
6438 })
6439 })
6440 .unwrap();
6441
6442 view.window_handle
6444 .update(cx, |_, _, cx| {
6445 view.input.update(cx, |state, _| {
6446 state.set_token_presentation(InlineTokenPresentation::default());
6447 });
6448 })
6449 .unwrap();
6450 view.window_handle
6451 .update(cx, |_, _, cx| {
6452 view.input.update(cx, |state, _| {
6453 assert!(state.token_hover(7, bounds, true, None).is_none())
6454 })
6455 })
6456 .unwrap();
6457 }
6458
6459 #[gpui::test]
6460 fn test_inline_token_hover_exit_delivered_when_token_removed(cx: &mut TestAppContext) {
6461 use crate::input::{InlineToken, InlineTokenPresentation};
6462 use std::cell::RefCell;
6463 use std::rc::Rc;
6464 cx.update(crate::init);
6465 let view = InputView::build(cx, |state| state.default_value("before @alice after"));
6466 let events: Rc<RefCell<Vec<(SharedString, bool)>>> = Rc::new(RefCell::new(Vec::new()));
6467 let sink = events.clone();
6468 view.window_handle
6469 .update(cx, |_, window, cx| {
6470 view.input.update(cx, |state, cx| {
6471 state
6472 .replace_range_with_token(
6473 7..13,
6474 InlineToken::new("a", "@alice"),
6475 window,
6476 cx,
6477 )
6478 .unwrap();
6479 state.set_token_presentation(
6480 InlineTokenPresentation::default()
6481 .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6482 .on_token_hover(move |event, _, _| {
6483 sink.borrow_mut()
6484 .push((event.token().id().clone(), event.is_hovered()));
6485 }),
6486 );
6487 });
6488 })
6489 .unwrap();
6490 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6491 visual.update(|window, cx| window.draw(cx).clear(cx));
6492 let known_bounds = view.input.read_with(&visual, |state, _| {
6493 state
6494 .token_bounds
6495 .get(&7)
6496 .copied()
6497 .expect("placed token bounds")
6498 });
6499 visual.simulate_mouse_move(known_bounds.center(), None, gpui::Modifiers::default());
6500 visual.run_until_parked();
6501 visual.update(|window, cx| window.draw(cx).clear(cx));
6502 assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6503
6504 view.window_handle
6508 .update(cx, |_, window, cx| {
6509 view.input
6510 .update(cx, |state, cx| state.set_value("no tokens", window, cx));
6511 })
6512 .unwrap();
6513 visual.run_until_parked();
6514 visual.update(|window, cx| window.draw(cx).clear(cx));
6515 assert_eq!(
6516 events.borrow().as_slice(),
6517 &[("a".into(), true), ("a".into(), false)]
6518 );
6519 }
6520
6521 #[gpui::test]
6522 fn test_inline_token_hover_bounds_stay_single_row_at_wrap_boundary(cx: &mut TestAppContext) {
6523 use crate::input::{InlineToken, InlineTokenPresentation};
6524 cx.update(crate::init);
6525 let view = InputView::build_textarea(cx, |state| {
6526 state
6527 .rows(4)
6528 .default_value("aaaa bbbb cccc dddd @alice eeee ffff")
6529 });
6530 view.window_handle
6531 .update(cx, |_, window, cx| {
6532 view.input.update(cx, |state, cx| {
6533 state
6534 .replace_range_with_token(
6535 20..26,
6536 InlineToken::new("a", "@alice"),
6537 window,
6538 cx,
6539 )
6540 .unwrap();
6541 state.set_token_presentation(
6542 InlineTokenPresentation::default()
6543 .token(|_, _, _| div().w(px(60.)).h(px(20.))),
6544 );
6545 });
6546 })
6547 .unwrap();
6548 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6549 visual.update(|window, cx| window.draw(cx).clear(cx));
6550 let (placed, ranged, line_height) = view.input.read_with(&visual, |state, _| {
6551 (
6552 state
6553 .token_bounds
6554 .get(&20)
6555 .copied()
6556 .expect("placed token bounds"),
6557 state.range_to_bounds(&(20..26)),
6558 state.last_layout.as_ref().unwrap().line_height,
6559 )
6560 });
6561 assert!(placed.size.height <= line_height + px(1.), "{placed:?}");
6565 assert!(
6566 placed.size.width <= px(61.) && placed.size.width > px(0.),
6567 "{placed:?}"
6568 );
6569 if let Some(ranged) = ranged {
6570 assert!(
6571 ranged.size.height >= placed.size.height - px(1.),
6572 "{ranged:?} vs {placed:?}"
6573 );
6574 }
6575 }
6576
6577 #[gpui::test]
6578 fn test_inline_token_hover_same_offset_replacement_exits_predecessor(cx: &mut TestAppContext) {
6579 use crate::input::{InlineToken, InlineTokenPresentation};
6580 use std::{cell::RefCell, rc::Rc};
6581 cx.update(crate::init);
6582 let view = InputView::build(cx, |state| state.default_value("@alice!"));
6583 let events = Rc::new(RefCell::new(Vec::new()));
6584 let sink = events.clone();
6585 view.window_handle
6586 .update(cx, |_, window, cx| {
6587 view.input.update(cx, |state, cx| {
6588 state
6589 .replace_range_with_token(0..6, InlineToken::new("a", "@alice"), window, cx)
6590 .unwrap();
6591 state.set_token_presentation(
6592 InlineTokenPresentation::default()
6593 .token(|_, _, _| div().w(px(100.)).h(px(20.)))
6594 .on_token_hover(move |event, _, _| {
6595 sink.borrow_mut()
6596 .push((event.token().id().clone(), event.is_hovered()));
6597 }),
6598 );
6599 });
6600 })
6601 .unwrap();
6602 let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
6603 visual.update(|window, cx| window.draw(cx).clear(cx));
6604 let bounds = view
6605 .input
6606 .read_with(&visual, |state, _| state.token_bounds[&0]);
6607 visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6608 visual.run_until_parked();
6609 visual.update(|window, cx| window.draw(cx).clear(cx));
6610 assert_eq!(events.borrow().as_slice(), &[("a".into(), true)]);
6611
6612 view.window_handle
6613 .update(cx, |_, window, cx| {
6614 view.input.update(cx, |state, cx| {
6615 state
6616 .replace_range_with_token(0..6, InlineToken::new("b", "@alice"), window, cx)
6617 .unwrap();
6618 });
6619 })
6620 .unwrap();
6621 visual.run_until_parked();
6622 visual.update(|window, cx| window.draw(cx).clear(cx));
6623 visual.simulate_mouse_move(
6624 bounds.center() + gpui::point(px(1.), px(0.)),
6625 None,
6626 gpui::Modifiers::default(),
6627 );
6628 visual.run_until_parked();
6629 visual.update(|window, cx| window.draw(cx).clear(cx));
6630 assert_eq!(
6631 events.borrow().as_slice(),
6632 &[("a".into(), true), ("a".into(), false), ("b".into(), true)]
6633 );
6634 view.input
6637 .update(&mut visual, |state, cx| state.set_disabled(true, cx));
6638 visual.update(|window, cx| window.draw(cx).clear(cx));
6639 visual.run_until_parked();
6640 assert_eq!(events.borrow().last(), Some(&("b".into(), false)));
6641 view.input
6642 .update(&mut visual, |state, cx| state.set_disabled(false, cx));
6643 visual.update(|window, cx| window.draw(cx).clear(cx));
6644 visual.run_until_parked();
6645 visual.simulate_mouse_move(bounds.center(), None, gpui::Modifiers::default());
6646 visual.run_until_parked();
6647 assert_eq!(
6648 events.borrow().as_slice(),
6649 &[
6650 ("a".into(), true),
6651 ("a".into(), false),
6652 ("b".into(), true),
6653 ("b".into(), false),
6654 ("b".into(), true)
6655 ]
6656 );
6657 visual.simulate_mouse_move(
6658 bounds.bottom_right() + gpui::point(px(10.), px(10.)),
6659 None,
6660 gpui::Modifiers::default(),
6661 );
6662 visual.run_until_parked();
6663 assert_eq!(
6664 events.borrow().as_slice(),
6665 &[
6666 ("a".into(), true),
6667 ("a".into(), false),
6668 ("b".into(), true),
6669 ("b".into(), false),
6670 ("b".into(), true),
6671 ("b".into(), false)
6672 ]
6673 );
6674 }
6675
6676 #[gpui::test]
6677 fn test_inline_token_hover_older_exit_keeps_newer_snapshot(cx: &mut TestAppContext) {
6678 use crate::input::{InlineToken, InlineTokenPresentation};
6679 use gpui::{Bounds, point, px, size};
6680 cx.update(crate::init);
6681 let view = InputView::build(cx, |state| state.default_value("@a @b"));
6682 let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(20.)));
6683 view.window_handle
6684 .update(cx, |_, window, cx| {
6685 view.input.update(cx, |state, cx| {
6686 state
6687 .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6688 .unwrap();
6689 state
6690 .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6691 .unwrap();
6692 state.set_token_presentation(
6693 InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6694 );
6695 state
6698 .token_hover(0, bounds, true, None)
6699 .expect("hover enters A");
6700 state
6701 .token_hover(3, bounds, true, None)
6702 .expect("hover enters B");
6703 let (_, exit_a) = state.token_hover(0, bounds, false, None).expect("A exits");
6704 assert!(!exit_a.is_hovered());
6705 assert_eq!(
6707 state
6708 .hovered_token
6709 .as_ref()
6710 .expect("B still hovered")
6711 .span
6712 .token()
6713 .id()
6714 .as_ref(),
6715 "b"
6716 );
6717 state.set_value("no tokens", window, cx);
6719 state.token_bounds.clear();
6720 let (listener, exit_b) = state.reconcile_token_hover().expect("B must exit");
6721 assert!(!exit_b.is_hovered());
6722 assert_eq!(exit_b.token().id().as_ref(), "b");
6723 drop(listener);
6724 });
6725 })
6726 .unwrap();
6727 }
6728
6729 #[gpui::test]
6730 fn test_inline_token_hover_late_exit_matches_replaced_token(cx: &mut TestAppContext) {
6731 use crate::input::{InlineToken, InlineTokenPresentation};
6732 cx.update(crate::init);
6733 let view = InputView::build(cx, |state| state.default_value("@a"));
6734 view.window_handle
6735 .update(cx, |_, window, cx| {
6736 view.input.update(cx, |state, cx| {
6737 let a = InlineToken::new("a", "@a");
6738 let b = InlineToken::new("b", "@a");
6739 state
6740 .replace_range_with_token(0..2, a.clone(), window, cx)
6741 .unwrap();
6742 state.set_token_presentation(
6743 InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6744 );
6745 let bounds = gpui::Bounds::default();
6746 state.token_hover(0, bounds, true, Some(&a)).unwrap();
6747 state
6748 .replace_range_with_token(0..2, b.clone(), window, cx)
6749 .unwrap();
6750 state.token_hover(0, bounds, true, Some(&b)).unwrap();
6751 let (_, exit_a) = state.token_hover(0, bounds, false, Some(&a)).unwrap();
6752 assert_eq!(exit_a.token().id().as_ref(), "a");
6753 assert_eq!(state.hovered_token.as_ref().unwrap().span.token(), &b);
6754 let (_, exit_b) = state.token_hover(0, bounds, false, Some(&b)).unwrap();
6755 assert_eq!(exit_b.token().id().as_ref(), "b");
6756 assert!(state.pending_token_hover_exits.is_empty());
6757 });
6758 })
6759 .unwrap();
6760 }
6761
6762 #[gpui::test]
6763 fn test_inline_token_hover_exit_keeps_entry_utf16_after_edit(cx: &mut TestAppContext) {
6764 use crate::input::{InlineToken, InlineTokenPresentation};
6765 use gpui::EntityInputHandler as _;
6766 cx.update(crate::init);
6767 let view = InputView::build(cx, |state| state.default_value("🙂 @a"));
6768 view.window_handle
6769 .update(cx, |_, window, cx| {
6770 view.input.update(cx, |state, cx| {
6771 state
6772 .replace_range_with_token(5..7, InlineToken::new("a", "@a"), window, cx)
6773 .unwrap();
6774 state.set_token_presentation(
6775 InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6776 );
6777 let bounds = gpui::Bounds::default();
6778 let (_, enter) = state.token_hover(5, bounds, true, None).unwrap();
6779 assert_eq!(enter.range_utf16(), (3, 5));
6780 state.replace_text_in_range(Some(0..2), "abcd", window, cx);
6781 assert_eq!(state.token_spans()[0].range(), 5..7);
6782 let (_, exit) = state.token_hover(5, bounds, false, None).unwrap();
6783 assert_eq!(exit.range_utf16(), (3, 5));
6784 });
6785 })
6786 .unwrap();
6787 }
6788
6789 #[gpui::test]
6790 fn test_text_length_utf16(cx: &mut TestAppContext) {
6791 use gpui::EntityInputHandler as _;
6792 cx.update(crate::init);
6793 let view = InputView::build(cx, |state| state.default_value("🙂 й"));
6795 view.window_handle
6796 .update(cx, |_, window, cx| {
6797 view.input.update(cx, |state, cx| {
6798 assert_eq!(state.text_length_utf16(window, cx), Some(4));
6799 state.replace_text_in_range(None, "ab", window, cx);
6800 assert_eq!(state.text_length_utf16(window, cx), Some(6));
6801 });
6802 })
6803 .unwrap();
6804 }
6805
6806 #[gpui::test]
6807 fn test_set_selected_text_range(cx: &mut TestAppContext) {
6808 use gpui::EntityInputHandler as _;
6809 cx.update(crate::init);
6810 let view = InputView::build(cx, |state| state.default_value("🙂 hello world"));
6812 view.window_handle
6813 .update(cx, |_, window, cx| {
6814 view.input.update(cx, |state, cx| {
6815 fn selection(
6816 state: &mut InputBaseState<InputMode>,
6817 window: &mut Window,
6818 cx: &mut Context<InputBaseState<InputMode>>,
6819 ) -> (Range<usize>, bool) {
6820 let selection = state.selected_text_range(false, window, cx).unwrap();
6821 (selection.range, selection.reversed)
6822 }
6823
6824 state.set_selected_text_range(3..8, window, cx);
6825 assert_eq!(state.selected_range(), 5..10);
6826 assert_eq!(selection(state, window, cx), (3..8, false));
6827
6828 state.set_selected_text_range(3..14, window, cx);
6830 assert_eq!(selection(state, window, cx), (3..14, false));
6831 assert_eq!(state.cursor(), 16);
6832
6833 state.set_selected_text_range(9..14, window, cx);
6835 assert_eq!(selection(state, window, cx), (9..14, true));
6836 assert_eq!(state.cursor(), 11);
6837
6838 state.set_selected_text_range(9..14, window, cx);
6840 assert_eq!(selection(state, window, cx), (9..14, true));
6841
6842 state.set_selected_text_range(100..9, window, cx);
6844 assert_eq!(selection(state, window, cx), (9..14, true));
6845
6846 state.set_selected_text_range(3..8, window, cx);
6848 state.set_selected_text_range(2..3, window, cx);
6849 assert_eq!(selection(state, window, cx), (2..3, true));
6850 assert_eq!(state.cursor(), 4);
6851 state.set_selected_text_range(3..8, window, cx);
6852 state.set_selected_text_range(8..9, window, cx);
6853 assert_eq!(selection(state, window, cx), (8..9, false));
6854 assert_eq!(state.cursor(), 11);
6855
6856 state.set_selected_text_range(2..2, window, cx);
6858 assert_eq!(selection(state, window, cx), (2..2, false));
6859 assert_eq!(state.value(), "🙂 hello world");
6860 });
6861 })
6862 .unwrap();
6863 }
6864
6865 #[gpui::test]
6866 fn test_inline_token_hover_callback_edit_preserves_both_exits(cx: &mut TestAppContext) {
6867 use crate::input::{InlineToken, InlineTokenPresentation};
6868 cx.update(crate::init);
6869 let view = InputView::build(cx, |state| state.default_value("@a @b"));
6870 view.window_handle
6871 .update(cx, |_, window, cx| {
6872 view.input.update(cx, |state, cx| {
6873 state
6874 .replace_range_with_token(0..2, InlineToken::new("a", "@a"), window, cx)
6875 .unwrap();
6876 state
6877 .replace_range_with_token(3..5, InlineToken::new("b", "@b"), window, cx)
6878 .unwrap();
6879 state.set_token_presentation(
6880 InlineTokenPresentation::default().on_token_hover(|_, _, _| {}),
6881 );
6882 let bounds = gpui::Bounds::default();
6883 state.token_hover(0, bounds, true, None).unwrap();
6884 state.token_hover(3, bounds, true, None).unwrap();
6885 state.set_value("gone", window, cx);
6887 let (_, exit_a) = state.token_hover(0, bounds, false, None).unwrap();
6888 assert_eq!(exit_a.token().id().as_ref(), "a");
6889 let (_, exit_b) = state.reconcile_token_hover().unwrap();
6890 assert_eq!(exit_b.token().id().as_ref(), "b");
6891 assert!(state.token_hover(0, bounds, false, None).is_none());
6892 assert!(state.reconcile_token_hover().is_none());
6893 });
6894 })
6895 .unwrap();
6896 }
6897
6898 #[gpui::test]
6899 fn test_inline_token_edit_history_and_validation(cx: &mut TestAppContext) {
6900 let view = InputView::build(cx, |state| state.default_value("问 @alice!"));
6901 view.window_handle
6902 .update(cx, |_, window, cx| {
6903 view.input.update(cx, |state, cx| {
6904 let token =
6905 crate::input::InlineToken::new("alice-1", "@alice").with_label("Alice");
6906 state
6907 .replace_range_with_token(4..10, token.clone(), window, cx)
6908 .unwrap();
6909 assert_eq!(state.value().as_ref(), "问 @alice!");
6910 assert_eq!(state.tokens()[0].range(), 4..10);
6911 assert_eq!(state.next_end_of_word_at(4), 10);
6912 assert_eq!(state.previous_start_of_word_at(10), 4);
6913 state.undo(&Undo, window, cx);
6914 assert!(
6915 state.tokens().is_empty(),
6916 "identity-only association is undoable"
6917 );
6918 assert_eq!(state.value().as_ref(), "问 @alice!");
6919 state.redo(&Redo, window, cx);
6920 assert_eq!(state.tokens()[0].token(), &token);
6921 state.set_selected_range(6..7, cx);
6922 assert_eq!(state.selected_range(), 4..10);
6923 state.replace("", window, cx);
6924 assert_eq!(state.value().as_ref(), "问 !");
6925 assert!(state.tokens().is_empty());
6926 state.undo(&Undo, window, cx);
6927 assert_eq!(state.tokens()[0].token(), &token);
6928 state.set_selected_range(0..0, cx);
6929 state.replace("🙂", window, cx);
6930 assert_eq!(state.tokens()[0].range(), 8..14);
6931 state.undo(&Undo, window, cx);
6932 assert_eq!(state.tokens()[0].range(), 4..10);
6933 let before = state.content();
6934 state
6935 .replace_range_with_token(0..0, token.clone(), window, cx)
6936 .expect("the same reference may occur twice");
6937 assert_eq!(state.value().as_ref(), "@alice问 @alice!");
6938 assert_eq!(state.tokens().len(), 2);
6939 assert_eq!(state.tokens()[1].token(), &token);
6940 state.undo(&Undo, window, cx);
6941 assert_eq!(state.content(), before);
6942 state.set_value(before.text().clone(), window, cx);
6943 assert!(state.tokens().is_empty());
6944 assert!(!state.undo_manager.has_undos());
6945 });
6946 })
6947 .unwrap();
6948 }
6949
6950 #[gpui::test]
6951 fn test_inline_token_textarea_ime_and_modes(cx: &mut TestAppContext) {
6952 use crate::input::{InlineToken, InlineTokenError, InputContent};
6953 let view = InputView::build_textarea(cx, |state| state);
6954 view.window_handle
6955 .update(cx, |_, window, cx| {
6956 view.input.update(cx, |state, cx| {
6957 let content = InputContent::new("@a@b\n后面")
6958 .with_token(0..2, InlineToken::new("a", "@a"))
6959 .unwrap()
6960 .with_token(2..4, InlineToken::new("b", "@b"))
6961 .unwrap();
6962 state.set_value(content.clone(), window, cx);
6963 state.set_selected_range(2..2, cx);
6964 assert_eq!(state.previous_boundary(2), 0);
6965 assert_eq!(state.next_boundary(2), 4);
6966 state.replace_and_mark_text_in_range(Some(1..2), "中", Some(1..1), window, cx);
6967 assert_eq!(state.value().as_ref(), "中@b\n后面");
6968 assert_eq!(state.tokens().len(), 1);
6969 assert_eq!(
6970 state.replace_with_token(InlineToken::new("x", "x"), window, cx),
6971 Err(InlineTokenError::CompositionActive)
6972 );
6973 state.replace_text_in_range(None, "中文", window, cx);
6974 state.undo(&Undo, window, cx);
6975 assert_eq!(state.content(), content);
6976 state.redo(&Redo, window, cx);
6977 assert_eq!(state.value().as_ref(), "中文@b\n后面");
6978 state.undo(&Undo, window, cx);
6979 state.replace_all("plain", window, cx);
6980 assert!(state.tokens().is_empty());
6981 state.undo(&Undo, window, cx);
6982 assert_eq!(state.content(), content);
6983 });
6984 })
6985 .unwrap();
6986 let view = InputView::build(cx, |state| state);
6987 view.window_handle
6988 .update(cx, |_, window, cx| {
6989 view.input.update(cx, |state, cx| {
6990 assert_eq!(
6991 InputContent::new("a\u{301}")
6992 .with_token(0..1, InlineToken::new("bad", "a"))
6993 .err(),
6994 Some(InlineTokenError::InvalidBoundary)
6995 );
6996 assert_eq!(
6997 InputContent::new("@a@a")
6998 .with_token(0..2, InlineToken::new("a", "@a"))
6999 .unwrap()
7000 .with_token(1..3, InlineToken::new("x", "a@"))
7001 .err(),
7002 Some(InlineTokenError::OverlappingTokens)
7003 );
7004 state
7005 .replace_with_token(InlineToken::new("a", "@a"), window, cx)
7006 .unwrap();
7007 let before = state.content();
7008 state.set_masked(true, window, cx);
7009 assert!(!state.tokens_visible());
7010 assert_eq!(
7011 state.replace_with_token(InlineToken::new("b", "b"), window, cx),
7012 Err(InlineTokenError::UnsupportedMode)
7013 );
7014 assert_eq!(state.content(), before);
7015 state.undo(&Undo, window, cx);
7016 assert!(state.tokens().is_empty());
7017 state.redo(&Redo, window, cx);
7018 assert_eq!(state.content(), before);
7019 assert!(!state.tokens_visible());
7020 });
7021 })
7022 .unwrap();
7023 }
7024
7025 use crate::theme::Theme;
7026 use gpui::{TestAppContext, VisualTestContext, size};
7027
7028 use crate::input::{EditorMode, EditorState, InputMode, LanguageConfig, TabSize, TextareaMode};
7029
7030 fn set_test_syntax_provider(
7031 provider: Rc<dyn crate::input::SyntaxContextProvider>,
7032 cx: &mut App,
7033 ) {
7034 struct TestLanguages(Rc<dyn crate::input::SyntaxContextProvider>);
7035 impl crate::input::LanguageProvider for TestLanguages {
7036 fn syntax_context_provider(
7037 &self,
7038 _: &str,
7039 ) -> Option<Rc<dyn crate::input::SyntaxContextProvider>> {
7040 Some(self.0.clone())
7041 }
7042 }
7043 crate::input::set_language_provider(Rc::new(TestLanguages(provider)), cx);
7044 }
7045
7046 struct TestRoot<M: InputModeKind>(Entity<InputBaseState<M>>);
7047
7048 impl<M: InputModeKind> Render for TestRoot<M> {
7049 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7050 div().size_full().child(self.0.clone())
7051 }
7052 }
7053
7054 struct InputView<M: InputModeKind> {
7055 input: Entity<InputBaseState<M>>,
7056 window_handle: gpui::WindowHandle<TestRoot<M>>,
7057 }
7058
7059 impl<M: InputModeKind> InputView<M> {
7061 fn build_with(
7062 cx: &mut TestAppContext,
7063 make: impl FnOnce(&mut Window, &mut Context<InputBaseState<M>>) -> InputBaseState<M>
7064 + 'static,
7065 ) -> Self {
7066 let mut input: Option<Entity<InputBaseState<M>>> = None;
7067
7068 let window = cx.update(|cx| {
7069 cx.open_window(Default::default(), |window, cx| {
7070 cx.set_global(Theme::default());
7072 super::super::init(cx);
7074
7075 input = Some(cx.new(|cx| make(window, cx)));
7076
7077 cx.new(|_| TestRoot(input.clone().unwrap()))
7078 })
7079 .unwrap()
7080 });
7081
7082 Self {
7083 input: input.unwrap(),
7084 window_handle: window,
7085 }
7086 }
7087 }
7088
7089 impl InputView<EditorMode> {
7090 fn new(cx: &mut TestAppContext) -> Self {
7092 Self::build_editor(cx, |state| state)
7093 }
7094
7095 fn build_editor(
7096 cx: &mut TestAppContext,
7097 f: impl FnOnce(InputBaseState<EditorMode>) -> InputBaseState<EditorMode> + 'static,
7098 ) -> Self {
7099 Self::build_with(cx, move |window, cx| {
7100 f(crate::input::EditorState::new(window, cx).language("sql"))
7101 })
7102 }
7103 }
7104
7105 impl InputView<TextareaMode> {
7106 fn build_textarea(
7107 cx: &mut TestAppContext,
7108 f: impl FnOnce(InputBaseState<TextareaMode>) -> InputBaseState<TextareaMode> + 'static,
7109 ) -> Self {
7110 Self::build_with(cx, move |window, cx| {
7111 f(crate::input::TextareaState::new(window, cx))
7112 })
7113 }
7114 }
7115
7116 impl InputView<InputMode> {
7117 fn build(
7119 cx: &mut TestAppContext,
7120 f: impl FnOnce(InputBaseState<InputMode>) -> InputBaseState<InputMode> + 'static,
7121 ) -> Self {
7122 Self::build_with(cx, move |window, cx| {
7123 f(crate::input::InputState::new(window, cx))
7124 })
7125 }
7126 }
7127
7128 fn swipe<M: InputModeKind>(
7130 view: &InputView<M>,
7131 cx: &mut VisualTestContext,
7132 dy: f32,
7133 phase: gpui::TouchPhase,
7134 ) {
7135 cx.update(|window, cx| {
7136 view.input.update(cx, |state, cx| {
7137 state.on_scroll_wheel(
7138 &ScrollEvent {
7139 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(dy))),
7140 touch_phase: phase,
7141 ..Default::default()
7142 },
7143 window,
7144 cx,
7145 )
7146 })
7147 });
7148 }
7149
7150 fn long_text() -> String {
7151 (0..60)
7152 .map(|n| format!("line {n}"))
7153 .collect::<Vec<_>>()
7154 .join("\n")
7155 }
7156
7157 #[gpui::test]
7158 fn test_scroll_bounce_stretches_past_the_end_and_springs_back(cx: &mut TestAppContext) {
7159 use gpui::TouchPhase::{Ended, Moved, Started};
7160
7161 let view = InputView::build_textarea(cx, |state| {
7162 state.scroll_bounce(true).default_value(long_text())
7163 });
7164 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7165 cx.update(|window, cx| window.draw(cx).clear(cx));
7166 let drawn_at = |cx: &mut VisualTestContext| {
7167 view.input
7168 .read_with(cx, |state, _| state.last_bounds.unwrap().origin.y)
7169 };
7170
7171 swipe(&view, &mut cx, -20., Started);
7172 swipe(&view, &mut cx, -100_000., Moved);
7173 let (end, stretch) = view.input.read_with(&cx, |state, _| {
7174 (state.scroll_handle.offset().y, state.overscroll.offset())
7175 });
7176 assert!(end < px(0.), "the text scrolled to its end");
7177 assert!(stretch < 0., "the rest stretched the edge: {stretch}");
7178 cx.update(|window, cx| window.draw(cx).clear(cx));
7179 let stretched_at = drawn_at(&mut cx);
7180
7181 swipe(&view, &mut cx, 0., Ended);
7182 for _ in 0..120 {
7183 cx.executor()
7184 .advance_clock(std::time::Duration::from_millis(16));
7185 cx.update(|window, cx| window.draw(cx).clear(cx));
7186 }
7187 view.input.read_with(&cx, |state, _| {
7188 assert_eq!(state.overscroll.offset(), 0., "the edge sprang back");
7189 assert_eq!(
7190 state.scroll_handle.offset().y,
7191 end,
7192 "scrolling stayed exact"
7193 );
7194 });
7195 let moved = (stretched_at - drawn_at(&mut cx)).as_f32();
7196 assert!(
7197 (moved - stretch).abs() < 0.001,
7198 "the stretch only moved where the text was drawn: {moved} vs {stretch}"
7199 );
7200 }
7201
7202 fn swipe_past_the_end(
7205 view: &InputView<TextareaMode>,
7206 cx: &mut VisualTestContext,
7207 ) -> (Pixels, f32) {
7208 use gpui::TouchPhase::{Moved, Started};
7209
7210 cx.update(|window, cx| window.draw(cx).clear(cx));
7211 swipe(view, cx, -20., Started);
7212 swipe(view, cx, -100_000., Moved);
7213 view.input.read_with(cx, |state, _| {
7214 (state.scroll_handle.offset().y, state.overscroll.offset())
7215 })
7216 }
7217
7218 #[gpui::test]
7219 fn test_scroll_bounce_stays_put_under_reduced_motion(cx: &mut TestAppContext) {
7220 cx.update(|cx| cx.set_reduce_motion(true));
7221 let view = InputView::build_textarea(cx, |state| {
7222 state.scroll_bounce(true).default_value(long_text())
7223 });
7224 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7225 let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7226 assert!(end < px(0.), "the text still scrolls");
7227 assert_eq!(stretch, 0., "the edge does not stretch");
7228 }
7229
7230 #[gpui::test]
7231 fn test_scroll_bounce_follows_the_platform_by_default(cx: &mut TestAppContext) {
7232 let view = InputView::build_textarea(cx, |state| state.default_value(long_text()));
7233 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7234 let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7235 assert!(end < px(0.), "the text scrolls");
7236 assert_eq!(
7237 stretch != 0.,
7238 crate::ScrollBounce::enabled_by_default(),
7239 "the edge stretches where the platform's scroll views do"
7240 );
7241 }
7242
7243 #[gpui::test]
7244 fn test_scroll_bounce_leaves_text_that_fits(cx: &mut TestAppContext) {
7245 let view = InputView::build_textarea(cx, |state| {
7246 state.scroll_bounce(true).default_value("one line")
7247 });
7248 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7249 let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7250 assert_eq!((end, stretch), (px(0.), 0.));
7251 }
7252
7253 #[gpui::test]
7254 fn test_scroll_bounce_resets_when_replacement_text_fits(cx: &mut TestAppContext) {
7255 let view = InputView::build_textarea(cx, |state| {
7256 state.scroll_bounce(true).default_value(long_text())
7257 });
7258 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7259 let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7260 assert!(stretch < 0.);
7261 cx.update(|window, cx| {
7262 view.input
7263 .update(cx, |state, cx| state.set_value("short", window, cx));
7264 window.draw(cx).clear(cx);
7265 });
7266 swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
7267 view.input.read_with(&cx, |state, _| {
7268 assert_eq!(state.overscroll.offset(), 0.);
7269 assert_eq!(state.scroll_handle.offset().y, px(0.));
7270 });
7271 }
7272
7273 #[gpui::test]
7274 fn test_scroll_bounce_releases_when_the_end_packet_is_horizontal(cx: &mut TestAppContext) {
7275 let view = InputView::build_textarea(cx, |state| {
7276 state.scroll_bounce(true).default_value(long_text())
7277 });
7278 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7279 let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7280 assert!(stretch < 0.);
7281 cx.update(|window, cx| {
7282 view.input.update(cx, |state, cx| {
7283 state.on_scroll_wheel(
7284 &ScrollEvent {
7285 delta: gpui::ScrollDelta::Pixels(point(px(1.), px(0.))),
7286 touch_phase: gpui::TouchPhase::Ended,
7287 ..Default::default()
7288 },
7289 window,
7290 cx,
7291 );
7292 });
7293 });
7294 for _ in 0..120 {
7295 cx.executor()
7296 .advance_clock(std::time::Duration::from_millis(16));
7297 cx.update(|window, cx| window.draw(cx).clear(cx));
7298 }
7299 assert_eq!(
7300 view.input
7301 .read_with(&cx, |state, _| state.overscroll.offset()),
7302 0.
7303 );
7304 }
7305
7306 #[gpui::test]
7307 fn test_scroll_bounce_ordinary_mouse_wheel_does_not_stretch(cx: &mut TestAppContext) {
7308 let view = InputView::build_textarea(cx, |state| {
7309 state.scroll_bounce(true).default_value(long_text())
7310 });
7311 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7312 cx.update(|window, cx| {
7313 window.draw(cx).clear(cx);
7314 view.input.update(cx, |state, cx| {
7315 state.on_scroll_wheel(
7316 &ScrollEvent {
7317 delta: gpui::ScrollDelta::Lines(point(0., -100_000.)),
7318 touch_phase: gpui::TouchPhase::Moved,
7319 ..Default::default()
7320 },
7321 window,
7322 cx,
7323 );
7324 assert!(state.scroll_handle.offset().y < px(0.));
7325 assert_eq!(state.overscroll.offset(), 0.);
7326 });
7327 });
7328 }
7329
7330 #[gpui::test]
7331 fn test_scroll_bounce_new_wheel_input_interrupts_the_return(cx: &mut TestAppContext) {
7332 let view = InputView::build_textarea(cx, |state| {
7333 state.scroll_bounce(true).default_value(long_text())
7334 });
7335 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7336 let (end, stretch) = swipe_past_the_end(&view, &mut cx);
7337 assert!(stretch < 0.);
7338 swipe(&view, &mut cx, 0., gpui::TouchPhase::Ended);
7339 cx.executor()
7340 .advance_clock(std::time::Duration::from_millis(16));
7341 cx.update(|window, cx| {
7342 window.draw(cx).clear(cx);
7343 view.input.update(cx, |state, cx| {
7344 state.on_scroll_wheel(
7345 &ScrollEvent {
7346 delta: gpui::ScrollDelta::Lines(point(0., 2.)),
7347 touch_phase: gpui::TouchPhase::Moved,
7348 ..Default::default()
7349 },
7350 window,
7351 cx,
7352 );
7353 assert!(state.scroll_handle.offset().y > end);
7354 assert_eq!(state.overscroll.offset(), 0.);
7355 });
7356 });
7357 }
7358
7359 #[gpui::test]
7360 fn test_turning_scroll_bounce_off_drops_the_stretch(cx: &mut TestAppContext) {
7361 let view = InputView::build_textarea(cx, |state| {
7362 state.scroll_bounce(true).default_value(long_text())
7363 });
7364 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7365 let (_, stretch) = swipe_past_the_end(&view, &mut cx);
7366 assert!(stretch < 0., "the edge stretched: {stretch}");
7367 view.input
7368 .update(&mut cx, |state, cx| state.set_scroll_bounce(false, cx));
7369 assert_eq!(
7370 view.input
7371 .read_with(&cx, |state, _| state.overscroll.offset()),
7372 0.
7373 );
7374 }
7375
7376 #[gpui::test]
7379 fn single_line_is_centered_in_a_taller_frame(cx: &mut TestAppContext) {
7380 struct Frame(Entity<InputBaseState<InputMode>>);
7381 impl Render for Frame {
7382 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7383 crate::input::InputBase::new("frame")
7384 .h(px(60.))
7385 .child(crate::input::Input::new(&self.0))
7386 }
7387 }
7388
7389 cx.update(crate::init);
7390 let mut input = None;
7391 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7392 let state = cx.new(|cx| crate::input::InputState::new(window, cx).default_value("a"));
7393 input = Some(state.clone());
7394 Frame(state)
7395 });
7396 let input = input.unwrap();
7397 let mut cx = VisualTestContext::from_window(window.into(), cx);
7398 cx.update(|window, cx| window.draw(cx).clear(cx));
7399
7400 input.read_with(&cx, |state, _| {
7401 let line = state.input_bounds;
7402 assert_eq!(line.center().y, px(30.), "line {line:?}");
7403 });
7404 }
7405
7406 #[gpui::test]
7407 fn test_noop_scroll_notifies_diagnostic_dismissal(cx: &mut TestAppContext) {
7408 use std::{cell::Cell, rc::Rc};
7409
7410 cx.update(crate::init);
7411 let mut input = None;
7412 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7413 input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7414 gpui::EmptyView
7415 });
7416 let input = input.unwrap();
7417 input.update(cx, |state, cx| {
7418 state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7419 state.scroll_size = size(px(100.), px(20.));
7420 state.present_diagnostic(crate::input::DiagnosticEntry::default(), cx);
7421 });
7422 let notifications = Rc::new(Cell::new(0));
7423 let count = notifications.clone();
7424 let _subscription =
7425 cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7426
7427 window
7428 .update(cx, |_, window, cx| {
7429 input.update(cx, |state, cx| {
7430 state.on_scroll_wheel(
7431 &ScrollEvent {
7432 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7433 ..Default::default()
7434 },
7435 window,
7436 cx,
7437 );
7438 assert_eq!(state.scroll_handle.offset(), Point::default());
7439 assert!(state.diagnostic_popover().is_none());
7440 });
7441 })
7442 .unwrap();
7443 assert_eq!(
7444 notifications.get(),
7445 1,
7446 "clearing a diagnostic must notify even when scrolling is clamped"
7447 );
7448 window
7449 .update(cx, |_, window, cx| {
7450 input.update(cx, |state, cx| {
7451 state.on_scroll_wheel(
7452 &ScrollEvent {
7453 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-40.))),
7454 ..Default::default()
7455 },
7456 window,
7457 cx,
7458 );
7459 });
7460 })
7461 .unwrap();
7462 assert_eq!(notifications.get(), 1, "an unchanged input must stay quiet");
7463 }
7464
7465 #[gpui::test]
7468 fn replacing_the_text_wraps_at_the_width_its_line_numbers_leave(cx: &mut TestAppContext) {
7469 struct Panel(Entity<crate::input::EditorState>);
7470 impl Render for Panel {
7471 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7472 div().size_full().child(self.0.clone())
7473 }
7474 }
7475 cx.update(crate::init);
7476 let mut input = None;
7477 let window = cx.open_window(size(px(400.), px(300.)), |window, cx| {
7478 let state = cx.new(|cx| {
7479 crate::input::EditorState::new(window, cx)
7480 .line_number(true)
7481 .soft_wrap(true)
7482 });
7483 input = Some(state.clone());
7484 Panel(state)
7485 });
7486 cx.run_until_parked();
7487 let input = input.unwrap();
7488 let wrap_width = |cx: &mut TestAppContext| {
7489 input.read_with(cx, |state, _| state.display_map.wrap_width())
7490 };
7491 let three_digits = wrap_width(cx).expect("a soft wrapped editor has a wrap width");
7492
7493 let predicted = window
7494 .update(cx, |_, window, cx| {
7495 input.update(cx, |state, cx| {
7496 state.set_value("line\n".repeat(1_000), window, cx);
7497 state.display_map.wrap_width()
7498 })
7499 })
7500 .unwrap()
7501 .unwrap();
7502 assert!(
7503 predicted < three_digits,
7504 "a fourth digit must narrow the text"
7505 );
7506 cx.run_until_parked();
7507 assert_eq!(
7508 wrap_width(cx),
7509 Some(predicted),
7510 "the layout must keep the width the text was wrapped at"
7511 );
7512 }
7513
7514 #[gpui::test]
7517 fn test_hover_reaches_bottom_of_scrolled_editor(cx: &mut TestAppContext) {
7518 use crate::input::{Diagnostic, Position};
7519 struct Frame(Entity<crate::input::EditorState>);
7520 impl Render for Frame {
7521 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7522 crate::input::InputBase::new("frame")
7523 .h(px(100.))
7524 .child(crate::input::Editor::new(&self.0))
7525 }
7526 }
7527
7528 cx.update(crate::init);
7529 let text = (0..100).map(|i| format!("line {i}\n")).collect::<String>();
7530 let mut input = None;
7531 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7532 let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
7533 input = Some(state.clone());
7534 Frame(state)
7535 });
7536 let input = input.unwrap();
7537 let mut cx = VisualTestContext::from_window(window.into(), cx);
7538 input.update(&mut cx, |state, _| {
7539 state.diagnostics_mut().unwrap().push(Diagnostic::new(
7540 Position::new(0, 0)..Position::new(100, 0),
7541 "everywhere",
7542 ));
7543 });
7544 cx.update(|window, cx| window.draw(cx).clear(cx));
7545 cx.update(|window, cx| {
7546 input.update(cx, |state, cx| {
7547 state.on_scroll_wheel(
7548 &ScrollEvent {
7549 delta: gpui::ScrollDelta::Pixels(point(px(0.), px(-400.))),
7550 ..Default::default()
7551 },
7552 window,
7553 cx,
7554 );
7555 })
7556 });
7557 cx.update(|window, cx| window.draw(cx).clear(cx));
7558
7559 let bounds = input.read_with(&cx, |state, _| state.input_bounds);
7560 cx.simulate_mouse_move(
7561 point(bounds.center().x, bounds.bottom() - px(5.)),
7562 None,
7563 gpui::Modifiers::default(),
7564 );
7565 assert!(
7566 input.read_with(&cx, |state, _| state.diagnostic_popover().is_some()),
7567 "no hover at the bottom of a scrolled editor, bounds {bounds:?}"
7568 );
7569 }
7570
7571 #[gpui::test]
7572 fn test_cursor_layout_consumer_updates_after_selection(cx: &mut TestAppContext) {
7573 use std::{cell::Cell, rc::Rc};
7574 struct Panel {
7575 input: Entity<crate::input::EditorState>,
7576 observed: Rc<Cell<Option<(Bounds<Pixels>, Pixels)>>>,
7577 }
7578 impl Render for Panel {
7579 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
7580 self.observed.set(self.input.read(cx).cursor_layout());
7581 div().size_full().child(self.input.clone())
7582 }
7583 }
7584 struct Root(Entity<Panel>);
7585 impl Render for Root {
7586 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7587 div().size_full().child(
7588 self.0
7589 .clone()
7590 .cached(gpui::StyleRefinement::default().size_full()),
7591 )
7592 }
7593 }
7594 cx.update(crate::init);
7595 let observed = Rc::new(Cell::new(None));
7596 let mut input = None;
7597 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7598 let state = cx.new(|cx| {
7599 let mut state = crate::input::EditorState::new(window, cx);
7600 state.set_value("abcdefgh", window, cx);
7601 state
7602 });
7603 input = Some(state.clone());
7604 Root(cx.new(|_| Panel {
7605 input: state,
7606 observed: observed.clone(),
7607 }))
7608 });
7609 cx.run_until_parked();
7610 let input = input.unwrap();
7611 let before = input.read_with(cx, |state, _| state.cursor_layout());
7612 input.update(cx, |_, cx| cx.notify());
7617 cx.run_until_parked();
7618 assert_eq!(observed.get(), before);
7619 window
7620 .update(cx, |_, _, cx| {
7621 input.update(cx, |state, cx| state.select_to_with_affinity(3, false, cx));
7622 })
7623 .unwrap();
7624 cx.run_until_parked();
7625 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7626 let after = input.read_with(cx, |state, _| state.cursor_layout());
7627 assert_ne!(after, before, "the caret must actually move");
7628 assert_eq!(
7629 observed.get(),
7630 after,
7631 "render consumers must receive the newly painted caret geometry"
7632 );
7633 }
7634
7635 #[gpui::test]
7636 fn test_input_scroll_offset_notifies_only_on_change(cx: &mut TestAppContext) {
7637 use std::{cell::Cell, rc::Rc};
7638
7639 cx.update(crate::init);
7640 let mut input = None;
7641 let _window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7642 input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7643 gpui::EmptyView
7644 });
7645 let input = input.unwrap();
7646 let notifications = Rc::new(Cell::new(0));
7647 let count = notifications.clone();
7648 let _subscription =
7649 cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7650
7651 input.update(cx, |state, _| {
7652 state.input_bounds = Bounds::new(Point::default(), size(px(100.), px(20.)));
7653 state.scroll_size = size(px(300.), px(20.));
7654 });
7655 for target in [
7656 None,
7657 Some(point(px(0.), px(0.))),
7658 Some(point(px(20.), px(50.))),
7659 ] {
7660 input.update(cx, |state, cx| state.update_scroll_offset(target, cx));
7661 assert_eq!(
7662 notifications.get(),
7663 0,
7664 "an unchanged clamped offset must stay quiet"
7665 );
7666 }
7667 input.update(cx, |state, cx| {
7668 state.update_scroll_offset(Some(point(px(-40.), px(0.))), cx);
7669 assert_eq!(state.scroll_handle.offset(), point(px(-40.), px(0.)));
7670 });
7671 assert_eq!(notifications.get(), 1, "a scroll must notify");
7672 input.update(cx, |state, cx| {
7673 state.update_scroll_offset(Some(point(px(-400.), px(50.))), cx);
7674 assert_eq!(state.scroll_handle.offset(), point(px(-200.), px(0.)));
7675 });
7676 assert_eq!(notifications.get(), 2);
7677 input.update(cx, |state, cx| {
7678 state.update_scroll_offset(Some(point(px(-500.), px(0.))), cx);
7679 });
7680 assert_eq!(
7681 notifications.get(),
7682 2,
7683 "clamping to the current offset must stay quiet"
7684 );
7685 input.update(cx, |state, cx| {
7686 state.scroll_size.width = px(110.);
7687 state.update_scroll_offset(None, cx);
7688 assert_eq!(state.scroll_handle.offset(), point(px(-10.), px(0.)));
7689 });
7690 assert_eq!(
7691 notifications.get(),
7692 3,
7693 "a smaller scroll range must clamp and notify"
7694 );
7695 }
7696
7697 #[gpui::test]
7698 fn test_set_line_number_notifies_only_on_change(cx: &mut TestAppContext) {
7699 use std::{cell::Cell, rc::Rc};
7700
7701 cx.update(crate::init);
7702 let mut input = None;
7703 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7704 input = Some(cx.new(|cx| crate::input::EditorState::new(window, cx)));
7705 gpui::EmptyView
7706 });
7707 let input = input.unwrap();
7708 let shown = input.read_with(cx, |state, _| state.mode.line_number());
7709 let notifications = Rc::new(Cell::new(0));
7710 let count = notifications.clone();
7711 let _subscription =
7712 cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7713
7714 window
7715 .update(cx, |_, window, cx| {
7716 input.update(cx, |state, cx| state.set_line_number(shown, window, cx))
7717 })
7718 .unwrap();
7719 assert_eq!(notifications.get(), 0);
7720
7721 window
7722 .update(cx, |_, window, cx| {
7723 input.update(cx, |state, cx| state.set_line_number(!shown, window, cx))
7724 })
7725 .unwrap();
7726 assert_eq!(notifications.get(), 1);
7727 assert_eq!(
7728 input.read_with(cx, |state, _| state.mode.line_number()),
7729 !shown
7730 );
7731 }
7732
7733 #[gpui::test]
7734 fn test_set_value_on_unfocused_input_stays_quiet(cx: &mut TestAppContext) {
7735 use std::{cell::Cell, rc::Rc};
7736
7737 cx.update(crate::init);
7738 let mut input = None;
7739 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7740 input = Some(cx.new(|cx| crate::input::InputState::new(window, cx)));
7741 gpui::EmptyView
7742 });
7743 let input = input.unwrap();
7744 cx.run_until_parked();
7745
7746 let notifications = Rc::new(Cell::new(0));
7747 let count = notifications.clone();
7748 let _subscription =
7749 cx.update(|cx| cx.observe(&input, move |_, _| count.set(count.get() + 1)));
7750 cx.run_until_parked();
7751
7752 window
7755 .update(cx, |_, window, cx| {
7756 input.update(cx, |state, cx| state.set_value("seeded", window, cx));
7757 })
7758 .unwrap();
7759 cx.run_until_parked();
7760 let settled = notifications.get();
7761
7762 cx.executor()
7763 .advance_clock(std::time::Duration::from_secs(3));
7764 cx.run_until_parked();
7765
7766 assert_eq!(
7767 notifications.get(),
7768 settled,
7769 "an unfocused input is blinking, and every blink repaints the view it is in"
7770 );
7771 }
7772
7773 #[gpui::test]
7774 fn test_input_does_not_invalidate_cached_parent_during_paint(cx: &mut TestAppContext) {
7775 use std::{cell::Cell, rc::Rc};
7776
7777 struct Panel {
7778 input: Entity<crate::input::InputState>,
7779 renders: Rc<Cell<usize>>,
7780 }
7781 impl Render for Panel {
7782 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7783 self.renders.set(self.renders.get() + 1);
7784 div().size_full().child(self.input.clone())
7785 }
7786 }
7787 struct Root(Entity<Panel>);
7788 impl Render for Root {
7789 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7790 div().size_full().child(
7791 self.0
7792 .clone()
7793 .cached(gpui::StyleRefinement::default().size_full()),
7794 )
7795 }
7796 }
7797
7798 cx.update(crate::init);
7799 let renders = Rc::new(Cell::new(0));
7800 let mut input = None;
7801 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
7802 let state = cx.new(|cx| crate::input::InputState::new(window, cx));
7803 input = Some(state.clone());
7804 Root(cx.new(|_| Panel {
7805 input: state,
7806 renders: renders.clone(),
7807 }))
7808 });
7809 cx.run_until_parked();
7810 let before = renders.get();
7811 assert!(before > 0);
7812 for _ in 0..60 {
7813 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7814 }
7815 assert_eq!(
7816 renders.get(),
7817 before,
7818 "an idle input must not invalidate its cached parent"
7819 );
7820
7821 let input = input.unwrap();
7822 window
7823 .update(cx, |_, window, cx| {
7824 input.update(cx, |state, cx| state.set_value("changed", window, cx));
7825 })
7826 .unwrap();
7827 assert!(
7828 renders.get() > before,
7829 "text changes must invalidate the parent"
7830 );
7831 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7833 let before = renders.get();
7834 for _ in 0..60 {
7835 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7836 }
7837 assert_eq!(renders.get(), before, "the edited input must settle again");
7838
7839 cx.simulate_window_resize(window.into(), size(px(240.), px(100.)));
7840 cx.run_until_parked();
7841 assert!(renders.get() > before, "resizing must invalidate layout");
7842 }
7843
7844 #[gpui::test]
7845 fn textarea_cursor_treats_crlf_as_one_newline(cx: &mut TestAppContext) {
7846 cx.update(crate::init);
7847 let view = InputView::build_textarea(cx, |state| state);
7848 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
7849 cx.update(|window, cx| {
7850 view.input.update(cx, |state, cx| {
7851 for original in ["\r\nlast", "\u{feff}first\r\nlast\n", "first\nlast\r\n"] {
7852 state.set_value(original, window, cx);
7853 let newline = original.find('\n').unwrap();
7854 let end = if original.as_bytes()[newline.saturating_sub(1)] == b'\r' {
7855 newline - 1
7856 } else {
7857 newline
7858 };
7859 state.end(&MoveEnd, window, cx);
7860 assert_eq!(state.cursor(), end);
7861 state.right(&MoveRight, window, cx);
7862 assert_eq!(state.cursor(), newline + 1);
7863 state.left(&MoveLeft, window, cx);
7864 assert_eq!(state.cursor(), end);
7865 state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
7866 assert_eq!(state.selected_range(), end..end);
7867 state.move_to_end(&MoveToEnd, window, cx);
7868 assert_eq!(state.cursor(), original.len());
7869 state.move_to_start(&MoveToStart, window, cx);
7870 assert_eq!(state.cursor(), 0);
7871 assert_eq!(state.value().as_bytes(), original.as_bytes());
7872 }
7873 state.set_value("a\rb", window, cx);
7875 state.right(&MoveRight, window, cx);
7876 assert_eq!(state.cursor(), 1);
7877 state.right(&MoveRight, window, cx);
7878 assert_eq!(state.cursor(), 2);
7879 })
7880 });
7881 }
7882
7883 #[gpui::test]
7884 fn only_a_multi_line_input_paints_scrollbars(cx: &mut TestAppContext) {
7885 cx.update(crate::init);
7886
7887 let single = InputView::build(cx, |state| state);
7891 single
7892 .input
7893 .update(cx, |state, _| assert!(!state.shows_scrollbar()));
7894
7895 let multi = InputView::build_textarea(cx, |state| state);
7896 multi
7897 .input
7898 .update(cx, |state, _| assert!(state.shows_scrollbar()));
7899 }
7900
7901 #[gpui::test]
7902 fn context_menu_handler_is_deferred_and_respects_disabled(cx: &mut TestAppContext) {
7903 use std::{cell::Cell, rc::Rc};
7904 cx.update(crate::init);
7905 let input_view = InputView::new(cx);
7906 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7907 let input = input_view.input;
7908 let calls = Rc::new(Cell::new(0usize));
7909 let items = Rc::new(Cell::new(0usize));
7910 let menu_focus = cx.update(|_, cx| cx.focus_handle());
7911
7912 cx.update(|window, cx| {
7913 input.update(cx, |state, cx| {
7914 let calls2 = calls.clone();
7915 let items2 = items.clone();
7916 let menu_focus = menu_focus.clone();
7917 state.on_context_menu(Rc::new(move |menu, _, _, window, cx| {
7918 calls2.set(calls2.get() + 1);
7919 items2.set(menu.items.len());
7920 menu_focus.focus(window, cx);
7921 }));
7922 state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx);
7923 })
7924 });
7925 assert_eq!(calls.get(), 1);
7926 assert_eq!(items.get(), 0);
7927 input.read_with(&cx, |state, _| {
7928 assert_eq!(
7929 state
7930 .selection_focus
7931 .as_ref()
7932 .and_then(WeakFocusHandle::upgrade)
7933 .as_ref(),
7934 Some(&menu_focus),
7935 "the menu callback must retain selection without reborrowing its input"
7936 );
7937 });
7938
7939 cx.update(|window, cx| {
7941 input.update(cx, |state, cx| {
7942 state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx);
7943 });
7944 });
7945 assert_eq!(calls.get(), 2);
7946 cx.update(|window, cx| {
7947 assert!(input.read(cx).has_selection_focus(window, cx));
7948 });
7949
7950 cx.update(|window, cx| {
7951 input.update(cx, |state, cx| {
7952 state.disabled = true;
7953 state.handle_right_click_menu(point(px(0.), px(0.)), 0, None, window, cx);
7954 })
7955 });
7956 assert_eq!(calls.get(), 2);
7957 }
7958
7959 #[gpui::test]
7960 fn context_menu_handler_can_read_its_input(cx: &mut TestAppContext) {
7961 use std::{cell::Cell, rc::Rc};
7962 cx.update(crate::init);
7963 let input_view = InputView::new(cx);
7964 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7965 let input = input_view.input;
7966 let cursor = Rc::new(Cell::new(None));
7967
7968 cx.update(|window, cx| {
7969 input.update(cx, |state, cx| {
7970 state.set_value("hello", window, cx);
7971 let weak = cx.weak_entity();
7972 let cursor = cursor.clone();
7973 state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7974 cursor.set(weak.upgrade().map(|input| input.read(cx).cursor()));
7975 }));
7976 state.handle_right_click_menu(point(px(0.), px(0.)), 2, None, window, cx);
7977 })
7978 });
7979 assert_eq!(cursor.get(), Some(2));
7980 }
7981
7982 #[gpui::test]
7983 fn context_menu_handler_can_read_the_offset_under_the_pointer(cx: &mut TestAppContext) {
7984 use std::{cell::Cell, rc::Rc};
7985 cx.update(crate::init);
7986 let input_view = InputView::new(cx);
7987 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
7988 let input = input_view.input;
7989 let seen = Rc::new(Cell::new(None));
7990
7991 cx.update(|window, cx| {
7992 input.update(cx, |state, cx| {
7993 state.set_value("hello world", window, cx);
7994 assert_eq!(state.context_menu_offset(), None);
7995 state.select_all(window, cx);
7996 let weak = cx.weak_entity();
7997 let seen = seen.clone();
7998 state.on_context_menu(Rc::new(move |_, _, _, _, cx| {
7999 seen.set(weak.upgrade().map(|input| {
8000 let input = input.read(cx);
8001 (input.cursor(), input.context_menu_offset())
8002 }));
8003 }));
8004 state.handle_right_click_menu(point(px(0.), px(0.)), 2, None, window, cx);
8006 })
8007 });
8008 assert_eq!(seen.get(), Some((11, Some(2))));
8009 }
8010
8011 #[gpui::test]
8012 fn test_readonly_rejects_user_edits_only(cx: &mut TestAppContext) {
8013 let input_view = InputView::new(cx);
8014 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8015 let input = input_view.input;
8016
8017 cx.update(|window, cx| {
8018 input.update(cx, |state, cx| {
8019 state.set_value("hello", window, cx);
8020 state.set_readonly(true, cx);
8021 });
8022 });
8023
8024 cx.update(|_, cx| {
8025 input.read_with(cx, |state, _| {
8026 assert!(!state.is_editable());
8027 assert!(!state.is_replaceable());
8028 });
8029 });
8030
8031 cx.update(|window, cx| {
8033 input.update(cx, |state, cx| {
8034 state.replace_text_in_range(None, " world", window, cx);
8035 state.replace_and_mark_text_in_range(None, "あ", None, window, cx);
8036 });
8037 });
8038 cx.update(|_, cx| {
8039 input.read_with(cx, |state, _| assert_eq!(state.value(), "hello"));
8040 });
8041
8042 cx.update(|window, cx| {
8044 input.update(cx, |state, cx| {
8045 state.insert(" world", window, cx);
8046 state.set_value("changed", window, cx);
8047 });
8048 });
8049 cx.update(|_, cx| {
8050 input.read_with(cx, |state, _| assert_eq!(state.value(), "changed"));
8051 });
8052
8053 cx.update(|window, cx| {
8056 input.update(cx, |state, cx| {
8057 state.set_readonly(false, cx);
8058 state.replace_text_in_range(None, "!", window, cx);
8059 });
8060 });
8061 cx.update(|_, cx| {
8062 input.read_with(cx, |state, _| {
8063 assert!(state.is_editable());
8064 assert_eq!(state.value(), "!changed");
8065 });
8066 });
8067 }
8068
8069 #[gpui::test]
8074 fn test_edit_reveals_far_offscreen_caret(cx: &mut TestAppContext) {
8075 let mut input = None;
8076 let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
8077 cx.set_global(Theme::default());
8078 super::super::init(cx);
8079 let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 6));
8080 input = Some(state.clone());
8081 TestRoot(state)
8082 });
8083 let mut cx = VisualTestContext::from_window(window.into(), cx);
8084 let input = input.unwrap();
8085
8086 let text: String = (1..=100)
8087 .map(|i| format!("line {i}"))
8088 .collect::<Vec<_>>()
8089 .join("\n");
8090 cx.update(|window, cx| {
8091 input.update(cx, |state, cx| {
8092 state.set_value(text, window, cx);
8093 let end = state.text.len();
8094 state.set_selection(end, end);
8095 });
8096 });
8097 cx.run_until_parked();
8098
8099 cx.update(|_, cx| {
8101 input.update(cx, |state, cx| {
8102 state.scroll_handle.set_offset(point(px(0.), px(0.)));
8103 cx.notify();
8104 });
8105 });
8106 cx.run_until_parked();
8107
8108 cx.update(|window, cx| {
8109 input.update(cx, |state, cx| {
8110 state.replace_text_in_range(None, "X", window, cx);
8111 });
8112 });
8113 cx.run_until_parked();
8114
8115 cx.update(|_, cx| {
8116 input.read_with(cx, |state, _| {
8117 assert!(state.value().ends_with("line 100X"));
8118 let (caret, _) = state.cursor_layout().expect("caret painted");
8119 let viewport = state.input_bounds();
8120 let scroll_y = state.scroll_handle.offset().y;
8121 let top = caret.origin.y + scroll_y - viewport.origin.y;
8122 assert!(
8123 top >= px(0.) && top + caret.size.height <= viewport.size.height,
8124 "caret top {top:?} outside viewport height {:?} (scroll {scroll_y:?})",
8125 viewport.size.height,
8126 );
8127 });
8128 });
8129 }
8130
8131 #[gpui::test]
8135 fn test_set_auto_grow_keeps_rows_fitted(cx: &mut TestAppContext) {
8136 let mut input = None;
8137 let window = cx.open_window(size(px(720.), px(400.)), |window, cx| {
8138 cx.set_global(Theme::default());
8139 super::super::init(cx);
8140 let state = cx.new(|cx| crate::input::TextareaState::new(window, cx).auto_grow(1, 10));
8141 input = Some(state.clone());
8142 TestRoot(state)
8143 });
8144 let mut cx = VisualTestContext::from_window(window.into(), cx);
8145 let input = input.unwrap();
8146
8147 let text: String = (1..=8)
8148 .map(|i| format!("line {i}"))
8149 .collect::<Vec<_>>()
8150 .join("\n");
8151 cx.update(|window, cx| {
8152 input.update(cx, |state, cx| state.set_value(text, window, cx));
8153 });
8154 cx.run_until_parked();
8155 cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
8156
8157 cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 12, cx)));
8159 cx.run_until_parked();
8160 cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 8)));
8161
8162 cx.update(|_, cx| input.update(cx, |state, cx| state.set_auto_grow(1, 4, cx)));
8164 cx.run_until_parked();
8165 cx.update(|_, cx| input.read_with(cx, |state, _| assert_eq!(state.mode.rows(), 4)));
8166 }
8167
8168 #[gpui::test]
8174 fn test_scroll_to_eob_does_not_overshoot_safe_range(cx: &mut TestAppContext) {
8175 let input_view = InputView::new(cx);
8176 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8177 let input = input_view.input;
8178
8179 cx.update(|window, cx| {
8181 input.update(cx, |state, cx| {
8182 state.set_scroll_beyond_last_line(Some(1), window, cx);
8183 state.set_cursor_surrounding_lines(Some(1), window, cx);
8184 let text: String = (1..=50)
8185 .map(|i| format!("line {i}"))
8186 .collect::<Vec<_>>()
8187 .join("\n");
8188 state.set_value(text, window, cx);
8189 });
8190 });
8191 cx.run_until_parked();
8192
8193 cx.update(|_, cx| {
8196 input.read_with(cx, |state, _| {
8197 assert!(
8198 state.scroll_size.height > px(0.),
8199 "scroll_size not populated by initial paint"
8200 );
8201 assert!(
8202 state.input_bounds.size.height > px(0.),
8203 "input_bounds not populated by initial paint"
8204 );
8205 });
8206 });
8207
8208 cx.update(|_, cx| {
8213 input.update(cx, |state, cx| {
8214 let end = state.text.len();
8215 state.move_to(end, Some(MoveDirection::Down), cx);
8216
8217 let deferred = state
8218 .deferred_scroll_offset
8219 .expect("scroll_to should populate deferred_scroll_offset");
8220 let safe_y_min =
8221 (-state.scroll_size.height + state.input_bounds.size.height).min(px(0.));
8222
8223 assert!(
8224 deferred.y >= safe_y_min,
8225 "deferred_scroll_offset.y = {:?} below safe_y_min = {:?} \
8226 — paint would jitter (Bug C regression)",
8227 deferred.y,
8228 safe_y_min,
8229 );
8230 });
8231 });
8232 }
8233
8234 #[gpui::test]
8235 fn test_next_search_match_reveals_with_padding_after_manual_scroll(cx: &mut TestAppContext) {
8236 assert_search_reveals_with_padding_after_manual_scroll(false, cx);
8237 }
8238
8239 #[gpui::test]
8240 fn test_previous_search_match_reveals_with_padding_after_manual_scroll(
8241 cx: &mut TestAppContext,
8242 ) {
8243 assert_search_reveals_with_padding_after_manual_scroll(true, cx);
8244 }
8245
8246 fn assert_search_reveals_with_padding_after_manual_scroll(
8247 previous: bool,
8248 cx: &mut TestAppContext,
8249 ) {
8250 let input_view = InputView::new(cx);
8251 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8252 let input = input_view.input;
8253 let text = (0..160)
8254 .map(|row| {
8255 if matches!(row, 20 | 60 | 100) {
8256 format!("match on row {row}")
8257 } else {
8258 format!("line {row}")
8259 }
8260 })
8261 .collect::<Vec<_>>()
8262 .join("\n");
8263 let start = text.match_indices("match").nth(1).unwrap().0;
8264 let expected_match = start..start + "match".len();
8265 cx.update(|window, cx| {
8266 input.update(cx, |state, cx| {
8267 state.set_cursor_surrounding_lines(Some(3), window, cx);
8268 state.set_value(text, window, cx);
8269 state.set_search_query("match", true, cx);
8270 if previous {
8271 state.search_session.matcher.next();
8272 state.search_session.matcher.next();
8273 }
8274 });
8275 });
8276 cx.run_until_parked();
8277 cx.update(|_, cx| {
8278 input.update(cx, |state, cx| {
8279 let line_height = state.last_layout.as_ref().unwrap().line_height;
8280 let y = if previous { px(0.) } else { -line_height * 80. };
8281 state.set_scroll_offset(point(px(0.), y), cx);
8282 });
8283 });
8284 cx.run_until_parked();
8285 input.read_with(&cx, |state, _| {
8286 let visible = state.visible_row_range().unwrap();
8287 if previous {
8288 assert!(visible.end <= 60, "target must be below the viewport");
8289 } else {
8290 assert!(visible.start > 60, "target must be above the viewport");
8291 }
8292 });
8293 cx.update(|_, cx| {
8294 input.update(cx, |state, cx| {
8295 let range = if previous {
8296 state.previous_search_match(cx)
8297 } else {
8298 state.next_search_match(cx)
8299 };
8300 assert_eq!(range, Some(expected_match));
8301 assert_eq!(state.search_session.matcher.label(), "2/3");
8302 });
8303 });
8304 cx.run_until_parked();
8305 input.read_with(&cx, |state, _| {
8306 assert!(state.visible_row_range().unwrap().contains(&60));
8307 let line_height = state.last_layout.as_ref().unwrap().line_height;
8308 let target_y = line_height * 60. + state.scroll_handle.offset().y;
8309 assert!(target_y >= line_height * 2. - px(0.1));
8311 assert!(
8312 target_y + line_height * 3.
8313 <= state.last_bounds.as_ref().unwrap().size.height + px(0.1),
8314 "search must preserve the configured surrounding-line padding"
8315 );
8316 });
8317 }
8318
8319 struct SearchHost {
8321 editor: Entity<InputBaseState<EditorMode>>,
8322 search_requests: Rc<Cell<usize>>,
8323 }
8324
8325 impl Render for SearchHost {
8326 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8327 let search_requests = self.search_requests.clone();
8328 div()
8329 .size_full()
8330 .on_action(cx.listener(move |_, _: &Search, _, _| {
8331 search_requests.set(search_requests.get() + 1);
8332 }))
8333 .child(self.editor.clone())
8334 }
8335 }
8336
8337 fn press_search_shortcut(
8340 cx: &mut TestAppContext,
8341 searchable: bool,
8342 ) -> (Entity<InputBaseState<EditorMode>>, Rc<Cell<usize>>) {
8343 let search_requests = Rc::new(Cell::new(0));
8344 let mut editor = None;
8345 let window = cx.update(|cx| {
8346 cx.open_window(Default::default(), |window, cx| {
8347 cx.set_global(Theme::default());
8348 super::super::init(cx);
8349 let state =
8350 cx.new(|cx| crate::input::EditorState::new(window, cx).searchable(searchable));
8351 editor = Some(state.clone());
8352 cx.new(|_| SearchHost {
8353 editor: state,
8354 search_requests: search_requests.clone(),
8355 })
8356 })
8357 .unwrap()
8358 });
8359 let editor = editor.unwrap();
8360 let mut cx = VisualTestContext::from_window(window.into(), cx);
8361 cx.update(|window, cx| {
8362 editor.update(cx, |state, cx| state.focus(window, cx));
8363 });
8364 cx.run_until_parked();
8365 #[cfg(target_os = "macos")]
8366 cx.simulate_keystrokes("cmd-f");
8367 #[cfg(not(target_os = "macos"))]
8368 cx.simulate_keystrokes("ctrl-f");
8369 cx.run_until_parked();
8370 (editor, search_requests)
8371 }
8372
8373 #[gpui::test]
8374 fn test_search_shortcut_reaches_the_host_when_not_searchable(cx: &mut TestAppContext) {
8375 let (editor, search_requests) = press_search_shortcut(cx, false);
8376 assert_eq!(search_requests.get(), 1);
8377 editor.read_with(cx, |state, _| {
8378 assert!(!state.search_session().open);
8379 assert!(!state.search_session().is_active());
8380 });
8381 }
8382
8383 #[gpui::test]
8384 fn test_search_shortcut_opens_the_panel_when_searchable(cx: &mut TestAppContext) {
8385 let (editor, search_requests) = press_search_shortcut(cx, true);
8386 assert_eq!(search_requests.get(), 0);
8387 editor.read_with(cx, |state, _| {
8388 assert!(state.search_session().open);
8389 assert!(state.search_session().is_active());
8390 });
8391 }
8392
8393 #[gpui::test]
8394 fn test_set_search_query_highlights_without_the_panel(cx: &mut TestAppContext) {
8395 let input_view = InputView::build_editor(cx, |state| state.searchable(false));
8396 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8397 let input = input_view.input;
8398 cx.update(|window, cx| {
8399 input.update(cx, |state, cx| {
8400 state.set_value("foo bar foo", window, cx);
8401 state.set_search_query("foo", true, cx);
8402 });
8403 });
8404 cx.run_until_parked();
8405 input.read_with(&cx, |state, _| {
8406 let session = state.search_session();
8407 assert!(session.is_active());
8408 assert!(!session.open);
8409 assert_eq!(session.matcher.len(), 2);
8410 });
8411 cx.update(|_, cx| {
8412 input.update(cx, |state, cx| state.close_search(cx));
8413 });
8414 input.read_with(&cx, |state, _| {
8415 assert!(!state.search_session().is_active());
8416 });
8417 }
8418
8419 #[gpui::test]
8422 fn test_closed_search_resyncs_matches_after_edits(cx: &mut TestAppContext) {
8423 let input_view = InputView::build_editor(cx, |state| state.searchable(false));
8424 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8425 let input = input_view.input;
8426 cx.update(|window, cx| {
8427 input.update(cx, |state, cx| {
8428 state.set_value("foo bar foo", window, cx);
8429 state.set_search_query("foo", true, cx);
8430 state.close_search(cx);
8431
8432 state.set_value("bar foo", window, cx);
8433 assert_eq!(state.next_search_match(cx), Some(4..7));
8434
8435 state.set_value("foo foo foo", window, cx);
8436 state.set_search_query("foo", true, cx);
8437 assert_eq!(state.search_session().matcher.len(), 3);
8438 });
8439 });
8440 }
8441
8442 #[gpui::test]
8443 fn test_search_reveals_offscreen_wrapped_match(cx: &mut TestAppContext) {
8444 let input_view = InputView::new(cx);
8445 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8446 let input = input_view.input;
8447 let text = format!(
8448 "match\n{}\n{}match\n{}",
8449 "line\n".repeat(80),
8450 "wrapped text ".repeat(500),
8451 "line\n".repeat(80)
8452 );
8453 cx.update(|window, cx| {
8454 input.update(cx, |state, cx| {
8455 state.set_cursor_surrounding_lines(Some(3), window, cx);
8456 state.set_value(text, window, cx);
8457 state.set_search_query("match", true, cx);
8458 });
8459 });
8460 cx.run_until_parked();
8461 cx.update(|_, cx| {
8462 input.update(cx, |state, cx| {
8463 state.next_search_match(cx).unwrap();
8464 });
8465 });
8466 cx.run_until_parked();
8467 input.read_with(&cx, |state, _| {
8468 let range = state.search_session.matcher.matched_ranges()[1].clone();
8469 let layout = state.last_layout.as_ref().unwrap();
8470 let (_, _, position) = state.line_and_position_for_offset(range.end);
8471 let y = position.expect("wrapped match must be laid out").y;
8472 assert!(y >= layout.line_height * 2. - px(0.1));
8473 assert!(
8474 y + layout.line_height * 3. <= state.last_bounds.unwrap().size.height + px(0.1),
8475 "wrapped match must retain surrounding display rows"
8476 );
8477 });
8478 }
8479
8480 #[gpui::test]
8481 fn test_number_step(cx: &mut TestAppContext) {
8482 let input = InputView::build(cx, |state| state).input;
8483
8484 cx.update(|cx| {
8485 input.update(cx, |_state, cx| {
8486 assert_eq!(
8487 NumberStep::from(5.).value(123., StepAction::Increment, cx),
8488 5.
8489 );
8490
8491 let step = NumberStep::by_value(|value, action, _cx| {
8494 let below = match action {
8495 StepAction::Increment => value < 1.0,
8496 StepAction::Decrement => value <= 1.0,
8497 };
8498 if below { 0.1 } else { 0.5 }
8499 });
8500 assert_eq!(step.value(0.5, StepAction::Increment, cx), 0.1);
8501 assert_eq!(step.value(1.0, StepAction::Increment, cx), 0.5);
8502 assert_eq!(step.value(1.0, StepAction::Decrement, cx), 0.1);
8503 assert_eq!(step.value(2.0, StepAction::Decrement, cx), 0.5);
8504 });
8505 });
8506 }
8507
8508 #[gpui::test]
8509 fn test_number_input_normalization(cx: &mut TestAppContext) {
8510 let input_view = InputView::build(cx, |state| {
8511 state.mask_pattern(MaskPattern::Number {
8512 separator: None,
8513 fraction: None,
8514 })
8515 });
8516 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8517 let input = input_view.input;
8518
8519 cx.update(|window, cx| {
8523 input.update(cx, |state, cx| {
8524 state.replace_text_in_range(None, "12。5", window, cx);
8525 });
8526 });
8527 cx.run_until_parked();
8528 cx.update(|_, cx| {
8529 input.read_with(cx, |state, _| {
8530 assert_eq!(state.value(), "12.5");
8531 let cursor: Range<usize> = state.selected_range();
8532 assert_eq!(cursor, 4..4);
8533 });
8534 });
8535
8536 cx.update(|window, cx| {
8538 input.update(cx, |state, cx| {
8539 state.replace_text_in_range(None, "abc", window, cx);
8540 });
8541 });
8542 cx.run_until_parked();
8543 cx.update(|_, cx| {
8544 input.read_with(cx, |state, _| {
8545 assert_eq!(state.value(), "12.5");
8546 });
8547 });
8548
8549 cx.update(|window, cx| {
8552 input.update(cx, |state, cx| {
8553 let range = state.range_to_utf16(&(0..state.text.len()));
8554 state.replace_text_in_range(Some(range), "。", window, cx);
8555 });
8556 });
8557 cx.run_until_parked();
8558 cx.update(|_, cx| {
8559 input.read_with(cx, |state, _| {
8560 assert_eq!(state.value(), ".");
8561 let cursor: Range<usize> = state.selected_range();
8562 assert_eq!(cursor, 1..1);
8563 });
8564 });
8565 }
8566
8567 #[gpui::test]
8568 fn test_mask_pattern_accepts_non_ascii_text(cx: &mut TestAppContext) {
8569 let input_view = InputView::build(cx, |state| state.mask_pattern("9999年99月"));
8570 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8571 let input = input_view.input;
8572
8573 cx.update(|window, cx| {
8574 input.update(cx, |state, cx| {
8575 state.replace_text_in_range(None, "2024年12月", window, cx);
8576 });
8577 });
8578 cx.run_until_parked();
8579 cx.update(|_, cx| {
8580 input.read_with(cx, |state, _| {
8581 assert_eq!(state.value(), "2024年12月");
8582 });
8583 });
8584 }
8585
8586 #[gpui::test]
8587 fn test_number_input_normalization_with_separator(cx: &mut TestAppContext) {
8588 let input_view = InputView::build(cx, |state| {
8589 state.mask_pattern(MaskPattern::Number {
8590 separator: Some(','),
8591 fraction: Some(2),
8592 })
8593 });
8594 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8595 let input = input_view.input;
8596
8597 cx.update(|window, cx| {
8598 input.update(cx, |state, cx| {
8599 state.replace_text_in_range(None, "1234", window, cx);
8600 });
8601 });
8602 cx.run_until_parked();
8603 cx.update(|_, cx| {
8604 input.read_with(cx, |state, _| {
8605 assert_eq!(state.value(), "1,234");
8606 assert_eq!(state.unmask_value(), "1234");
8607 });
8608 });
8609 }
8610
8611 #[gpui::test]
8612 fn test_number_input_clamp_on_blur(cx: &mut TestAppContext) {
8613 let input_view = InputView::build(cx, |state| {
8614 state
8615 .mask_pattern(MaskPattern::Number {
8616 separator: None,
8617 fraction: None,
8618 })
8619 .min(10.)
8620 .max(100.)
8621 });
8622 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8623 let input = input_view.input;
8624
8625 cx.update(|window, cx| {
8627 input.update(cx, |state, cx| {
8628 state.replace_text_in_range(None, "1000", window, cx);
8629 assert_eq!(state.value(), "1000");
8630 state.clamp_number_value(window, cx);
8631 assert_eq!(state.value(), "100");
8632
8633 let range = state.range_to_utf16(&(0..state.text.len()));
8634 state.replace_text_in_range(Some(range), "1", window, cx);
8635 assert_eq!(state.value(), "1");
8636 state.clamp_number_value(window, cx);
8637 assert_eq!(state.value(), "10");
8638 });
8639 });
8640 }
8641
8642 #[gpui::test]
8643 fn test_number_input_undo_with_mask(cx: &mut TestAppContext) {
8644 let input_view = InputView::build(cx, |state| {
8645 state.mask_pattern(MaskPattern::Number {
8646 separator: Some(','),
8647 fraction: None,
8648 })
8649 });
8650 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8651 let input = input_view.input;
8652
8653 cx.update(|window, cx| {
8656 input.update(cx, |state, cx| {
8657 state.replace_text_in_range(None, "1234", window, cx);
8658 assert_eq!(state.value(), "1,234");
8659 state.replace_text_in_range(None, "5", window, cx);
8660 assert_eq!(state.value(), "12,345");
8661
8662 state.undo(&Undo, window, cx);
8666 assert_eq!(state.value(), "1,234");
8667 state.undo(&Undo, window, cx);
8668 assert_eq!(state.value(), "");
8669 state.redo(&Redo, window, cx);
8670 assert_eq!(state.value(), "1,234");
8671 state.redo(&Redo, window, cx);
8672 assert_eq!(state.value(), "12,345");
8673 });
8674 });
8675 }
8676
8677 #[gpui::test]
8678 fn test_undo_manager_coalesces_adjacent_typing_transactions(cx: &mut TestAppContext) {
8679 let input_view = InputView::build(cx, |state| state);
8680 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8681 let input = input_view.input;
8682
8683 cx.update(|window, cx| {
8684 input.update(cx, |state, cx| {
8685 state.replace_text_in_range(None, "a", window, cx);
8686 state.replace_text_in_range(None, "b", window, cx);
8687 assert_eq!(state.value(), "ab");
8688
8689 state.undo(&Undo, window, cx);
8690 assert_eq!(state.value(), "");
8691 });
8692 });
8693 }
8694
8695 #[gpui::test]
8696 fn test_undo_manager_cursor_movement_splits_typing(cx: &mut TestAppContext) {
8697 let input_view = InputView::build(cx, |state| state);
8698 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8699 let input = input_view.input;
8700
8701 cx.update(|window, cx| {
8702 input.update(cx, |state, cx| {
8703 state.replace_text_in_range(None, "a", window, cx);
8704 state.replace_text_in_range(None, "b", window, cx);
8705 state.left(&MoveLeft, window, cx);
8706 state.replace_text_in_range(None, "x", window, cx);
8707 assert_eq!(state.value(), "axb");
8708
8709 state.undo(&Undo, window, cx);
8710 assert_eq!(state.value(), "ab");
8711 state.undo(&Undo, window, cx);
8712 assert_eq!(state.value(), "");
8713 });
8714 });
8715 }
8716
8717 #[gpui::test]
8718 fn test_undo_manager_splits_backward_and_forward_delete(cx: &mut TestAppContext) {
8719 let input_view = InputView::build(cx, |state| state);
8720 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8721 let input = input_view.input;
8722
8723 cx.update(|window, cx| {
8724 input.update(cx, |state, cx| {
8725 state.set_value("abcd", window, cx);
8726 state.set_selected_range(2..2, cx);
8727 state.backspace(&Backspace, window, cx);
8728 state.delete(&Delete, window, cx);
8729 assert_eq!(state.value(), "ad");
8730
8731 state.undo(&Undo, window, cx);
8732 assert_eq!(state.value(), "acd");
8733 state.undo(&Undo, window, cx);
8734 assert_eq!(state.value(), "abcd");
8735 });
8736 });
8737 }
8738
8739 #[gpui::test]
8740 fn test_undo_manager_coalesces_directional_character_deletes(cx: &mut TestAppContext) {
8741 let input_view = InputView::build(cx, |state| state);
8742 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8743 let input = input_view.input;
8744
8745 cx.update(|window, cx| {
8746 input.update(cx, |state, cx| {
8747 state.set_value("abcd", window, cx);
8748 state.backspace(&Backspace, window, cx);
8749 state.backspace(&Backspace, window, cx);
8750 assert_eq!(state.value(), "ab");
8751 state.undo(&Undo, window, cx);
8752 assert_eq!(state.value(), "abcd");
8753 assert_eq!(state.selected_range(), 4..4);
8754
8755 state.set_value("abcd", window, cx);
8756 state.set_selected_range(1..1, cx);
8757 state.delete(&Delete, window, cx);
8758 state.delete(&Delete, window, cx);
8759 assert_eq!(state.value(), "ad");
8760 state.undo(&Undo, window, cx);
8761 assert_eq!(state.value(), "abcd");
8762 assert_eq!(state.selected_range(), 1..1);
8763 });
8764 });
8765 }
8766
8767 #[gpui::test]
8768 fn test_undo_manager_atomic_paste_isolated_from_typing(cx: &mut TestAppContext) {
8769 let input_view = InputView::build(cx, |state| state);
8770 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8771 let input = input_view.input;
8772
8773 cx.update(|window, cx| {
8774 cx.write_to_clipboard(ClipboardItem::new_string("P".to_string()));
8775 input.update(cx, |state, cx| {
8776 state.replace_text_in_range(None, "a", window, cx);
8777 state.paste(&Paste, window, cx);
8778 state.replace_text_in_range(None, "b", window, cx);
8779 assert_eq!(state.value(), "aPb");
8780
8781 state.undo(&Undo, window, cx);
8782 assert_eq!(state.value(), "aP");
8783 state.undo(&Undo, window, cx);
8784 assert_eq!(state.value(), "a");
8785 state.undo(&Undo, window, cx);
8786 assert_eq!(state.value(), "");
8787 });
8788 });
8789 }
8790
8791 #[gpui::test]
8792 fn test_undo_manager_programmatic_insert_is_atomic(cx: &mut TestAppContext) {
8793 let input_view = InputView::build(cx, |state| state);
8794 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8795 let input = input_view.input;
8796
8797 cx.update(|window, cx| {
8798 input.update(cx, |state, cx| {
8799 state.replace_text_in_range(None, "a", window, cx);
8800 state.insert("P", window, cx);
8801 state.replace_text_in_range(None, "b", window, cx);
8802 assert_eq!(state.value(), "aPb");
8803
8804 state.undo(&Undo, window, cx);
8805 assert_eq!(state.value(), "aP");
8806 state.undo(&Undo, window, cx);
8807 assert_eq!(state.value(), "a");
8808 });
8809 });
8810 }
8811
8812 #[gpui::test]
8813 fn test_undo_manager_selection_round_trip_splits_typing(cx: &mut TestAppContext) {
8814 let input_view = InputView::build(cx, |state| state);
8815 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8816 let input = input_view.input;
8817
8818 cx.update(|window, cx| {
8819 input.update(cx, |state, cx| {
8820 state.replace_text_in_range(None, "a", window, cx);
8821 state.replace_text_in_range(None, "b", window, cx);
8822 state.select_all(window, cx);
8823 state.unselect(window, cx);
8824 state.replace_text_in_range(None, "c", window, cx);
8825
8826 state.undo(&Undo, window, cx);
8827 assert_eq!(state.value(), "ab");
8828 state.undo(&Undo, window, cx);
8829 assert_eq!(state.value(), "");
8830 });
8831 });
8832 }
8833
8834 #[gpui::test]
8835 fn test_undo_manager_enter_is_atomic(cx: &mut TestAppContext) {
8836 let input_view = InputView::build_textarea(cx, |state| state);
8837 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8838 let input = input_view.input;
8839
8840 cx.update(|window, cx| {
8841 input.update(cx, |state, cx| {
8842 state.replace_text_in_range(None, "a", window, cx);
8843 state.enter(
8844 &Enter {
8845 secondary: false,
8846 shift: false,
8847 },
8848 window,
8849 cx,
8850 );
8851 state.replace_text_in_range(None, "b", window, cx);
8852
8853 state.undo(&Undo, window, cx);
8854 assert_eq!(state.value(), "a\n");
8855 state.undo(&Undo, window, cx);
8856 assert_eq!(state.value(), "a");
8857 state.undo(&Undo, window, cx);
8858 assert_eq!(state.value(), "");
8859 });
8860 });
8861 }
8862
8863 #[gpui::test]
8864 fn test_textarea_secondary_enter_does_not_insert_newline(cx: &mut TestAppContext) {
8865 let input_view = InputView::build_textarea(cx, |state| state);
8866 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8867 let input = input_view.input;
8868
8869 cx.update(|window, cx| {
8870 input.update(cx, |state, cx| {
8871 state.replace_text_in_range(None, "hello", window, cx);
8872 state.set_selection(0, 0);
8873 state.enter(
8874 &Enter {
8875 secondary: true,
8876 shift: false,
8877 },
8878 window,
8879 cx,
8880 );
8881 assert_eq!(state.value(), "hello");
8882 });
8883 });
8884 }
8885
8886 #[gpui::test]
8887 fn test_undo_manager_single_line_return_commits_the_typing_session(cx: &mut TestAppContext) {
8888 let input_view = InputView::build(cx, |state| state);
8889 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8890 let input = input_view.input;
8891
8892 cx.update(|window, cx| {
8893 input.update(cx, |state, cx| {
8894 for part in ["a", "b", "c"] {
8895 state.replace_text_in_range(None, part, window, cx);
8896 }
8897 state.enter(
8898 &Enter {
8899 secondary: false,
8900 shift: false,
8901 },
8902 window,
8903 cx,
8904 );
8905 for part in ["d", "e", "f"] {
8906 state.replace_text_in_range(None, part, window, cx);
8907 }
8908 assert_eq!(state.value(), "abcdef");
8909
8910 state.undo(&Undo, window, cx);
8911 assert_eq!(state.value(), "abc");
8912 state.undo(&Undo, window, cx);
8913 assert_eq!(state.value(), "");
8914 });
8915 });
8916 }
8917
8918 #[gpui::test]
8919 fn test_undo_manager_submit_on_enter_commits_the_textarea_session(cx: &mut TestAppContext) {
8920 let input_view = InputView::build_textarea(cx, |state| state.submit_on_enter(true));
8921 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8922 let input = input_view.input;
8923
8924 cx.update(|window, cx| {
8925 input.update(cx, |state, cx| {
8926 state.replace_text_in_range(None, "before submit", window, cx);
8927 state.enter(
8928 &Enter {
8929 secondary: false,
8930 shift: false,
8931 },
8932 window,
8933 cx,
8934 );
8935 state.replace_text_in_range(None, " after submit", window, cx);
8936 assert_eq!(state.value(), "before submit after submit");
8937
8938 state.undo(&Undo, window, cx);
8939 assert_eq!(state.value(), "before submit");
8940 state.undo(&Undo, window, cx);
8941 assert_eq!(state.value(), "");
8942 });
8943 });
8944 }
8945
8946 #[gpui::test]
8947 fn test_undo_manager_blur_commits_the_typing_session(cx: &mut TestAppContext) {
8948 let input_view = InputView::build(cx, |state| state);
8949 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8950 let input = input_view.input;
8951
8952 cx.update(|window, cx| {
8953 input.update(cx, |state, cx| {
8954 state.replace_text_in_range(None, "before blur", window, cx);
8955 state.on_blur(window, cx);
8956 state.on_focus(window, cx);
8957 state.replace_text_in_range(None, " after focus", window, cx);
8958 assert_eq!(state.value(), "before blur after focus");
8959
8960 state.undo(&Undo, window, cx);
8961 assert_eq!(state.value(), "before blur");
8962 state.undo(&Undo, window, cx);
8963 assert_eq!(state.value(), "");
8964 });
8965 });
8966 }
8967
8968 #[gpui::test]
8969 fn test_undo_manager_keeps_rapid_lines_in_distinct_transactions(cx: &mut TestAppContext) {
8970 let input_view = InputView::build_textarea(cx, |state| state);
8971 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8972 let input = input_view.input;
8973
8974 cx.update(|window, cx| {
8975 input.update(cx, |state, cx| {
8976 let enter = Enter {
8977 secondary: false,
8978 shift: false,
8979 };
8980 state.replace_text_in_range(None, "a", window, cx);
8981 state.enter(&enter, window, cx);
8982 state.replace_text_in_range(None, "b", window, cx);
8983 state.enter(&enter, window, cx);
8984 state.replace_text_in_range(None, "c", window, cx);
8985 assert_eq!(state.value(), "a\nb\nc");
8986
8987 for expected in ["a\nb\n", "a\nb", "a\n", "a", ""] {
8988 state.undo(&Undo, window, cx);
8989 assert_eq!(state.value(), expected);
8990 }
8991 });
8992 });
8993 }
8994
8995 #[gpui::test]
8996 fn test_undo_manager_coalesces_long_unicode_typing_without_a_timer(cx: &mut TestAppContext) {
8997 let input_view = InputView::build_textarea(cx, |state| state);
8998 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
8999 let input = input_view.input;
9000 let parts = [
9001 "The ",
9002 "quick ",
9003 "brown fox, ",
9004 "你好,世界 ",
9005 "🦀 jumps over 13 lazy dogs.",
9006 ];
9007 let expected = parts.concat();
9008
9009 cx.update(|window, cx| {
9010 input.update(cx, |state, cx| {
9011 for part in parts {
9012 state.replace_text_in_range(None, part, window, cx);
9013 }
9014 assert_eq!(state.value(), expected);
9015
9016 state.undo(&Undo, window, cx);
9017 assert_eq!(state.value(), "");
9018 state.redo(&Redo, window, cx);
9019 assert_eq!(state.value(), expected);
9020 });
9021 });
9022 }
9023
9024 #[gpui::test]
9025 fn test_undo_manager_long_multiline_sequence_has_structural_boundaries(
9026 cx: &mut TestAppContext,
9027 ) {
9028 let input_view = InputView::build_textarea(cx, |state| state);
9029 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9030 let input = input_view.input;
9031 let enter = Enter {
9032 secondary: false,
9033 shift: false,
9034 };
9035
9036 cx.update(|window, cx| {
9037 input.update(cx, |state, cx| {
9038 for (index, line) in [
9039 "first line with punctuation!",
9040 "第二行包含 Unicode 🦀",
9041 "third line has several words",
9042 ]
9043 .into_iter()
9044 .enumerate()
9045 {
9046 for chunk in line.split_inclusive(' ') {
9047 state.replace_text_in_range(None, chunk, window, cx);
9048 }
9049 if index < 2 {
9050 state.enter(&enter, window, cx);
9051 }
9052 }
9053
9054 assert_eq!(
9055 state.value(),
9056 "first line with punctuation!\n第二行包含 Unicode 🦀\nthird line has several words"
9057 );
9058 state.undo(&Undo, window, cx);
9059 assert_eq!(
9060 state.value(),
9061 "first line with punctuation!\n第二行包含 Unicode 🦀\n"
9062 );
9063 state.undo(&Undo, window, cx);
9064 assert_eq!(
9065 state.value(),
9066 "first line with punctuation!\n第二行包含 Unicode 🦀"
9067 );
9068 state.undo(&Undo, window, cx);
9069 assert_eq!(state.value(), "first line with punctuation!\n");
9070 });
9071 });
9072 }
9073
9074 #[gpui::test]
9075 fn test_masked_input_keeps_its_value_out_of_the_clipboard(cx: &mut TestAppContext) {
9076 let input_view = InputView::build(cx, |state| state);
9077 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9078 let input = input_view.input;
9079
9080 cx.update(|window, cx| {
9081 input.update(cx, |state, cx| {
9082 state.set_value("hunter2", window, cx);
9083 state.set_masked(true, window, cx);
9084 state.select_all(window, cx);
9085 cx.write_to_clipboard(ClipboardItem::new_string("sentinel".into()));
9086
9087 state.copy(&Copy, window, cx);
9088 assert_eq!(
9089 cx.read_from_clipboard().and_then(|item| item.text()),
9090 Some("sentinel".to_string())
9091 );
9092
9093 state.cut(&Cut, window, cx);
9095 assert_eq!(state.value(), "hunter2");
9096 assert_eq!(
9097 cx.read_from_clipboard().and_then(|item| item.text()),
9098 Some("sentinel".to_string())
9099 );
9100
9101 state.set_masked(false, window, cx);
9103 state.copy(&Copy, window, cx);
9104 assert_eq!(
9105 cx.read_from_clipboard().and_then(|item| item.text()),
9106 Some("hunter2".to_string())
9107 );
9108 });
9109 });
9110 }
9111
9112 #[gpui::test]
9113 fn test_masked_input_redacts_ime_text(cx: &mut TestAppContext) {
9114 let input_view = InputView::build(cx, |state| state.masked(true).default_value("a🦀b"));
9115 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9116 cx.update(|window, cx| {
9117 input_view.input.update(cx, |state, cx| {
9118 let mut adjusted = None;
9119 assert_eq!(
9120 state.text_for_range(1..5, &mut adjusted, window, cx),
9121 Some("•••".into())
9122 );
9123 assert_eq!(adjusted, Some(1..4));
9124
9125 state.set_masked(false, window, cx);
9126 assert_eq!(
9127 state.text_for_range(1..5, &mut adjusted, window, cx),
9128 Some("🦀b".into())
9129 );
9130 assert_eq!(adjusted, Some(1..4));
9131 });
9132 });
9133 }
9134
9135 #[gpui::test]
9136 fn test_masked_input_collapses_word_boundaries(cx: &mut TestAppContext) {
9137 let input_view = InputView::build(cx, |state| state);
9138 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9139 let input = input_view.input;
9140
9141 cx.update(|window, cx| {
9142 input.update(cx, |state, cx| {
9143 state.set_value("aaa bbb ccc", window, cx);
9144 state.set_masked(true, window, cx);
9145 state.set_selected_range(7..7, cx);
9146
9147 state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
9150 assert_eq!(state.value(), " ccc");
9151 assert_eq!(state.selected_range(), 0..0);
9152
9153 state.delete_next_word(&DeleteToNextWordEnd, window, cx);
9154 assert_eq!(state.value(), "");
9155
9156 state.set_value("aaa bbb ccc", window, cx);
9158 state.select_word(9, window, cx);
9159 assert_eq!(state.selected_range(), 0..11);
9160
9161 state.set_masked(false, window, cx);
9163 state.set_value("aaa bbb ccc", window, cx);
9164 state.set_selected_range(11..11, cx);
9165 state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
9166 assert_eq!(state.value(), "aaa bbb ");
9167
9168 state.set_value("aaa bbb ccc", window, cx);
9169 state.select_word(9, window, cx);
9170 assert_eq!(state.selected_range(), 8..11);
9171 });
9172 });
9173 }
9174
9175 #[gpui::test]
9176 fn test_ctrl_delete_stops_at_whitespace(cx: &mut TestAppContext) {
9177 let input_view = InputView::build_textarea(cx, |state| state);
9178 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9179 let input = input_view.input;
9180
9181 cx.update(|window, cx| {
9182 input.update(cx, |state, cx| {
9183 state.set_value(" four leading spaces", window, cx);
9185 assert_eq!(state.next_word_delete_end_at(0, true), 4);
9186 assert_eq!(state.next_word_delete_end_at(4, true), 8);
9187 assert_eq!(state.next_word_delete_end_at(8, true), 9);
9188 assert_eq!(state.next_word_delete_end_at(0, false), 8);
9190
9191 state.set_value("one\n two", window, cx);
9194 assert_eq!(state.next_word_delete_end_at(3, true), 4);
9195 state.set_value("one\r\n two", window, cx);
9196 assert_eq!(state.next_word_delete_end_at(3, true), 5);
9197 state.set_value("one \ntwo", window, cx);
9199 assert_eq!(state.next_word_delete_end_at(3, true), 5);
9200
9201 state.set_value(" four leading spaces", window, cx);
9202 state.set_selected_range(0..0, cx);
9203 state.delete_next_word(&DeleteToNextWordEnd, window, cx);
9204 #[cfg(not(target_os = "macos"))]
9205 assert_eq!(state.value(), "four leading spaces");
9206 #[cfg(target_os = "macos")]
9207 assert_eq!(state.value(), " leading spaces");
9208 });
9209 });
9210 }
9211
9212 #[gpui::test]
9213 fn test_masked_input_disables_the_copy_context_menu_items(cx: &mut TestAppContext) {
9214 let input_view = InputView::build(cx, |state| state);
9215 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9216 let input = input_view.input;
9217
9218 cx.update(|window, cx| {
9219 input.update(cx, |state, cx| {
9220 state.set_value("hunter2", window, cx);
9221 state.select_all(window, cx);
9222 assert!(state.context_menu_capabilities().is_copyable());
9223
9224 state.set_masked(true, window, cx);
9225 let capabilities = state.context_menu_capabilities();
9226 assert!(capabilities.is_masked());
9227 assert!(capabilities.has_selection());
9228 assert!(!capabilities.is_copyable());
9229 });
9230 });
9231 }
9232
9233 #[gpui::test]
9234 fn test_undo_manager_cut_and_repeated_pastes_are_distinct_transactions(
9235 cx: &mut TestAppContext,
9236 ) {
9237 let input_view = InputView::build(cx, |state| state);
9238 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9239 let input = input_view.input;
9240
9241 cx.update(|window, cx| {
9242 input.update(cx, |state, cx| {
9243 state.replace_text_in_range(None, "alpha beta gamma", window, cx);
9244 state.set_selected_range(6..10, cx);
9245 state.cut(&Cut, window, cx);
9246 assert_eq!(state.value(), "alpha gamma");
9247
9248 state.paste(&Paste, window, cx);
9249 state.paste(&Paste, window, cx);
9250 assert_eq!(state.value(), "alpha betabeta gamma");
9251
9252 state.undo(&Undo, window, cx);
9253 assert_eq!(state.value(), "alpha beta gamma");
9254 state.undo(&Undo, window, cx);
9255 assert_eq!(state.value(), "alpha gamma");
9256 state.undo(&Undo, window, cx);
9257 assert_eq!(state.value(), "alpha beta gamma");
9258 });
9259 });
9260 }
9261
9262 #[gpui::test]
9263 fn test_undo_manager_word_and_line_deletes_do_not_coalesce(cx: &mut TestAppContext) {
9264 let input_view = InputView::build_textarea(cx, |state| state);
9265 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9266 let input = input_view.input;
9267
9268 cx.update(|window, cx| {
9269 input.update(cx, |state, cx| {
9270 state.set_value("one two three\nfour five", window, cx);
9271 state.set_selected_range(13..13, cx);
9272 state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
9273 assert_eq!(state.value(), "one two \nfour five");
9274 state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
9275 assert_eq!(state.value(), "one two four five");
9276
9277 state.undo(&Undo, window, cx);
9278 assert_eq!(state.value(), "one two \nfour five");
9279 state.undo(&Undo, window, cx);
9280 assert_eq!(state.value(), "one two three\nfour five");
9281 });
9282 });
9283 }
9284
9285 #[gpui::test]
9286 fn test_undo_manager_multiline_replacement_is_one_atomic_transaction(cx: &mut TestAppContext) {
9287 let input_view = InputView::build_textarea(cx, |state| state);
9288 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9289 let input = input_view.input;
9290
9291 cx.update(|window, cx| {
9292 input.update(cx, |state, cx| {
9293 state.replace_text_in_range(None, "before", window, cx);
9294 state.set_selected_range(0..6, cx);
9295 state.replace_text_in_range(None, "line one\nline two\n第三行", window, cx);
9296 assert_eq!(state.value(), "line one\nline two\n第三行");
9297
9298 state.undo(&Undo, window, cx);
9299 assert_eq!(state.value(), "before");
9300 assert_eq!(state.selected_range(), 0..6);
9301 state.redo(&Redo, window, cx);
9302 assert_eq!(state.value(), "line one\nline two\n第三行");
9303 });
9304 });
9305 }
9306
9307 #[gpui::test]
9308 fn test_undo_manager_composition_isolated_from_long_typing(cx: &mut TestAppContext) {
9309 let input_view = InputView::build(cx, |state| state);
9310 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9311 let input = input_view.input;
9312
9313 cx.update(|window, cx| {
9314 input.update(cx, |state, cx| {
9315 state.replace_text_in_range(None, "prefix ", window, cx);
9316 state.replace_and_mark_text_in_range(None, "n", None, window, cx);
9317 state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
9318 state.replace_and_mark_text_in_range(None, "你", None, window, cx);
9319 state.unmark_text(window, cx);
9320 state.replace_text_in_range(None, " suffix", window, cx);
9321 assert_eq!(state.value(), "prefix 你 suffix");
9322
9323 state.undo(&Undo, window, cx);
9324 assert_eq!(state.value(), "prefix 你");
9325 state.undo(&Undo, window, cx);
9326 assert_eq!(state.value(), "prefix ");
9327 state.undo(&Undo, window, cx);
9328 assert_eq!(state.value(), "");
9329 });
9330 });
9331 }
9332
9333 #[gpui::test]
9334 fn test_undo_manager_selected_replacement_is_atomic(cx: &mut TestAppContext) {
9335 let input_view = InputView::build(cx, |state| state);
9336 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9337 let input = input_view.input;
9338
9339 cx.update(|window, cx| {
9340 input.update(cx, |state, cx| {
9341 state.replace_text_in_range(None, "abc", window, cx);
9342 state.set_selected_range(1..2, cx);
9343 state.replace_text_in_range(None, "X", window, cx);
9344 state.replace_text_in_range(None, "z", window, cx);
9345 assert_eq!(state.value(), "aXzc");
9346
9347 state.undo(&Undo, window, cx);
9348 assert_eq!(state.value(), "aXc");
9349 state.undo(&Undo, window, cx);
9350 assert_eq!(state.value(), "abc");
9351 state.undo(&Undo, window, cx);
9352 assert_eq!(state.value(), "");
9353 });
9354 });
9355 }
9356
9357 #[gpui::test]
9358 fn test_number_input_leading_dot_editable(cx: &mut TestAppContext) {
9359 let input_view = InputView::build(cx, |state| {
9360 state.mask_pattern(MaskPattern::Number {
9361 separator: None,
9362 fraction: None,
9363 })
9364 });
9365 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9366 let input = input_view.input;
9367
9368 cx.update(|window, cx| {
9369 input.update(cx, |state, cx| {
9370 state.replace_text_in_range(None, "1.2", window, cx);
9371
9372 let range = state.range_to_utf16(&(0..1));
9376 state.replace_text_in_range(Some(range), "", window, cx);
9377 assert_eq!(state.value(), ".2");
9378 let cursor: Range<usize> = state.selected_range();
9379 assert_eq!(cursor, 0..0);
9380
9381 state.replace_text_in_range(Some(0..0), "3", window, cx);
9383 assert_eq!(state.value(), "3.2");
9384 });
9385 });
9386 }
9387
9388 #[gpui::test]
9389 fn test_number_input_escape_invalid_text(cx: &mut TestAppContext) {
9390 let input_view = InputView::build(cx, |state| {
9393 state
9394 .mask_pattern(MaskPattern::Number {
9395 separator: None,
9396 fraction: None,
9397 })
9398 .default_value("1,234")
9399 });
9400 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9401 let input = input_view.input;
9402
9403 cx.update(|window, cx| {
9404 input.update(cx, |state, cx| {
9405 let range = state.range_to_utf16(&(4..5));
9409 state.replace_text_in_range(Some(range), "", window, cx);
9410 assert_eq!(state.value(), "1,23");
9411
9412 let range = state.range_to_utf16(&(1..2));
9414 state.replace_text_in_range(Some(range), "", window, cx);
9415 assert_eq!(state.value(), "123");
9416 state.replace_text_in_range(None, "a", window, cx);
9417 assert_eq!(state.value(), "123");
9418 });
9419 });
9420 }
9421
9422 #[gpui::test]
9426 fn test_set_value_single_line_caret_at_end_view_at_start(cx: &mut TestAppContext) {
9427 let input_view = InputView::build(cx, |state| state);
9428 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9429 let input = input_view.input;
9430
9431 let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9433 let len = value.len();
9434
9435 cx.update(|window, cx| {
9438 input.update(cx, |state, cx| {
9439 state.set_value(value.clone(), window, cx);
9440
9441 assert_eq!(
9442 state.selected_range(),
9443 len..len,
9444 "single-line caret should be at the end after set_value"
9445 );
9446 assert_eq!(
9447 state.deferred_scroll_offset,
9448 Some(point(px(0.), px(0.))),
9449 "the view should be forced back to the start"
9450 );
9451 });
9452 });
9453
9454 cx.run_until_parked();
9457 cx.update(|_, cx| {
9458 input.read_with(cx, |state, _| {
9459 assert!(
9460 state.scroll_size.width > state.input_bounds.size.width,
9461 "value must overflow the input width or this test is vacuous"
9462 );
9463 assert_eq!(
9464 state.scroll_handle.offset().x,
9465 px(0.),
9466 "long value should display from its start, not its tail"
9467 );
9468 });
9469 });
9470 }
9471
9472 #[gpui::test]
9476 fn test_replace_all_single_line(cx: &mut TestAppContext) {
9477 let input_view = InputView::build(cx, |state| state);
9478 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9479 let input = input_view.input;
9480
9481 let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9483 let len = value.len();
9484
9485 cx.update(|window, cx| {
9489 input.update(cx, |state, cx| {
9490 state.set_value("hello", window, cx);
9491 state.replace_all(value.clone(), window, cx);
9492 assert_eq!(state.value(), value);
9493 assert_eq!(
9494 state.selected_range(),
9495 len..len,
9496 "single-line caret should be at the end after replace_all"
9497 );
9498 assert_eq!(
9499 state.scroll_handle.offset(),
9500 point(px(0.), px(0.)),
9501 "the scroll offset should be reset to the start"
9502 );
9503 assert_eq!(
9504 state.deferred_scroll_offset,
9505 Some(point(px(0.), px(0.))),
9506 "single-line should set a deferred scroll offset to keep the start visible"
9507 );
9508 });
9509 });
9510
9511 cx.run_until_parked();
9514 cx.update(|_, cx| {
9515 input.read_with(cx, |state, _| {
9516 assert!(
9517 state.scroll_size.width > state.input_bounds.size.width,
9518 "value must overflow the input width or this test is vacuous"
9519 );
9520 assert_eq!(
9521 state.scroll_handle.offset().x,
9522 px(0.),
9523 "long value should display from its start, not its tail"
9524 );
9525 });
9526 });
9527 }
9528
9529 #[gpui::test]
9532 fn test_paste_reveals_caret_single_line(cx: &mut TestAppContext) {
9533 let input_view = InputView::build(cx, |state| state);
9534 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9535 let input = input_view.input;
9536 cx.run_until_parked();
9537
9538 let value = format!("https://example.com/v1/users?{}", "x=1&".repeat(120));
9539 cx.update(|window, cx| {
9540 cx.write_to_clipboard(ClipboardItem::new_string(value.clone()));
9541 input.update(cx, |state, cx| state.paste(&Paste, window, cx));
9542 });
9543 cx.run_until_parked();
9544
9545 cx.update(|_, cx| {
9546 input.read_with(cx, |state, _| {
9547 assert!(
9548 state.scroll_size.width > state.input_bounds.size.width,
9549 "value must overflow the input width or this test is vacuous"
9550 );
9551 let caret = state
9552 .last_layout
9553 .as_ref()
9554 .and_then(|layout| layout.cursor_bounds)
9555 .expect("a caret");
9556 assert!(
9557 caret.left() >= state.input_bounds.left()
9558 && caret.right() <= state.input_bounds.right(),
9559 "the caret at {caret:?} should be inside {:?}",
9560 state.input_bounds
9561 );
9562 });
9563 });
9564 }
9565
9566 #[gpui::test]
9567 fn test_single_line_removes_newlines(cx: &mut TestAppContext) {
9568 let input_view = InputView::build(cx, |state| state.default_value("default\nvalue"));
9569 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9570 let input = input_view.input;
9571
9572 cx.update(|window, cx| {
9573 input.update(cx, |state, cx| {
9574 assert_eq!(state.value(), "defaultvalue");
9575
9576 state.set_value("first\nsecond\r\nthird\rfourth", window, cx);
9577 assert_eq!(state.value(), "firstsecondthirdfourth");
9578
9579 state.set_value("", window, cx);
9580 state.insert("a\nb", window, cx);
9581 assert_eq!(state.value(), "ab");
9582 });
9583
9584 cx.write_to_clipboard(ClipboardItem::new_string("a\r\nb\nc\rd".to_string()));
9585 input.update(cx, |state, cx| {
9586 state.set_value("", window, cx);
9587 state.paste(&Paste, window, cx);
9588 assert_eq!(state.value(), "abcd");
9589 });
9590 });
9591
9592 cx.run_until_parked();
9593 }
9594
9595 #[gpui::test]
9599 fn test_single_line_removes_tabs(cx: &mut TestAppContext) {
9600 let input_view = InputView::build(cx, |state| state);
9601 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9602 let input = input_view.input;
9603
9604 cx.update(|window, cx| {
9605 input.update(cx, |state, cx| state.focus(window, cx));
9606 });
9607 cx.run_until_parked();
9608
9609 cx.simulate_input("a");
9610 cx.simulate_keystrokes("tab");
9611 cx.simulate_input("b");
9612 input.read_with(&cx, |state, _| assert_eq!(state.value(), "ab"));
9613
9614 cx.update(|window, cx| {
9615 input.update(cx, |state, cx| {
9616 state.set_value("c\td\ne", window, cx);
9617 assert_eq!(state.value(), "cde");
9618 });
9619 });
9620 }
9621
9622 #[gpui::test]
9626 fn test_replace_all_multi_line(cx: &mut TestAppContext) {
9627 let input_view = InputView::build_textarea(cx, |state| state);
9628 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9629 let input = input_view.input;
9630
9631 cx.update(|window, cx| {
9632 input.update(cx, |state, cx| {
9633 state.set_value("foo\nbar", window, cx);
9634 state.replace_all("baz\nqux", window, cx);
9635 assert_eq!(state.value(), "baz\nqux");
9636 assert_eq!(
9637 state.selected_range(),
9638 0..0,
9639 "multi-line selection should be cleared after replace_all"
9640 );
9641 assert_eq!(
9642 state.scroll_handle.offset(),
9643 point(px(0.), px(0.)),
9644 "the scroll offset should be reset to the start"
9645 );
9646 assert!(
9647 state.deferred_scroll_offset.is_none(),
9648 "multi-line should not set a deferred scroll offset"
9649 );
9650 });
9651 });
9652 }
9653
9654 #[gpui::test]
9657 fn test_replace_all_preserves_undo_history(cx: &mut TestAppContext) {
9658 let input_view = InputView::build(cx, |state| state);
9659 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9660 let input = input_view.input;
9661
9662 cx.update(|window, cx| {
9663 input.update(cx, |state, cx| {
9664 state.set_value("first", window, cx);
9666 assert!(
9667 !state.undo_manager.has_undos(),
9668 "history should be empty after set_value"
9669 );
9670
9671 state.replace_all("second", window, cx);
9673 assert_eq!(state.value(), "second");
9674 assert!(
9675 state.undo_manager.has_undos(),
9676 "replace_all should record an undo step"
9677 );
9678
9679 state.undo(&Undo, window, cx);
9681 assert_eq!(state.value(), "first");
9682
9683 state.redo(&Redo, window, cx);
9685 assert_eq!(state.value(), "second");
9686 });
9687 });
9688 }
9689
9690 #[gpui::test]
9693 fn test_replace_all_code_editor(cx: &mut TestAppContext) {
9694 let input_view = InputView::new(cx);
9695 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9696 let input = input_view.input;
9697
9698 cx.update(|window, cx| {
9699 input.update(cx, |state, cx| {
9700 state.set_value("select 1", window, cx);
9702 state._pending_update = false;
9703
9704 state.replace_all("select 2", window, cx);
9705 assert_eq!(state.value(), "select 2");
9706 assert!(
9707 state._pending_update,
9708 "replace_all on a code editor should request a pending update"
9709 );
9710 });
9711 });
9712 }
9713
9714 #[gpui::test]
9715 fn test_set_selected_range(cx: &mut TestAppContext) {
9716 let input_view = InputView::build(cx, |state| state.default_value("hello world"));
9717 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9718 let input = input_view.input;
9719
9720 cx.update(|_, cx| {
9721 input.update(cx, |s, cx| {
9722 s.set_selected_range(0..5, cx);
9723 assert_eq!(s.selected_range(), 0..5);
9724 assert_eq!(s.selected_text().to_string(), "hello");
9725
9726 s.set_selected_range(6..11, cx);
9727 assert_eq!(s.selected_text().to_string(), "world");
9728
9729 s.set_selected_range(100..100, cx);
9731 assert_eq!(s.selected_range(), 11..11);
9732 });
9733 });
9734 }
9735
9736 #[gpui::test]
9738 fn test_replace_text_in_ranges_single_edit(cx: &mut TestAppContext) {
9739 let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9740 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9741 let input = input_view.input;
9742
9743 cx.update(|window, cx| {
9744 input.update(cx, |s, cx| {
9745 s.replace_text_in_ranges(&[(0..5, "HELLO".to_string())], window, cx);
9746 assert_eq!(s.value(), "HELLO world");
9747
9748 s.undo(&Undo, window, cx);
9749 assert_eq!(s.value(), "hello world");
9750
9751 s.redo(&Redo, window, cx);
9752 assert_eq!(s.value(), "HELLO world");
9753 });
9754 });
9755 }
9756
9757 #[gpui::test]
9760 fn test_replace_text_in_ranges_multi_edit_transaction(cx: &mut TestAppContext) {
9761 let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9762 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9763 let input = input_view.input;
9764
9765 cx.update(|window, cx| {
9766 input.update(cx, |s, cx| {
9767 s.replace_text_in_ranges(
9770 &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9771 window,
9772 cx,
9773 );
9774 assert_eq!(s.value(), "X bbb Y");
9775
9776 let cursors: Vec<usize> =
9778 s.selections.iter().map(|sel| sel.cursor_offset()).collect();
9779 assert_eq!(cursors, vec![1, 7]);
9780
9781 assert_eq!(s.undo_manager.undo_count(), 1);
9783
9784 s.undo(&Undo, window, cx);
9786 assert_eq!(s.value(), "aaa bbb ccc");
9787
9788 s.redo(&Redo, window, cx);
9790 assert_eq!(s.value(), "X bbb Y");
9791 });
9792 });
9793 }
9794
9795 #[gpui::test]
9799 fn test_replace_text_in_ranges_drives_the_highlighter_once(cx: &mut TestAppContext) {
9800 use crate::input::{FoldRange, HighlightStyleResolver, InputEdit, InputHighlighter};
9801 use gpui::HighlightStyle;
9802 use std::cell::RefCell;
9803
9804 struct RecordingHighlighter(Rc<RefCell<Vec<Vec<String>>>>);
9805
9806 impl InputHighlighter for RecordingHighlighter {
9807 fn language(&self) -> SharedString {
9808 "recording".into()
9809 }
9810
9811 fn update(
9812 &mut self,
9813 _: Option<InputEdit>,
9814 text: &Rope,
9815 _: bool,
9816 _: &mut Window,
9817 _: &mut Context<EditorState>,
9818 ) {
9819 self.0.borrow_mut().push(vec![text.to_string()]);
9820 }
9821
9822 fn update_batch(
9823 &mut self,
9824 edits: &[(InputEdit, Rope)],
9825 _: bool,
9826 _: &mut Window,
9827 _: &mut Context<EditorState>,
9828 ) {
9829 let texts = edits.iter().map(|(_, text)| text.to_string()).collect();
9830 self.0.borrow_mut().push(texts);
9831 }
9832
9833 fn styles(
9834 &self,
9835 range: &Range<usize>,
9836 _: &dyn HighlightStyleResolver,
9837 ) -> Vec<(Range<usize>, HighlightStyle)> {
9838 vec![(range.clone(), HighlightStyle::default())]
9839 }
9840
9841 fn fold_ranges(&self, _: &Rope) -> Vec<FoldRange> {
9842 Vec::new()
9843 }
9844 }
9845
9846 let updates = Rc::new(RefCell::new(Vec::new()));
9847 let input_view = InputView::new(cx);
9848 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9849 let input = input_view.input;
9850
9851 cx.update(|window, cx| {
9852 input.update(cx, |s, cx| {
9853 s.set_value("aaa bbb ccc", window, cx);
9854 let recorded = updates.clone();
9855 s.set_highlighter_factory(
9856 Rc::new(move |_: &str| {
9857 let highlighter: Box<dyn InputHighlighter> =
9858 Box::new(RecordingHighlighter(recorded.clone()));
9859 Some(highlighter)
9860 }),
9861 cx,
9862 );
9863 s.replace_text_in_ranges(
9864 &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9865 window,
9866 cx,
9867 );
9868 });
9869 });
9870
9871 assert_eq!(
9872 *updates.borrow(),
9873 vec![vec!["aaa bbb Y".to_string(), "X bbb Y".to_string()]]
9874 );
9875 }
9876
9877 #[gpui::test]
9879 fn test_last_input_edits_single_insert(cx: &mut TestAppContext) {
9880 let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9881 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9882 let input = input_view.input;
9883
9884 cx.update(|window, cx| {
9885 input.update(cx, |state, cx| {
9886 state.replace_text_in_ranges(&[(5..5, " big".to_string())], window, cx);
9887
9888 let edits = state.last_input_edits.as_slice();
9889 assert_eq!(edits.len(), 1);
9890 let (edit, text_after) = &edits[0];
9891 assert_eq!(edit.start_byte, 5);
9892 assert_eq!(edit.old_end_byte, 5);
9893 assert_eq!(edit.new_end_byte, 9);
9894 assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9895 assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9896 assert_eq!(edit.new_end_position, crate::input::Point::new(0, 9));
9897 assert_eq!(text_after.to_string(), "hello big world");
9898 });
9899 });
9900 }
9901
9902 #[gpui::test]
9904 fn test_last_input_edits_delete_and_paste(cx: &mut TestAppContext) {
9905 let input_view = InputView::build_textarea(cx, |state| state.default_value("hello world"));
9906 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9907 let input = input_view.input;
9908
9909 cx.update(|window, cx| {
9910 input.update(cx, |state, cx| {
9911 state.replace_text_in_ranges(&[(5..11, String::new())], window, cx);
9912 assert_eq!(state.value(), "hello");
9913
9914 let edits = state.last_input_edits.as_slice();
9915 assert_eq!(edits.len(), 1);
9916 let (edit, text_after) = &edits[0];
9917 assert_eq!(edit.start_byte, 5);
9918 assert_eq!(edit.old_end_byte, 11);
9919 assert_eq!(edit.new_end_byte, 5);
9920 assert_eq!(text_after.to_string(), "hello");
9921
9922 state.replace_text_in_ranges(&[(5..5, "\nnext".to_string())], window, cx);
9923 assert_eq!(state.value(), "hello\nnext");
9924
9925 let edits = state.last_input_edits.as_slice();
9926 assert_eq!(edits.len(), 1);
9927 let (edit, text_after) = &edits[0];
9928 assert_eq!(edit.start_byte, 5);
9929 assert_eq!(edit.old_end_byte, 5);
9930 assert_eq!(edit.new_end_byte, 10);
9931 assert_eq!(edit.start_position, crate::input::Point::new(0, 5));
9932 assert_eq!(edit.old_end_position, crate::input::Point::new(0, 5));
9933 assert_eq!(edit.new_end_position, crate::input::Point::new(1, 4));
9934 assert_eq!(text_after.to_string(), "hello\nnext");
9935 });
9936 });
9937 }
9938
9939 #[gpui::test]
9941 fn test_last_input_edits_grouped_change(cx: &mut TestAppContext) {
9942 let input_view = InputView::build_textarea(cx, |state| state.default_value("aaa bbb ccc"));
9943 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9944 let input = input_view.input;
9945
9946 cx.update(|window, cx| {
9947 input.update(cx, |state, cx| {
9948 state.replace_text_in_ranges(
9949 &[(0..3, "X".to_string()), (8..11, "Y".to_string())],
9950 window,
9951 cx,
9952 );
9953 assert_eq!(state.value(), "X bbb Y");
9954
9955 let edits = state.last_input_edits.as_slice();
9956 assert_eq!(edits.len(), 2);
9957 assert_eq!(edits[0].0.start_byte, 8);
9959 assert_eq!(edits[0].0.old_end_byte, 11);
9960 assert_eq!(edits[0].0.new_end_byte, 9);
9961 assert_eq!(edits[0].0.start_position, crate::input::Point::new(0, 8));
9962 assert_eq!(edits[0].0.old_end_position, crate::input::Point::new(0, 11));
9963 assert_eq!(edits[0].0.new_end_position, crate::input::Point::new(0, 9));
9964 assert_eq!(edits[0].1.to_string(), "aaa bbb Y");
9965
9966 assert_eq!(edits[1].0.start_byte, 0);
9967 assert_eq!(edits[1].0.old_end_byte, 3);
9968 assert_eq!(edits[1].0.new_end_byte, 1);
9969 assert_eq!(edits[1].0.start_position, crate::input::Point::new(0, 0));
9970 assert_eq!(edits[1].0.old_end_position, crate::input::Point::new(0, 3));
9971 assert_eq!(edits[1].0.new_end_position, crate::input::Point::new(0, 1));
9972 assert_eq!(edits[1].1.to_string(), "X bbb Y");
9973 });
9974 });
9975 }
9976
9977 #[gpui::test]
9979 fn test_last_input_edits_without_a_highlighter(cx: &mut TestAppContext) {
9980 let input_view = InputView::new(cx);
9981 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
9982 let input = input_view.input;
9983
9984 cx.update(|window, cx| {
9985 input.update(cx, |state, cx| {
9986 state.set_value("fn main() {}", window, cx);
9987 let no_highlighter: InputHighlighterFactory = Rc::new(|_: &str| None);
9988 state.set_highlighter_factory(no_highlighter, cx);
9989 assert!(state.last_input_edits.as_slice().is_empty());
9990
9991 state.replace_text_in_ranges(&[(12..12, "\n".to_string())], window, cx);
9992 assert_eq!(state.value(), "fn main() {}\n");
9993
9994 let edits = state.last_input_edits.as_slice();
9995 assert_eq!(edits.len(), 1);
9996 let (edit, text_after) = &edits[0];
9997 assert_eq!(edit.start_byte, 12);
9998 assert_eq!(edit.old_end_byte, 12);
9999 assert_eq!(edit.new_end_byte, 13);
10000 assert_eq!(edit.start_position, crate::input::Point::new(0, 12));
10001 assert_eq!(edit.old_end_position, crate::input::Point::new(0, 12));
10002 assert_eq!(edit.new_end_position, crate::input::Point::new(1, 0));
10003 assert_eq!(text_after.to_string(), "fn main() {}\n");
10004 });
10005 });
10006 }
10007
10008 #[gpui::test]
10010 fn test_last_input_edits_cleared_by_set_value(cx: &mut TestAppContext) {
10011 let input_view = InputView::build_textarea(cx, |state| state.default_value("hello"));
10012 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10013 let input = input_view.input;
10014
10015 cx.update(|window, cx| {
10016 input.update(cx, |state, cx| {
10017 state.replace_text_in_ranges(&[(5..5, "!".to_string())], window, cx);
10018 assert_eq!(state.last_input_edits.as_slice().len(), 1);
10019
10020 state.set_value("replaced", window, cx);
10021 assert!(state.last_input_edits.as_slice().is_empty());
10022
10023 state.replace_text_in_ranges(&[(8..8, "?".to_string())], window, cx);
10024 let edits = state.last_input_edits.as_slice();
10025 assert_eq!(edits.len(), 1);
10026 assert_eq!(edits[0].1.to_string(), "replaced?");
10027 });
10028 });
10029 }
10030
10031 fn replay_input_edits(text: &mut String, event: &InputEditsEvent) {
10033 for (edit, after) in event.edits() {
10034 let replacement = after.slice(edit.start_byte..edit.new_end_byte).to_string();
10035 text.replace_range(edit.start_byte..edit.old_end_byte, &replacement);
10036 assert_eq!(*text, after.to_string());
10037 }
10038 }
10039
10040 #[gpui::test]
10041 fn input_edits_events_preserve_queued_changes_and_undo(cx: &mut TestAppContext) {
10042 let view = InputView::build_textarea(cx, |state| state.default_value("hello"));
10043 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10044 let input = view.input;
10045 let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
10046 let seen = observed.clone();
10047 let _subscription = cx.update(|_, cx| {
10048 cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
10049 seen.borrow_mut().push(event.clone());
10050 })
10051 });
10052 cx.update(|window, cx| {
10053 input.update(cx, |state, cx| {
10054 state.replace_text_in_ranges(&[(5..5, "!".into())], window, cx);
10055 state.replace_text_in_ranges(&[(6..6, "?".into())], window, cx);
10056 state.undo(&Undo, window, cx);
10057 });
10058 });
10059 let events = observed.borrow();
10060 assert!(events.len() >= 3);
10061 let mut text = "hello".to_string();
10062 for event in events.iter() {
10063 replay_input_edits(&mut text, event);
10064 }
10065 assert_eq!(
10066 text,
10067 input.read_with(&cx, |state, _| state.value().to_string())
10068 );
10069 assert_eq!(events[0].edits()[0].1.to_string(), "hello!");
10070 assert_eq!(events[1].edits()[0].1.to_string(), "hello!?");
10071 }
10072
10073 #[gpui::test]
10074 fn input_edits_event_replays_ime_commit(cx: &mut TestAppContext) {
10075 let view = InputView::build_textarea(cx, |state| state.default_value(""));
10076 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10077 let input = view.input;
10078 let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
10079 let seen = observed.clone();
10080 let _subscription = cx.update(|_, cx| {
10081 cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
10082 seen.borrow_mut().push(event.clone());
10083 })
10084 });
10085 cx.update(|window, cx| {
10086 input.update(cx, |state, cx| {
10087 state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10088 state.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
10089 state.replace_text_in_range(None, "你", window, cx);
10090 });
10091 });
10092 let events = observed.borrow();
10093 assert_eq!(events.len(), 1);
10094 let mut text = String::new();
10095 replay_input_edits(&mut text, &events[0]);
10096 assert_eq!(text, "你");
10097 }
10098
10099 #[gpui::test]
10100 fn input_edits_event_replays_after_cancelled_composition(cx: &mut TestAppContext) {
10101 let view = InputView::build_textarea(cx, |state| state.default_value(""));
10102 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10103 let input = view.input;
10104 let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
10105 let seen = observed.clone();
10106 let _subscription = cx.update(|_, cx| {
10107 cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
10108 seen.borrow_mut().push(event.clone());
10109 })
10110 });
10111 cx.update(|window, cx| {
10112 input.update(cx, |state, cx| {
10113 state.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10114 state.replace_and_mark_text_in_range(None, "", None, window, cx);
10115 state.replace_text_in_range(None, "x", window, cx);
10116 });
10117 });
10118 let events = observed.borrow();
10119 assert_eq!(events.len(), 1);
10120 let mut text = String::new();
10121 replay_input_edits(&mut text, &events[0]);
10122 assert_eq!(text, "x");
10123 }
10124
10125 #[gpui::test]
10126 fn input_edits_event_replays_mask_rewrite(cx: &mut TestAppContext) {
10127 let view = InputView::build(cx, |state| {
10128 state
10129 .mask_pattern(MaskPattern::Number {
10130 separator: Some(','),
10131 fraction: None,
10132 })
10133 .default_value("999")
10134 });
10135 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10136 let input = view.input;
10137 let observed = Rc::new(std::cell::RefCell::new(Vec::<InputEditsEvent>::new()));
10138 let seen = observed.clone();
10139 let _subscription = cx.update(|_, cx| {
10140 cx.subscribe(&input, move |_, event: &InputEditsEvent, _| {
10141 seen.borrow_mut().push(event.clone());
10142 })
10143 });
10144 cx.update(|window, cx| {
10145 input.update(cx, |state, cx| {
10146 state.set_cursor_to(3);
10147 state.replace_text_in_range(None, "9", window, cx)
10148 });
10149 });
10150 let events = observed.borrow();
10151 assert_eq!(events.len(), 1);
10152 let mut text = "999".to_string();
10153 replay_input_edits(&mut text, &events[0]);
10154 assert_eq!(text, "9,999");
10155 }
10156
10157 #[gpui::test]
10159 fn test_ime_composition_undoes_as_one_unit(cx: &mut TestAppContext) {
10160 let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
10161 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10162 let input = input_view.input;
10163
10164 cx.update(|window, cx| {
10165 input.update(cx, |s, cx| {
10166 s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10168 s.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
10169 s.replace_text_in_range(None, "你", window, cx);
10170 assert_eq!(s.value(), "你");
10171
10172 assert_eq!(s.undo_manager.undo_count(), 1);
10174
10175 s.undo(&Undo, window, cx);
10176 assert_eq!(s.value(), "");
10177
10178 s.redo(&Redo, window, cx);
10179 assert_eq!(s.value(), "你");
10180 });
10181 });
10182 }
10183
10184 #[gpui::test]
10187 fn test_edit_after_composition_is_separate_undo(cx: &mut TestAppContext) {
10188 let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
10189 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10190 let input = input_view.input;
10191
10192 cx.update(|window, cx| {
10193 input.update(cx, |s, cx| {
10194 s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10195 s.replace_text_in_range(None, "你", window, cx);
10196 assert_eq!(s.value(), "你");
10197 assert_eq!(s.undo_manager.undo_count(), 1);
10198
10199 s.replace_text_in_range(None, "x", window, cx);
10201 assert_eq!(s.value(), "你x");
10202 assert_eq!(s.undo_manager.undo_count(), 2);
10203
10204 s.undo(&Undo, window, cx);
10205 assert_eq!(s.value(), "你");
10206 s.undo(&Undo, window, cx);
10207 assert_eq!(s.value(), "");
10208 });
10209 });
10210 }
10211
10212 #[gpui::test]
10215 fn test_composition_cancel_via_unmark_does_not_leak(cx: &mut TestAppContext) {
10216 let input_view = InputView::build_textarea(cx, |state| state.default_value(""));
10217 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10218 let input = input_view.input;
10219
10220 cx.update(|window, cx| {
10221 input.update(cx, |s, cx| {
10222 s.replace_and_mark_text_in_range(None, "n", Some(1..1), window, cx);
10224 s.unmark_text(window, cx);
10225 let after_cancel = s.undo_manager.undo_count();
10226
10227 s.replace_text_in_range(None, "x", window, cx);
10229 assert_eq!(s.undo_manager.undo_count(), after_cancel + 1);
10230 });
10231 });
10232 }
10233
10234 #[gpui::test]
10235 fn test_unmark_text_notifies_when_clearing_marked_range(cx: &mut TestAppContext) {
10236 use std::cell::Cell;
10237 use std::rc::Rc;
10238
10239 let input_view = InputView::build(cx, |state| state.default_value("hello"));
10240 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10241 let input = input_view.input;
10242
10243 let notify_count = Rc::new(Cell::new(0usize));
10244 let change_count = Rc::new(Cell::new(0usize));
10245 let _subscriptions = cx.update(|_window, cx| {
10246 let notify_count = notify_count.clone();
10247 let observe = cx.observe(&input, move |_, _| {
10248 notify_count.set(notify_count.get() + 1);
10249 });
10250 let change_count = change_count.clone();
10251 let subscribe = cx.subscribe(&input, move |_, event: &InputEvent, _| {
10252 if matches!(event, InputEvent::Change) {
10253 change_count.set(change_count.get() + 1);
10254 }
10255 });
10256 (observe, subscribe)
10257 });
10258
10259 cx.update(|window, cx| {
10262 input.update(cx, |state, cx| {
10263 state.replace_and_mark_text_in_range(Some(0..5), "hello", None, window, cx);
10264 assert!(state.marked_text_range(window, cx).is_some());
10265 });
10266 });
10267 cx.run_until_parked();
10268 notify_count.set(0);
10269 change_count.set(0);
10270
10271 cx.update(|window, cx| {
10272 input.update(cx, |state, cx| {
10273 state.unmark_text(window, cx);
10274 assert!(state.marked_text_range(window, cx).is_none());
10275 });
10276 });
10277 cx.run_until_parked();
10278 assert_eq!(notify_count.get(), 1);
10279 assert_eq!(change_count.get(), 0);
10280
10281 cx.update(|window, cx| {
10283 input.update(cx, |state, cx| {
10284 state.unmark_text(window, cx);
10285 });
10286 });
10287 cx.run_until_parked();
10288 assert_eq!(notify_count.get(), 1);
10289
10290 cx.update(|window, cx| {
10292 input.update(cx, |state, cx| {
10293 state.replace_and_mark_text_in_range(None, "!", Some(1..1), window, cx);
10294 assert!(state.marked_text_range(window, cx).is_some());
10295 });
10296 });
10297 cx.run_until_parked();
10298 notify_count.set(0);
10299 change_count.set(0);
10300
10301 cx.update(|window, cx| {
10302 input.update(cx, |state, cx| {
10303 state.unmark_text(window, cx);
10304 assert!(state.marked_text_range(window, cx).is_none());
10305 });
10306 });
10307 cx.run_until_parked();
10308 assert_eq!(notify_count.get(), 1);
10309 assert_eq!(change_count.get(), 1);
10310 }
10311
10312 #[gpui::test]
10313 fn test_set_selected_range_clips_to_utf8_boundaries(cx: &mut TestAppContext) {
10314 let input_view = InputView::build(cx, |state| state.default_value("éx"));
10315 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10316 let input = input_view.input;
10317
10318 cx.update(|window, cx| {
10319 input.update(cx, |state, cx| {
10320 state.set_selected_range(0..1, cx);
10321 assert_eq!(state.selected_range(), 0..2);
10322 state.copy(&Copy, window, cx);
10323
10324 state.set_selected_range(1..1, cx);
10325 assert_eq!(state.selected_range(), 0..0);
10326 });
10327 });
10328 }
10329
10330 #[gpui::test]
10331 fn test_is_composing_lifecycle(cx: &mut TestAppContext) {
10332 let input_view = InputView::build(cx, |state| state.default_value("hello"));
10333 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10334 let input = input_view.input;
10335
10336 cx.update(|window, cx| {
10337 input.update(cx, |state, cx| {
10338 assert!(!state.is_composing());
10339
10340 state.replace_and_mark_text_in_range(None, "ni", Some(2..2), window, cx);
10341 assert!(state.is_composing());
10342 assert!(state.marked_text_range(window, cx).is_some());
10343
10344 state.replace_text_in_range(None, "你", window, cx);
10346 assert!(!state.is_composing());
10347 assert!(state.marked_text_range(window, cx).is_none());
10348
10349 state.replace_and_mark_text_in_range(None, "hao", Some(3..3), window, cx);
10351 assert!(state.is_composing());
10352 state.unmark_text(window, cx);
10353 assert!(!state.is_composing());
10354 assert!(state.marked_text_range(window, cx).is_none());
10355
10356 state.replace_and_mark_text_in_range(None, "a", Some(1..1), window, cx);
10358 assert!(state.is_composing());
10359 state.replace_and_mark_text_in_range(None, "", None, window, cx);
10360 assert!(!state.is_composing());
10361 });
10362 });
10363 }
10364
10365 #[gpui::test]
10366 fn test_ime_selection_is_relative_to_replacement_start(cx: &mut TestAppContext) {
10367 let input_view = InputView::build(cx, |state| state.default_value("你好 "));
10368 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10369 let input = input_view.input;
10370
10371 cx.update(|window, cx| {
10372 input.update(cx, |state, cx| {
10373 state.set_selected_range(7..7, cx);
10374 state.replace_and_mark_text_in_range(None, "s", Some(1..1), window, cx);
10375 state.replace_and_mark_text_in_range(None, "sh", Some(2..2), window, cx);
10376
10377 assert_eq!(state.value(), "你好 sh");
10378 assert_eq!(state.selected_range(), 9..9);
10379 assert_eq!(state.ime_marked_range, Some((7..9).into()));
10380 });
10381 });
10382 }
10383
10384 #[gpui::test]
10385 fn test_undo_manager_composition_is_one_undo_group(cx: &mut TestAppContext) {
10386 let input_view = InputView::build(cx, |state| state);
10387 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10388 let input = input_view.input;
10389
10390 cx.update(|window, cx| {
10391 input.update(cx, |state, cx| {
10392 state.set_value("a", window, cx);
10393 state.replace_and_mark_text_in_range(None, "s", None, window, cx);
10394 state.replace_and_mark_text_in_range(None, "sh", None, window, cx);
10395 state.replace_text_in_range(None, "是", window, cx);
10396 assert_eq!(state.value(), "a是");
10397
10398 state.undo(&Undo, window, cx);
10399 assert_eq!(state.value(), "a");
10400 state.redo(&Redo, window, cx);
10401 assert_eq!(state.value(), "a是");
10402 });
10403 });
10404 }
10405
10406 #[gpui::test]
10407 fn test_undo_manager_consecutive_compositions_are_separate_groups(cx: &mut TestAppContext) {
10408 let input_view = InputView::build(cx, |state| state);
10409 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10410 let input = input_view.input;
10411
10412 cx.update(|window, cx| {
10413 input.update(cx, |state, cx| {
10414 state.replace_and_mark_text_in_range(None, "j", None, window, cx);
10416 state.replace_and_mark_text_in_range(None, "jin", None, window, cx);
10417 state.replace_text_in_range(None, "今天", window, cx);
10418 state.replace_and_mark_text_in_range(None, "w", None, window, cx);
10420 state.replace_and_mark_text_in_range(None, "wo", None, window, cx);
10421 state.replace_text_in_range(None, "我们", window, cx);
10422 assert_eq!(state.value(), "今天我们");
10423 assert_eq!(state.selected_range(), 12..12);
10424
10425 state.undo(&Undo, window, cx);
10426 assert_eq!(state.value(), "今天");
10427 assert_eq!(state.selected_range(), 6..6);
10428
10429 state.undo(&Undo, window, cx);
10430 assert_eq!(state.value(), "");
10431 assert_eq!(state.selected_range(), 0..0);
10432
10433 state.redo(&Redo, window, cx);
10434 assert_eq!(state.value(), "今天");
10435 assert_eq!(state.selected_range(), 6..6);
10436
10437 state.redo(&Redo, window, cx);
10438 assert_eq!(state.value(), "今天我们");
10439 assert_eq!(state.selected_range(), 12..12);
10440 });
10441 });
10442 }
10443
10444 #[gpui::test]
10445 fn test_undo_manager_typing_after_composition_is_a_separate_group(cx: &mut TestAppContext) {
10446 let input_view = InputView::build(cx, |state| state);
10447 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10448 let input = input_view.input;
10449
10450 cx.update(|window, cx| {
10451 input.update(cx, |state, cx| {
10452 state.replace_and_mark_text_in_range(None, "n", None, window, cx);
10453 state.replace_text_in_range(None, "你", window, cx);
10454 state.undo_manager.set_pending_intent(EditIntent::Typing);
10455 state.replace_text_in_range(None, "a", window, cx);
10456 state.undo_manager.set_pending_intent(EditIntent::Typing);
10457 state.replace_text_in_range(None, "b", window, cx);
10458 assert_eq!(state.value(), "你ab");
10459
10460 state.undo(&Undo, window, cx);
10461 assert_eq!(state.value(), "你");
10462
10463 state.undo(&Undo, window, cx);
10464 assert_eq!(state.value(), "");
10465 });
10466 });
10467 }
10468
10469 #[gpui::test]
10470 fn test_undo_manager_composition_cancel_leaves_no_entry(cx: &mut TestAppContext) {
10471 let input_view = InputView::build(cx, |state| state);
10472 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10473 let input = input_view.input;
10474
10475 cx.update(|window, cx| {
10476 input.update(cx, |state, cx| {
10477 state.set_value("a", window, cx);
10478 state.replace_and_mark_text_in_range(None, "s", None, window, cx);
10479 state.replace_and_mark_text_in_range(None, "", None, window, cx);
10480
10481 assert_eq!(state.value(), "a");
10482 assert!(!state.undo_manager.has_undos());
10483 });
10484 });
10485 }
10486
10487 #[gpui::test]
10489 fn test_undo_manager_ime_rewrites_of_typed_char_are_one_group(cx: &mut TestAppContext) {
10490 let input_view = InputView::build(cx, |state| state);
10491 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10492 let input = input_view.input;
10493
10494 cx.update(|window, cx| {
10495 input.update(cx, |state, cx| {
10496 state.set_value("é ", window, cx);
10497 state.set_selected_range(3..3, cx);
10498 state.replace_text_in_range(None, "ㅎ", window, cx);
10500 state.replace_text_in_range(Some(2..3), "하", window, cx);
10501 state.replace_text_in_range(Some(2..3), "한", window, cx);
10502 state.replace_text_in_range(None, "ㄱ", window, cx);
10503 state.replace_text_in_range(Some(3..4), "그", window, cx);
10504 state.replace_text_in_range(Some(3..4), "글", window, cx);
10505 assert_eq!(state.value(), "é 한글");
10506 assert_eq!(state.undo_manager.undo_count(), 1);
10507
10508 state.undo(&Undo, window, cx);
10509 assert_eq!(state.value(), "é ");
10510 assert_eq!(state.selected_range(), 3..3);
10511
10512 state.redo(&Redo, window, cx);
10513 assert_eq!(state.value(), "é 한글");
10514 assert_eq!(state.selected_range(), 9..9);
10515 });
10516 });
10517 }
10518
10519 #[gpui::test]
10520 fn test_undo_manager_rewrite_after_cursor_movement_is_separate(cx: &mut TestAppContext) {
10521 let input_view = InputView::build(cx, |state| state);
10522 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10523 let input = input_view.input;
10524
10525 cx.update(|window, cx| {
10526 input.update(cx, |state, cx| {
10527 state.replace_text_in_range(None, "c", window, cx);
10528 state.replace_text_in_range(None, "e", window, cx);
10529 state.left(&MoveLeft, window, cx);
10530 state.right(&MoveRight, window, cx);
10531 state.replace_text_in_range(Some(1..2), "é", window, cx);
10532 assert_eq!(state.value(), "cé");
10533
10534 state.undo(&Undo, window, cx);
10535 assert_eq!(state.value(), "ce");
10536 state.undo(&Undo, window, cx);
10537 assert_eq!(state.value(), "");
10538 });
10539 });
10540 }
10541
10542 #[gpui::test]
10543 fn test_undo_manager_selection_restored_by_undo_and_redo(cx: &mut TestAppContext) {
10544 let input_view = InputView::build(cx, |state| state);
10545 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10546 let input = input_view.input;
10547
10548 cx.update(|window, cx| {
10549 input.update(cx, |state, cx| {
10550 state.set_value("abc", window, cx);
10551 state.set_selected_range(1..2, cx);
10552 state.replace_text_in_range(None, "X", window, cx);
10553
10554 state.undo(&Undo, window, cx);
10555 assert_eq!(state.value(), "abc");
10556 assert_eq!(state.selected_range(), 1..2);
10557
10558 state.redo(&Redo, window, cx);
10559 assert_eq!(state.value(), "aXc");
10560 assert_eq!(state.selected_range(), 2..2);
10561 });
10562 });
10563 }
10564
10565 #[gpui::test]
10566 fn test_undo_manager_forward_delete_restores_cursor(cx: &mut TestAppContext) {
10567 let input_view = InputView::build(cx, |state| state);
10568 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10569 let input = input_view.input;
10570
10571 cx.update(|window, cx| {
10572 input.update(cx, |state, cx| {
10573 state.set_value("abc", window, cx);
10574 state.set_selected_range(1..1, cx);
10575 state.delete(&Delete, window, cx);
10576
10577 state.undo(&Undo, window, cx);
10578 assert_eq!(state.value(), "abc");
10579 assert_eq!(state.selected_range(), 1..1);
10580 });
10581 });
10582 }
10583
10584 #[gpui::test]
10585 fn test_undo_manager_selection_movement_preserves_redo(cx: &mut TestAppContext) {
10586 let input_view = InputView::build(cx, |state| state);
10587 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10588 let input = input_view.input;
10589
10590 cx.update(|window, cx| {
10591 input.update(cx, |state, cx| {
10592 state.replace_text_in_range(None, "ab", window, cx);
10593 state.undo(&Undo, window, cx);
10594 state.set_selected_range(0..0, cx);
10595 state.redo(&Redo, window, cx);
10596 assert_eq!(state.value(), "ab");
10597
10598 state.undo(&Undo, window, cx);
10599 state.replace_text_in_range(None, "x", window, cx);
10600 state.redo(&Redo, window, cx);
10601 assert_eq!(state.value(), "x");
10602 });
10603 });
10604 }
10605
10606 #[gpui::test]
10607 fn test_undo_manager_noop_edit_preserves_redo(cx: &mut TestAppContext) {
10608 let input_view = InputView::build(cx, |state| state);
10609 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10610 let input = input_view.input;
10611
10612 cx.update(|window, cx| {
10613 input.update(cx, |state, cx| {
10614 state.replace_text_in_range(None, "a", window, cx);
10615 state.move_to(0, None, cx);
10616 state.replace_text_in_range(None, "", window, cx);
10617 state.undo(&Undo, window, cx);
10618 assert_eq!(state.value(), "");
10619 state.redo(&Redo, window, cx);
10620 assert_eq!(state.value(), "a");
10621 assert_eq!(state.cursor(), 1);
10622 });
10623 });
10624 }
10625
10626 #[gpui::test]
10627 fn test_cursor_round_trip_stops_typing_coalescing(cx: &mut TestAppContext) {
10628 let input_view = InputView::build(cx, |state| state);
10629 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10630 let input = input_view.input;
10631
10632 cx.update(|window, cx| {
10633 input.update(cx, |state, cx| {
10634 state.replace_text_in_range(None, "a", window, cx);
10635 state.left(&MoveLeft, window, cx);
10636 state.right(&MoveRight, window, cx);
10637 state.replace_text_in_range(None, "b", window, cx);
10638
10639 state.undo(&Undo, window, cx);
10640 assert_eq!(state.value(), "a");
10641 state.undo(&Undo, window, cx);
10642 assert_eq!(state.value(), "");
10643 });
10644 });
10645 }
10646
10647 #[gpui::test]
10648 fn test_undo_manager_noop_edit_breaks_coalescing_without_clearing_history(
10649 cx: &mut TestAppContext,
10650 ) {
10651 let input_view = InputView::build(cx, |state| state);
10652 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10653 let input = input_view.input;
10654
10655 cx.update(|window, cx| {
10656 input.update(cx, |state, cx| {
10657 state.replace_text_in_range(None, "alpha", window, cx);
10658 state.replace_text_in_range(None, "", window, cx);
10659 state.replace_text_in_range(None, "beta", window, cx);
10660 assert_eq!(state.value(), "alphabeta");
10661
10662 state.undo(&Undo, window, cx);
10663 assert_eq!(state.value(), "alpha");
10664 state.undo(&Undo, window, cx);
10665 assert_eq!(state.value(), "");
10666 });
10667 });
10668 }
10669
10670 #[gpui::test]
10671 fn test_undo_manager_masked_redo_restores_actual_cursor(cx: &mut TestAppContext) {
10672 let input_view = InputView::build(cx, |state| {
10673 state.mask_pattern(MaskPattern::Number {
10674 separator: Some(','),
10675 fraction: None,
10676 })
10677 });
10678 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
10679 let input = input_view.input;
10680
10681 cx.update(|window, cx| {
10682 input.update(cx, |state, cx| {
10683 state.set_value("12345", window, cx);
10684 state.set_selected_range(2..2, cx);
10685 state.replace_text_in_range(None, "9", window, cx);
10686 let selection_after_edit = state.selected_range();
10687 assert_ne!(selection_after_edit.end, state.value().len());
10688
10689 state.undo(&Undo, window, cx);
10690 state.redo(&Redo, window, cx);
10691 assert_eq!(state.selected_range(), selection_after_edit);
10692 });
10693 });
10694 }
10695
10696 #[gpui::test]
10699 fn test_fold_all_and_fold_at_level(cx: &mut TestAppContext) {
10700 use crate::input::FoldRange;
10701
10702 let view = InputView::<EditorMode>::new(cx);
10703 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10704 let input = view.input;
10705
10706 cx.update(|window, cx| {
10708 input.update(cx, |state, cx| {
10709 state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj", window, cx);
10710 state.apply_highlighter_fold_candidates(
10711 vec![
10712 FoldRange::new(0, 9),
10713 FoldRange::new(1, 4),
10714 FoldRange::new(2, 3),
10715 FoldRange::new(5, 8),
10716 ],
10717 cx,
10718 );
10719 });
10720 });
10721 let folded = |cx: &mut VisualTestContext| {
10722 cx.update(|_, cx| {
10723 input.read_with(cx, |state, _| {
10724 state
10725 .display_map
10726 .folded_ranges()
10727 .iter()
10728 .map(|f| f.start_line)
10729 .collect::<Vec<_>>()
10730 })
10731 })
10732 };
10733
10734 cx.update(|_, cx| input.update(cx, |state, cx| state.fold_all(cx)));
10735 assert_eq!(folded(&mut cx), vec![0, 1, 2, 5]);
10736
10737 cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(2, cx)));
10738 assert_eq!(folded(&mut cx), vec![1, 5]);
10739
10740 cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(1, cx)));
10741 assert_eq!(folded(&mut cx), vec![0]);
10742
10743 cx.update(|_, cx| input.update(cx, |state, cx| state.fold_at_level(3, cx)));
10744 assert_eq!(folded(&mut cx), vec![2]);
10745
10746 cx.update(|_, cx| input.update(cx, |state, cx| state.unfold_all(cx)));
10747 assert!(folded(&mut cx).is_empty());
10748 cx.update(|_, cx| {
10749 input.read_with(cx, |state, _| assert_eq!(state.fold_candidates().len(), 4));
10750 });
10751
10752 cx.update(|_, cx| {
10753 input.update(cx, |state, cx| {
10754 assert!(state.set_folded(5, true, cx));
10755 assert!(!state.set_folded(6, true, cx));
10756 })
10757 });
10758 assert_eq!(folded(&mut cx), vec![5]);
10759 }
10760
10761 #[gpui::test]
10767 fn test_unfold_at(cx: &mut TestAppContext) {
10768 use crate::input::{FoldRange, Position};
10769
10770 let view = InputView::<EditorMode>::new(cx);
10771 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10772 let input = view.input;
10773
10774 cx.update(|window, cx| {
10777 input.update(cx, |state, cx| {
10778 state.set_value("a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl", window, cx);
10779 state.apply_highlighter_fold_candidates(
10780 vec![
10781 FoldRange::new(0, 5),
10782 FoldRange::new(2, 4),
10783 FoldRange::new(7, 10),
10784 ],
10785 cx,
10786 );
10787 state.display_map.set_folded(0, true);
10788 state.display_map.set_folded(2, true);
10789 state.display_map.set_folded(7, true);
10790 });
10791 });
10792
10793 for line in [0, 5] {
10796 cx.update(|_, cx| {
10797 input.update(cx, |state, cx| {
10798 assert!(!state.display_map.is_buffer_line_hidden(line));
10799 assert!(!state.unfold_at(Position::new(line as u32, 0), cx));
10800 });
10801 input.read_with(cx, |state, _| {
10802 assert!(state.display_map.is_folded_at(0));
10803 assert!(state.display_map.is_folded_at(2));
10804 assert!(state.display_map.is_folded_at(7));
10805 });
10806 });
10807 }
10808
10809 cx.update(|_, cx| {
10812 input.update(cx, |state, cx| {
10813 assert!(state.unfold_at(Position::new(3, 0), cx));
10814 });
10815 input.read_with(cx, |state, _| {
10816 assert!(!state.display_map.is_buffer_line_hidden(3));
10817 assert!(!state.display_map.is_folded_at(0));
10818 assert!(!state.display_map.is_folded_at(2));
10819 assert!(state.display_map.is_folded_at(7));
10820 assert!(state.display_map.is_fold_candidate(0));
10822 assert!(state.display_map.is_fold_candidate(2));
10823 });
10824 });
10825
10826 cx.update(|_, cx| {
10828 input.update(cx, |state, cx| {
10829 assert!(!state.unfold_at(Position::new(3, 0), cx));
10830 });
10831 });
10832 }
10833
10834 #[gpui::test]
10839 fn test_blur_keeps_decorations(cx: &mut TestAppContext) {
10840 let view = InputView::<EditorMode>::new(cx);
10841 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10842 let input = view.input;
10843
10844 cx.update(|window, cx| {
10845 input.update(cx, |state, cx| {
10846 state.set_value("select 1", window, cx);
10847 let _collection = state.create_decorations_collection(
10848 vec![crate::input::TextDecoration::new(
10849 0..6,
10850 gpui::HighlightStyle {
10851 font_weight: Some(gpui::FontWeight::BOLD),
10852 ..Default::default()
10853 },
10854 )],
10855 cx,
10856 );
10857 state.present_hover(
10858 0..6,
10859 lsp_types::Hover {
10860 contents: lsp_types::HoverContents::Scalar(
10861 lsp_types::MarkedString::String("docs".into()),
10862 ),
10863 range: None,
10864 },
10865 cx,
10866 );
10867 assert!(state.hover_popover().is_some());
10868
10869 state.on_blur(window, cx);
10870
10871 assert!(
10872 state.hover_popover().is_none(),
10873 "blur should hide the hover popover"
10874 );
10875 let decorations = state.extras.decoration_layers();
10876 assert!(
10877 decorations.iter().any(|layer| !layer.is_empty()),
10878 "blur must not discard decorations"
10879 );
10880 });
10881 });
10882 }
10883
10884 #[gpui::test]
10889 fn test_kind_does_not_follow_the_row_count(cx: &mut TestAppContext) {
10890 let view = InputView::build_textarea(cx, |state| state.auto_grow(1, 1));
10891 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
10892 view.input.read_with(&mut cx, |state, _| {
10893 assert!(state.is_multi_line());
10894 assert!(!state.is_single_line());
10895 assert!(!state.is_code_editor());
10896 });
10897 }
10898
10899 #[gpui::test]
10900 fn test_textarea_prewrap_prepares_content_rows_before_layout(cx: &mut TestAppContext) {
10901 cx.update(crate::init);
10902 for (value, expected_rows) in [("", 1), ("one\ntwo", 2)] {
10903 cx.open_window(size(px(400.), px(100.)), |window, cx| {
10904 let font = window.text_style().font();
10905 cx.new(|cx| {
10906 let mut state = crate::input::TextareaState::new(window, cx)
10907 .rows(12)
10908 .default_value(value);
10909 assert_eq!(state.display_map().wrap_row_count(), 0);
10910 state.prewrap(font, px(14.), px(120.), cx);
10911 assert_eq!(state.display_map().wrap_row_count(), expected_rows);
10912 assert_eq!(state.value(), value);
10913 state
10914 });
10915 gpui::EmptyView
10916 });
10917 }
10918 }
10919
10920 #[gpui::test]
10921 fn test_textarea_prewrap_respects_soft_wrap_before_layout(cx: &mut TestAppContext) {
10922 cx.update(crate::init);
10923 let value = "select id, name, email, phone from users where active\nlimit 10";
10924 for soft_wrap in [true, false] {
10925 cx.open_window(size(px(400.), px(100.)), |window, cx| {
10926 let font = window.text_style().font();
10927 cx.new(|cx| {
10928 let mut state = crate::input::TextareaState::new(window, cx)
10929 .rows(1)
10930 .soft_wrap(soft_wrap)
10931 .default_value(value);
10932 state.prewrap(font, px(14.), px(120.), cx);
10933 let rows = state.display_map().wrap_row_count();
10934 if soft_wrap {
10935 assert!(rows > 2, "the first logical line must wrap");
10936 } else {
10937 assert_eq!(rows, 2);
10938 }
10939 assert_eq!(state.value(), value);
10940 state
10941 });
10942 gpui::EmptyView
10943 });
10944 }
10945 }
10946
10947 #[gpui::test]
10948 fn test_prewrap_counts_wrapped_rows_before_the_first_paint(cx: &mut TestAppContext) {
10949 cx.update(crate::init);
10950 let text = "select id, name, email, phone from users where active\nlimit 10";
10951 for (soft_wrap, wraps) in [(true, true), (false, false)] {
10952 let mut input = None;
10953 cx.open_window(size(px(400.), px(100.)), |window, cx| {
10954 let font = window.text_style().font();
10955 let editor = cx.new(|cx| {
10956 let mut state = crate::input::EditorState::new(window, cx)
10957 .soft_wrap(soft_wrap)
10958 .default_value(text);
10959 state.prewrap(font, px(14.), px(120.), cx);
10960 state
10961 });
10962 input = Some(editor);
10963 gpui::EmptyView
10964 });
10965 let rows = input
10966 .unwrap()
10967 .read_with(cx, |state, _| state.display_map().wrap_row_count());
10968 assert_eq!(rows > 2, wraps, "soft_wrap({soft_wrap}): {rows} rows");
10970 if !wraps {
10971 assert_eq!(rows, 2);
10972 }
10973 }
10974 }
10975
10976 #[gpui::test]
10977 fn test_prewrap_uses_the_configured_tab_stops(cx: &mut TestAppContext) {
10978 cx.update(crate::init);
10979 cx.open_window(size(px(400.), px(100.)), |window, cx| {
10980 let font = window.text_style().font();
10981 let font_size = px(14.);
10982 let font_id = window.text_system().resolve_font(&font);
10983 let space_width = window.text_system().layout_width(font_id, font_size, ' ');
10984 cx.new(|cx| {
10985 let mut state = crate::input::EditorState::new(window, cx)
10986 .tab_size(TabSize {
10987 tab_size: 4,
10988 hard_tabs: true,
10989 })
10990 .default_value("\t\t");
10991 for (tab_size, expected_rows) in [(4, 2), (2, 1), (8, 2)] {
10992 state.set_tab_size(
10993 TabSize {
10994 tab_size,
10995 hard_tabs: true,
10996 },
10997 cx,
10998 );
10999 state.prewrap(font.clone(), font_size, space_width * 5. + RIGHT_MARGIN, cx);
11000 assert_eq!(state.display_map().wrap_row_count(), expected_rows);
11001 }
11002 state
11003 });
11004 gpui::EmptyView
11005 });
11006 }
11007
11008 #[gpui::test]
11011 fn test_prewrap_wraps_with_the_wrapping_indent(cx: &mut TestAppContext) {
11012 cx.update(crate::init);
11013 let text = " select id, name, email, phone from users where active";
11014 let mut rows = Vec::new();
11015 for indent in [WrappingIndent::Same, WrappingIndent::None] {
11016 let mut input = None;
11017 cx.open_window(size(px(400.), px(100.)), |window, cx| {
11018 let font = window.text_style().font();
11019 input = Some(cx.new(|cx| {
11020 let mut state = crate::input::EditorState::new(window, cx)
11021 .wrapping_indent(indent)
11022 .default_value(text);
11023 state.prewrap(font, px(14.), px(200.), cx);
11024 state
11025 }));
11026 gpui::EmptyView
11027 });
11028 rows.push(
11029 input
11030 .unwrap()
11031 .read_with(cx, |state, _| state.display_map().wrap_row_count()),
11032 );
11033 }
11034 assert!(rows[0] > rows[1], "rows with Same, None: {rows:?}");
11035 }
11036
11037 #[gpui::test]
11039 fn test_prewrap_does_nothing_once_laid_out(cx: &mut TestAppContext) {
11040 struct Frame(Entity<crate::input::EditorState>);
11041 impl Render for Frame {
11042 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11043 crate::input::InputBase::new("frame")
11044 .h(px(100.))
11045 .child(crate::input::Editor::new(&self.0))
11046 }
11047 }
11048
11049 cx.update(crate::init);
11050 let text = "select id, name, email, phone from users where active\nlimit 10";
11051 let mut input = None;
11052 let window = cx.open_window(size(px(400.), px(100.)), |window, cx| {
11053 let state = cx.new(|cx| crate::input::EditorState::new(window, cx).default_value(text));
11054 input = Some(state.clone());
11055 Frame(state)
11056 });
11057 let input = input.unwrap();
11058 let mut cx = VisualTestContext::from_window(window.into(), cx);
11059 cx.update(|window, cx| window.draw(cx).clear(cx));
11060
11061 let laid_out = input.read_with(&cx, |state, _| state.display_map().wrap_row_count());
11062 assert!(laid_out >= 2, "laid out to {laid_out} rows");
11063 let font = cx.update(|window, _| window.text_style().font());
11064 input.update(&mut cx, |state, cx| {
11065 state.prewrap(font, px(14.), px(60.), cx)
11066 });
11067 assert_eq!(
11068 input.read_with(&cx, |state, _| state.display_map().wrap_row_count()),
11069 laid_out
11070 );
11071 }
11072
11073 #[gpui::test]
11078 fn test_soft_wrap_is_enabled_by_default(cx: &mut TestAppContext) {
11079 let textarea = InputView::build_textarea(cx, |state| state);
11080 let mut textarea_cx = VisualTestContext::from_window(textarea.window_handle.into(), cx);
11081 textarea
11082 .input
11083 .read_with(&mut textarea_cx, |state, _| assert!(state.soft_wrap));
11084
11085 let editor = InputView::<EditorMode>::new(cx);
11086 let mut editor_cx = VisualTestContext::from_window(editor.window_handle.into(), cx);
11087 editor
11088 .input
11089 .read_with(&mut editor_cx, |state, _| assert!(state.soft_wrap));
11090 }
11091
11092 fn parse_cursor_spec(input: &str) -> (String, Vec<usize>) {
11096 let mut full_text = String::new();
11097 let mut cursor_offsets = Vec::new();
11098 let non_empty_lines: Vec<&str> = input.lines().filter(|l| !l.is_empty()).collect();
11099
11100 for (line_idx, line) in non_empty_lines.iter().enumerate() {
11101 let mut positions = Vec::new();
11102 let mut text = String::new();
11103 for ch in line.chars() {
11104 if ch == '|' {
11105 positions.push(text.len());
11106 } else {
11107 text.push(ch);
11108 }
11109 }
11110
11111 if line_idx > 0 {
11112 full_text.push('\n');
11113 }
11114 let line_start = full_text.len();
11115 for pos in positions {
11116 cursor_offsets.push(line_start + pos);
11117 }
11118 full_text.push_str(&text);
11119 }
11120 full_text.push('\n');
11121
11122 (full_text, cursor_offsets)
11123 }
11124
11125 fn multi_line(cx: &mut TestAppContext) -> InputView<TextareaMode> {
11127 InputView::build_textarea(cx, |state| state)
11128 }
11129
11130 fn setup_cursors<M: InputModeKind>(
11132 cx: &mut VisualTestContext,
11133 input: &Entity<InputBaseState<M>>,
11134 spec: &str,
11135 ) {
11136 let (full_text, offsets) = parse_cursor_spec(spec);
11137 cx.update(|window, cx| {
11138 input.update(cx, |state, cx| {
11139 state.set_value(&full_text, window, cx);
11140 let selections = offsets
11141 .into_iter()
11142 .map(|offset| {
11143 CursorSelection::new(state.selections.generate_id(), offset, offset)
11144 })
11145 .collect();
11146 state.selections.replace_all(selections);
11147 cx.notify();
11148 });
11149 });
11150 }
11151
11152 #[track_caller]
11154 fn assert_cursors<M: InputModeKind>(
11155 cx: &mut VisualTestContext,
11156 input: &Entity<InputBaseState<M>>,
11157 spec: &str,
11158 ) {
11159 let (expected_text, mut expected_cursors) = parse_cursor_spec(spec);
11160 expected_cursors.sort();
11161
11162 let (actual_text, mut actual_cursors) = input.read_with(cx, |state, _| {
11163 (
11164 state.text.to_string(),
11165 state
11166 .selections
11167 .iter()
11168 .map(|s| s.cursor_offset())
11169 .collect::<Vec<_>>(),
11170 )
11171 });
11172 actual_cursors.sort();
11173
11174 assert_eq!(
11175 actual_text, expected_text,
11176 "Text mismatch:\nExpected: {expected_text:?}\nActual: {actual_text:?}"
11177 );
11178 assert_eq!(
11179 actual_cursors, expected_cursors,
11180 "Cursor mismatch:\nExpected: {expected_cursors:?}\nActual: {actual_cursors:?}"
11181 );
11182 }
11183
11184 #[gpui::test]
11185 fn test_alt_drag_selects_a_block_and_replaces_each_row(cx: &mut TestAppContext) {
11186 cx.update(crate::init);
11187 let view = InputView::<EditorMode>::new(cx);
11188 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11189 for modifiers in [
11190 gpui::Modifiers {
11191 alt: true,
11192 ..Default::default()
11193 },
11194 gpui::Modifiers {
11195 alt: true,
11196 shift: true,
11197 ..Default::default()
11198 },
11199 #[cfg(target_os = "linux")]
11200 gpui::Modifiers {
11201 alt: true,
11202 control: true,
11203 ..Default::default()
11204 },
11205 ] {
11206 setup_cursors(&mut cx, &view.input, "|abcd\nabcd\nabcd");
11207 cx.update(|window, cx| {
11208 view.input.update(cx, |state, cx| state.focus(window, cx));
11209 });
11210 let (start, end) = view.input.read_with(&cx, |state, _| {
11211 let layout = state.last_layout.as_ref().unwrap();
11212 let origin = state.last_bounds.unwrap().origin;
11213 let position = |row: usize, col| {
11214 let local = layout.lines[row]
11215 .position_for_index(col, layout, false)
11216 .unwrap();
11217 origin
11218 + point(
11219 layout.line_number_width + local.x,
11220 layout.line_height * (row as f32 + 0.5),
11221 )
11222 };
11223 (position(0, 1), position(2, 3))
11224 });
11225 let end = point(end.x - px(0.5), end.y);
11228 cx.update(|_, cx| {
11230 view.input.update(cx, |state, _| {
11231 state.extras.hover_definition.update(
11232 0..4,
11233 vec![lsp_types::LocationLink {
11234 origin_selection_range: None,
11235 target_uri: "file:///tmp/column-selection.rs".parse().unwrap(),
11236 target_range: Default::default(),
11237 target_selection_range: Default::default(),
11238 }],
11239 );
11240 });
11241 });
11242 cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
11243 cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
11244 cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
11245 view.input.read_with(&cx, |state, _| {
11246 let ranges: Vec<_> = state
11247 .selections
11248 .iter()
11249 .map(|sel| sel.start..sel.end)
11250 .collect();
11251 assert_eq!(ranges, vec![1..3, 6..8, 11..13]);
11252 });
11253 cx.simulate_mouse_move(start, None, modifiers);
11255 cx.simulate_keystrokes("x");
11256 assert_cursors(&mut cx, &view.input, "ax|d\nax|d\nax|d");
11257 }
11258 }
11259
11260 #[gpui::test]
11261 fn test_alt_drag_extends_upward_from_an_existing_cursor(cx: &mut TestAppContext) {
11262 cx.update(crate::init);
11263 let view = InputView::<EditorMode>::new(cx);
11264 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11265 setup_cursors(&mut cx, &view.input, "abcd\nabcd\na|bcd");
11266 cx.update(|window, cx| {
11267 view.input.update(cx, |state, cx| state.focus(window, cx));
11268 });
11269 let (start, end) = view.input.read_with(&cx, |state, _| {
11270 let layout = state.last_layout.as_ref().unwrap();
11271 let origin = state.last_bounds.unwrap().origin;
11272 let local = layout.lines[0]
11273 .position_for_index(1, layout, false)
11274 .unwrap();
11275 let x = layout.line_number_width + local.x;
11276 (
11277 origin + point(x, layout.line_height * 2.5),
11278 origin + point(x, layout.line_height * 0.5),
11279 )
11280 });
11281 let modifiers = gpui::Modifiers {
11282 alt: true,
11283 ..Default::default()
11284 };
11285 cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
11286 cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
11287 cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
11288 assert_cursors(&mut cx, &view.input, "a|bcd\na|bcd\na|bcd");
11289 }
11290
11291 #[gpui::test]
11292 fn test_alt_drag_over_a_short_row_keeps_the_block_width(cx: &mut TestAppContext) {
11293 cx.update(crate::init);
11294 let view = InputView::<EditorMode>::new(cx);
11295 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11296 setup_cursors(&mut cx, &view.input, "abcdef\nab\nabcdef");
11297 cx.update(|window, cx| {
11298 view.input.update(cx, |state, cx| state.focus(window, cx));
11299 });
11300 let (start, end) = view.input.read_with(&cx, |state, _| {
11303 let layout = state.last_layout.as_ref().unwrap();
11304 let origin = state.last_bounds.unwrap().origin;
11305 let x_of = |index| {
11306 layout.line_number_width
11307 + layout.lines[0]
11308 .position_for_index(index, layout, false)
11309 .unwrap()
11310 .x
11311 };
11312 (
11313 origin + point(x_of(1), layout.line_height * 0.5),
11314 origin + point(x_of(5), layout.line_height * 1.5),
11315 )
11316 });
11317 let modifiers = gpui::Modifiers {
11318 alt: true,
11319 shift: true,
11320 ..Default::default()
11321 };
11322 cx.simulate_mouse_down(start, MouseButton::Left, modifiers);
11323 cx.simulate_mouse_move(end, MouseButton::Left, modifiers);
11324 cx.simulate_mouse_up(end, MouseButton::Left, modifiers);
11325
11326 view.input.read_with(&cx, |state, _| {
11328 let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
11329 assert_eq!(ranges, vec![(1, 5), (8, 9)]);
11330 });
11331 }
11332
11333 #[gpui::test]
11334 fn test_lost_mouse_release_ends_selection_on_plain_motion(cx: &mut TestAppContext) {
11335 cx.update(crate::init);
11336 let view = InputView::<EditorMode>::new(cx);
11337 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11338 setup_cursors(&mut cx, &view.input, "|alpha bravo charlie delta");
11339 let (start, end, beyond) = view.input.read_with(&cx, |state, _| {
11340 (
11341 state.range_to_bounds(&(0..1)).unwrap().center(),
11342 state.range_to_bounds(&(6..7)).unwrap().center(),
11343 state.range_to_bounds(&(18..19)).unwrap().center(),
11344 )
11345 });
11346 cx.simulate_mouse_down(start, MouseButton::Left, gpui::Modifiers::default());
11347 cx.simulate_mouse_move(end, MouseButton::Left, gpui::Modifiers::default());
11348 let selected = view.input.read_with(&cx, |state, _| {
11349 assert!(state.selecting);
11350 let text = state.selected_value();
11351 assert!(!text.is_empty());
11352 text
11353 });
11354 cx.simulate_mouse_move(beyond, None, gpui::Modifiers::default());
11355 view.input.read_with(&cx, |state, _| {
11356 assert!(!state.selecting);
11357 assert_eq!(state.selected_value(), selected);
11358 });
11359 }
11360
11361 #[gpui::test]
11362 fn test_alt_mouse_release_outside_editor_ends_column_selection(cx: &mut TestAppContext) {
11363 cx.update(crate::init);
11364 let view = InputView::<EditorMode>::new(cx);
11365 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11366 setup_cursors(&mut cx, &view.input, "|abcd\nabcd");
11367 let position = view.input.read_with(&cx, |state, _| {
11368 let layout = state.last_layout.as_ref().unwrap();
11369 state.last_bounds.unwrap().origin
11370 + point(layout.line_number_width + px(2.), layout.line_height * 0.5)
11371 });
11372 let modifiers = gpui::Modifiers {
11373 alt: true,
11374 ..Default::default()
11375 };
11376 cx.simulate_mouse_down(position, MouseButton::Left, modifiers);
11377 cx.simulate_mouse_up(point(px(-100.), px(-100.)), MouseButton::Left, modifiers);
11378 view.input.read_with(&cx, |state, _| {
11379 assert!(!state.selecting);
11380 assert!(state.column_select_start.is_none());
11381 });
11382 }
11383
11384 #[gpui::test]
11385 fn test_consumed_keystrokes_keep_cursor_visible(cx: &mut TestAppContext) {
11386 let view = InputView::<EditorMode>::new(cx);
11387 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11388 setup_cursors(&mut cx, &view.input, "a|b");
11389 cx.update(|window, cx| {
11390 view.input.update(cx, |state, cx| {
11391 state.focus(window, cx);
11392 state.pause_blink_cursor(cx);
11393 });
11394 });
11395 cx.run_until_parked();
11396 cx.executor()
11397 .advance_clock(std::time::Duration::from_millis(300));
11398 cx.run_until_parked();
11399 view.input.read_with(&cx, |state, cx| {
11400 assert!(!state.blink_cursor.read(cx).visible());
11401 });
11402 for _ in 0..5 {
11404 #[cfg(target_os = "macos")]
11405 cx.simulate_keystrokes("cmd-c");
11406 #[cfg(not(target_os = "macos"))]
11407 cx.simulate_keystrokes("ctrl-c");
11408 cx.run_until_parked();
11409 cx.executor()
11410 .advance_clock(std::time::Duration::from_millis(200));
11411 cx.run_until_parked();
11412 view.input.read_with(&cx, |state, cx| {
11413 assert!(state.blink_cursor.read(cx).visible());
11414 });
11415 }
11416 }
11417
11418 #[gpui::test]
11419 fn test_mouse_down_shows_cursor_like_a_cursor_move(cx: &mut TestAppContext) {
11420 cx.update(crate::init);
11421 let view = InputView::<EditorMode>::new(cx);
11422 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11423 setup_cursors(&mut cx, &view.input, "abcd|efgh");
11424 let position = |offset: Pixels, cx: &mut VisualTestContext| {
11425 view.input.read_with(cx, |state, _| {
11426 let layout = state.last_layout.as_ref().unwrap();
11427 state.last_bounds.unwrap().origin
11428 + point(layout.line_number_width + offset, layout.line_height * 0.5)
11429 })
11430 };
11431 let visible = |cx: &mut VisualTestContext| {
11432 view.input
11433 .read_with(cx, |state, cx| state.blink_cursor.read(cx).visible())
11434 };
11435
11436 let first = position(px(2.), &mut cx);
11439 cx.simulate_mouse_down(first, MouseButton::Left, Default::default());
11440 assert!(visible(&mut cx));
11441 cx.simulate_mouse_up(first, MouseButton::Left, Default::default());
11442 cx.run_until_parked();
11443
11444 cx.executor()
11447 .advance_clock(std::time::Duration::from_millis(400));
11448 cx.run_until_parked();
11449 assert!(!visible(&mut cx));
11450 let second = position(px(30.), &mut cx);
11451 cx.simulate_mouse_down(second, MouseButton::Left, Default::default());
11452 assert!(visible(&mut cx));
11453 cx.executor()
11454 .advance_clock(std::time::Duration::from_millis(250));
11455 cx.run_until_parked();
11456 assert!(visible(&mut cx));
11457 cx.simulate_mouse_up(second, MouseButton::Left, Default::default());
11458 }
11459
11460 #[gpui::test]
11461 fn test_multi_cursor_actions_reveal_hidden_carets(cx: &mut TestAppContext) {
11462 let view = InputView::<EditorMode>::new(cx);
11463 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11464 setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
11465 for action in 0..6 {
11468 cx.update(|_, cx| {
11469 view.input.update(cx, |state, cx| {
11470 state.blink_cursor = cx.new(BlinkCursor::new);
11471 state.blink_cursor.update(cx, |cursor, cx| cursor.start(cx));
11472 });
11473 });
11474 cx.run_until_parked();
11475 cx.executor()
11476 .advance_clock(std::time::Duration::from_millis(500));
11477 cx.run_until_parked();
11478 view.input.read_with(&cx, |state, cx| {
11479 assert!(!state.blink_cursor.read(cx).visible(), "action {action}");
11480 });
11481
11482 cx.update(|window, cx| {
11483 view.input.update(cx, |state, cx| {
11484 match action {
11485 0 => state.add_cursor_above(&AddCursorAbove, window, cx),
11486 1 => state.add_cursor_below(&AddCursorBelow, window, cx),
11487 2 => state.select_up(&SelectUp, window, cx),
11488 3 => state.select_down(&SelectDown, window, cx),
11489 4 => state.replace_text_in_range(None, "x", window, cx),
11490 _ => state.backspace(&Backspace, window, cx),
11491 }
11492 assert!(state.blink_cursor.read(cx).visible(), "action {action}");
11493 });
11494 });
11495 }
11496 }
11497
11498 #[gpui::test]
11499 fn test_multi_cursor_keyboard_dispatch(cx: &mut TestAppContext) {
11500 let view = InputView::<EditorMode>::new(cx);
11501 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11502 setup_cursors(&mut cx, &view.input, "ab\na|b\nab");
11503 cx.update(|window, cx| {
11504 view.input.update(cx, |state, cx| state.focus(window, cx));
11505 });
11506 #[cfg(target_os = "macos")]
11507 cx.simulate_keystrokes("cmd-alt-up");
11508 #[cfg(target_os = "windows")]
11509 cx.simulate_keystrokes("ctrl-alt-up");
11510 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
11511 cx.simulate_keystrokes("alt-shift-up");
11512 view.input
11513 .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
11514 #[cfg(target_os = "macos")]
11515 cx.simulate_keystrokes("cmd-alt-down");
11516 #[cfg(target_os = "windows")]
11517 cx.simulate_keystrokes("ctrl-alt-down");
11518 #[cfg(not(any(target_os = "macos", target_os = "windows")))]
11519 cx.simulate_keystrokes("alt-shift-down");
11520 view.input
11521 .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 3));
11522 cx.simulate_keystrokes("x");
11523 assert_cursors(&mut cx, &view.input, "ax|b\nax|b\nax|b");
11524 }
11525
11526 #[gpui::test]
11527 fn test_multi_cursor_platform_word_selection_dispatch(cx: &mut TestAppContext) {
11528 let view = InputView::<EditorMode>::new(cx);
11529 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11530 setup_cursors(&mut cx, &view.input, "one |two\none |two");
11531 cx.update(|window, cx| {
11532 view.input.update(cx, |state, cx| state.focus(window, cx));
11533 });
11534 #[cfg(any(target_os = "macos", target_os = "linux"))]
11535 cx.simulate_keystrokes("alt-shift-right");
11536 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
11537 cx.simulate_keystrokes("ctrl-shift-right");
11538 cx.simulate_keystrokes("x");
11539 assert_cursors(&mut cx, &view.input, "one x|\none x|");
11540 setup_cursors(&mut cx, &view.input, "one two|\none two|");
11541 #[cfg(any(target_os = "macos", target_os = "linux"))]
11542 cx.simulate_keystrokes("alt-shift-left");
11543 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
11544 cx.simulate_keystrokes("ctrl-shift-left");
11545 cx.simulate_keystrokes("x");
11546 assert_cursors(&mut cx, &view.input, "one x|\none x|");
11547 }
11548
11549 #[cfg(not(target_os = "macos"))]
11550 #[gpui::test]
11551 fn test_multi_cursor_horizontal_selection_dispatch(cx: &mut TestAppContext) {
11552 let view = InputView::<EditorMode>::new(cx);
11553 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11554 setup_cursors(&mut cx, &view.input, "ab\na|b");
11555 cx.update(|window, cx| {
11556 view.input.update(cx, |state, cx| state.focus(window, cx));
11557 });
11558 #[cfg(target_os = "windows")]
11559 cx.simulate_keystrokes("ctrl-alt-up");
11560 #[cfg(not(target_os = "windows"))]
11561 cx.simulate_keystrokes("alt-shift-up");
11562 #[cfg(target_os = "linux")]
11563 cx.simulate_keystrokes("shift-right");
11564 #[cfg(not(target_os = "linux"))]
11565 cx.simulate_keystrokes("alt-shift-right");
11566 view.input.read_with(&cx, |state, _| {
11567 assert_eq!(
11568 state
11569 .selections
11570 .iter()
11571 .map(|s| s.start..s.end)
11572 .collect::<Vec<_>>(),
11573 vec![4..5, 1..2]
11574 );
11575 });
11576 #[cfg(target_os = "linux")]
11577 cx.simulate_keystrokes("shift-left shift-left");
11578 #[cfg(not(target_os = "linux"))]
11579 cx.simulate_keystrokes("alt-shift-left alt-shift-left");
11580 view.input.read_with(&cx, |state, _| {
11581 assert_eq!(
11582 state
11583 .selections
11584 .iter()
11585 .map(|s| s.start..s.end)
11586 .collect::<Vec<_>>(),
11587 vec![3..4, 0..1]
11588 );
11589 });
11590 cx.simulate_keystrokes("x");
11591 assert_cursors(&mut cx, &view.input, "x|b\nx|b");
11592 }
11593
11594 #[gpui::test]
11595 fn test_multi_cursor_alt_click_dispatch(cx: &mut TestAppContext) {
11596 cx.update(crate::init);
11597 let view = InputView::<EditorMode>::new(cx);
11598 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11599 setup_cursors(&mut cx, &view.input, "a|b\nab\nab");
11600 cx.update(|window, cx| {
11601 view.input.update(cx, |state, cx| state.focus(window, cx));
11602 });
11603 let position = view.input.read_with(&cx, |state, _| {
11604 let bounds = state.last_bounds.unwrap();
11605 let layout = state.last_layout.as_ref().unwrap();
11606 bounds.origin + point(layout.line_number_width + px(2.), layout.line_height * 1.5)
11607 });
11608 cx.simulate_click(
11609 position,
11610 gpui::Modifiers {
11611 alt: true,
11612 ..Default::default()
11613 },
11614 );
11615 view.input
11616 .read_with(&cx, |state, _| assert_eq!(state.selections.len(), 2));
11617 }
11618
11619 #[gpui::test]
11620 fn test_add_selection(cx: &mut TestAppContext) {
11621 let view = InputView::<EditorMode>::new(cx);
11622 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11623 cx.update(|window, cx| {
11624 view.input.update(cx, |state, cx| {
11625 state.focus(window, cx);
11626 state.set_value("foo bar foo", window, cx);
11627 state.set_selected_range(0..3, cx);
11628 state.add_selection(8..11, cx);
11630 state.add_selection(0..3, cx);
11632 });
11633 });
11634 view.input.read_with(&cx, |state, _| {
11635 let mut ranges: Vec<Range<usize>> =
11636 state.selections.iter().map(|s| s.start..s.end).collect();
11637 ranges.sort_by_key(|r| r.start);
11638 assert_eq!(ranges, vec![0..3, 8..11]);
11639 });
11640 cx.simulate_keystrokes("x");
11642 view.input.read_with(&cx, |state, _| {
11643 assert_eq!(state.text.to_string(), "x bar x")
11644 });
11645 }
11646
11647 #[gpui::test]
11648 fn test_add_selection_preserves_crlf_boundaries(cx: &mut TestAppContext) {
11649 let view = InputView::build_textarea(cx, |state| state.default_value("a\r\nb"));
11650 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11651 cx.update(|window, cx| {
11652 view.input.update(cx, |state, cx| {
11653 state.focus(window, cx);
11654 state.set_selected_range(4..4, cx);
11655 state.add_selection(2..2, cx);
11656 let ranges: Vec<_> = state.selections.iter().map(|s| s.start..s.end).collect();
11657 assert_eq!(ranges, vec![4..4, 1..1]);
11658 });
11659 });
11660 cx.simulate_keystrokes("x");
11661 view.input.read_with(&cx, |state, _| {
11662 assert_eq!(state.value(), "ax\r\nbx");
11663 });
11664 cx.update(|window, cx| {
11665 view.input.update(cx, |state, cx| {
11666 state.set_value("a\r\nb", window, cx);
11667 state.set_selected_range(4..4, cx);
11668 state.add_selection(2..3, cx);
11669 state.cut(&Cut, window, cx);
11670 assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "\r\n");
11671 assert_eq!(state.value(), "ab");
11672 });
11673 });
11674 }
11675
11676 #[gpui::test]
11677 fn test_add_selection_merges_overlaps_before_copy_and_cut(cx: &mut TestAppContext) {
11678 let view = InputView::<EditorMode>::new(cx);
11679 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11680 cx.update(|window, cx| {
11681 view.input.update(cx, |state, cx| {
11682 for additions in [vec![2..5], vec![0..5], vec![4..5, 2..4]] {
11685 state.set_value("abcdef", window, cx);
11686 state.set_selected_range(0..3, cx);
11687 let active_id = state.active_selection().id;
11688 for range in additions {
11689 state.add_selection(range, cx);
11690 }
11691 assert_eq!(state.active_selection().id, active_id);
11692 assert_eq!(state.selected_range(), 0..5);
11693 assert_eq!(state.selections.len(), 1);
11694 state.copy(&Copy, window, cx);
11695 assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11696 state.cut(&Cut, window, cx);
11697 assert_eq!(cx.read_from_clipboard().unwrap().text().unwrap(), "abcde");
11698 assert_eq!(state.value(), "f");
11699 state.undo(&Undo, window, cx);
11700 assert_eq!(state.value(), "abcdef");
11701 assert_eq!(state.selected_range(), 0..5);
11702 }
11703 });
11704 });
11705 }
11706
11707 #[gpui::test]
11708 fn test_add_selection_clears_inline_completion(cx: &mut TestAppContext) {
11709 use crate::input::CompletionProvider;
11710 use gpui::Task;
11711 use lsp_types::{
11712 CompletionContext, CompletionResponse, InlineCompletionContext, InlineCompletionItem,
11713 InlineCompletionResponse,
11714 };
11715 use std::time::Duration;
11716
11717 struct Provider(Rc<Cell<usize>>);
11718
11719 impl CompletionProvider for Provider {
11720 fn is_completion_trigger(&self, _: usize, _: &str, _: &mut App) -> bool {
11721 false
11722 }
11723
11724 fn completions(
11725 &self,
11726 _: &Rope,
11727 _: usize,
11728 _: CompletionContext,
11729 _: &mut Window,
11730 _: &mut App,
11731 ) -> Task<anyhow::Result<CompletionResponse>> {
11732 Task::ready(Ok(CompletionResponse::Array(vec![])))
11733 }
11734
11735 fn inline_completion(
11736 &self,
11737 _: &Rope,
11738 _: usize,
11739 _: InlineCompletionContext,
11740 _: &mut Window,
11741 _: &mut App,
11742 ) -> Task<anyhow::Result<InlineCompletionResponse>> {
11743 self.0.set(self.0.get() + 1);
11744 Task::ready(Ok(InlineCompletionResponse::Array(vec![])))
11745 }
11746 }
11747
11748 let view = InputView::<EditorMode>::new(cx);
11749 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11750 let calls = Rc::new(Cell::new(0));
11751 cx.update(|window, cx| {
11752 view.input.update(cx, |state, cx| {
11753 state.focus(window, cx);
11754 state.set_value("aa\naa", window, cx);
11755 state.set_selected_range(2..2, cx);
11756 state.extras.inline_completion.item = Some(InlineCompletionItem {
11757 insert_text: "suggestion".into(),
11758 filter_text: None,
11759 range: None,
11760 command: None,
11761 insert_text_format: None,
11762 });
11763 state.add_selection(5..5, cx);
11764 assert!(!state.has_inline_completion());
11765 state.indent_inline(&IndentInline, window, cx);
11766 assert_eq!(state.value(), "aa \naa ");
11767 assert_eq!(state.selections.len(), 2);
11768
11769 state.set_value("aa\naa", window, cx);
11772 state.set_selected_range(2..2, cx);
11773 state.extras.lsp.completion_provider = Some(Rc::new(Provider(calls.clone())));
11774 state.schedule_inline_completion(window, cx);
11775 });
11776 });
11777 cx.run_until_parked();
11778 cx.update(|_, cx| {
11779 view.input
11780 .update(cx, |state, cx| state.add_selection(5..5, cx));
11781 });
11782 cx.executor().advance_clock(Duration::from_secs(1));
11783 cx.run_until_parked();
11784 assert_eq!(calls.get(), 0);
11785 view.input.read_with(&cx, |state, _| {
11786 assert!(!state.has_inline_completion());
11787 assert_eq!(state.selections.len(), 2);
11788 assert_eq!(state.value(), "aa\naa");
11789 });
11790 }
11791
11792 #[gpui::test]
11793 fn test_word_delete_undo_restores_caret(cx: &mut TestAppContext) {
11794 let view = multi_line(cx);
11795 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11796 setup_cursors(&mut cx, &view.input, "hello|");
11797 cx.update(|window, cx| {
11798 view.input.update(cx, |state, cx| {
11799 state.delete_previous_word(&DeleteToPreviousWordStart, window, cx);
11800 state.undo(&Undo, window, cx);
11801 assert_eq!(state.selected_range(), 5..5);
11802 });
11803 });
11804 }
11805
11806 #[gpui::test]
11807 fn test_merged_delete_undo_restores_all_carets(cx: &mut TestAppContext) {
11808 let view = multi_line(cx);
11809 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11810 setup_cursors(&mut cx, &view.input, "a|b|c");
11811 cx.update(|window, cx| {
11812 view.input.update(cx, |state, cx| {
11813 state.backspace(&Backspace, window, cx);
11814 state.undo(&Undo, window, cx);
11815 });
11816 });
11817 assert_cursors(&mut cx, &view.input, "a|b|c");
11818 }
11819
11820 #[gpui::test]
11821 fn test_shift_end_respects_soft_wrap_end(cx: &mut TestAppContext) {
11822 let view = InputView::<EditorMode>::new(cx);
11823 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11824 cx.update(|window, cx| {
11825 view.input.update(cx, |state, cx| {
11826 state.set_value("abcdef ".repeat(30), window, cx);
11827 state.display_map.on_layout_changed(Some(px(60.)), cx);
11828 let line = state.display_map.line(0).unwrap();
11829 assert!(line.wrapped_lines.len() > 1);
11830 let boundary = line.wrapped_lines[0].end;
11831 state.move_to_with_affinity(boundary, None, true, cx);
11832 state.select_to_end_of_line(&SelectToEndOfLine, window, cx);
11833 assert_eq!(state.selected_range(), boundary..state.text.len());
11834 });
11835 });
11836 }
11837
11838 #[gpui::test]
11839 fn test_outdent_unindented_unicode_is_unchanged(cx: &mut TestAppContext) {
11840 let view = multi_line(cx);
11841 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11842 setup_cursors(&mut cx, &view.input, "|你好\n|世界");
11843 cx.update(|window, cx| {
11844 view.input.update(cx, |state, cx| {
11845 state.outdent(false, window, cx);
11846 state.outdent(true, window, cx);
11847 });
11848 });
11849 assert_cursors(&mut cx, &view.input, "|你好\n|世界");
11850 }
11851
11852 #[gpui::test]
11853 fn test_column_selection_stays_on_unicode_boundaries(cx: &mut TestAppContext) {
11854 let view = multi_line(cx);
11855 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11856 setup_cursors(&mut cx, &view.input, "ab\n你好\ncd");
11857 cx.update(|window, cx| {
11858 view.input.update(cx, |state, cx| {
11859 state.build_columnar_selection(
11860 ColumnarPoint::new(1, 0),
11861 ColumnarPoint::new(11, 0),
11862 cx,
11863 );
11864 let text = state.value();
11865 for sel in state.selections.iter() {
11866 assert!(text.is_char_boundary(sel.start));
11867 assert!(text.is_char_boundary(sel.end));
11868 }
11869 state.replace_text_in_range(None, "X", window, cx);
11870 });
11871 });
11872 }
11873
11874 #[gpui::test]
11875 fn test_cursor_moves_and_deletes_whole_graphemes(cx: &mut TestAppContext) {
11876 let input_view = InputView::build(cx, |state| state);
11877 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
11878 let input = input_view.input;
11879
11880 let graphemes = ["a", "\u{267B}\u{FE0F}", "👍🏽", "👨👩👧", "🇸🇪", "e\u{301}", "b"];
11881 let text = graphemes.concat();
11882 let ends: Vec<usize> = graphemes
11883 .iter()
11884 .scan(0, |end, g| {
11885 *end += g.len();
11886 Some(*end)
11887 })
11888 .collect();
11889
11890 cx.update(|window, cx| {
11891 input.update(cx, |state, cx| {
11892 state.set_value(text.clone(), window, cx);
11893 state.set_selected_range(0..0, cx);
11894 for &end in &ends {
11895 state.right(&MoveRight, window, cx);
11896 assert_eq!(state.cursor(), end);
11897 }
11898 for &end in ends.iter().rev().skip(1).chain([&0]) {
11899 state.left(&MoveLeft, window, cx);
11900 assert_eq!(state.cursor(), end);
11901 }
11902
11903 state.set_selected_range(ends[3]..ends[3], cx);
11904 state.backspace(&Backspace, window, cx);
11905 assert_eq!(
11906 state.value(),
11907 ["a", graphemes[1], graphemes[2]].concat() + &graphemes[4..].concat()
11908 );
11909 state.delete(&Delete, window, cx);
11910 assert_eq!(
11911 state.value(),
11912 ["a", graphemes[1], graphemes[2]].concat() + &graphemes[5..].concat()
11913 );
11914 });
11915 });
11916 }
11917
11918 #[gpui::test]
11919 fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
11920 let view = InputView::<EditorMode>::new(cx);
11921 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11922 cx.update(|window, cx| {
11923 view.input.update(cx, |state, cx| {
11924 state.set_value("abc def", window, cx);
11925 state.create_decorations_collection(
11926 vec![crate::input::TextDecoration::new(
11927 4..7,
11928 gpui::HighlightStyle::default(),
11929 )],
11930 cx,
11931 );
11932 state.set_selected_range(0..0, cx);
11933 state.replace_text_in_range(None, "X", window, cx);
11934 let layers = state.extras.decoration_layers();
11935 assert_eq!(layers.into_iter().flatten().next().unwrap().range, 5..8);
11936 });
11937 });
11938 }
11939
11940 #[gpui::test]
11941 fn test_backspace_preserves_escaped_quote_terminator(cx: &mut TestAppContext) {
11942 let view = InputView::<EditorMode>::new(cx);
11943 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11944 setup_cursors(&mut cx, &view.input, r#"{"s":"\"|"}"#);
11945 cx.update(|window, cx| {
11946 view.input.update(cx, |state, cx| {
11947 set_test_syntax_provider(std::rc::Rc::new(StringAllProvider), cx);
11948 state.backspace(&Backspace, window, cx);
11949 });
11950 });
11951 assert_cursors(&mut cx, &view.input, r#"{"s":"\|"}"#);
11952 }
11953
11954 #[gpui::test]
11955 fn test_ordinary_typing_does_not_query_syntax(cx: &mut TestAppContext) {
11956 struct UnexpectedQuery;
11957 impl crate::input::SyntaxContextProvider for UnexpectedQuery {
11958 fn context_at(&self, _: &ropey::Rope, _: usize) -> crate::input::SyntaxContext {
11959 panic!("ordinary typing must not query syntax");
11960 }
11961 }
11962 let view = InputView::<EditorMode>::new(cx);
11963 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11964 setup_cursors(&mut cx, &view.input, "|");
11965 cx.update(|window, cx| {
11966 view.input.update(cx, |state, cx| {
11967 set_test_syntax_provider(std::rc::Rc::new(UnexpectedQuery), cx);
11968 for c in ["a", "b", "c"] {
11969 state.replace_text_in_range(None, c, window, cx);
11970 }
11971 });
11972 });
11973 assert_cursors(&mut cx, &view.input, "abc|");
11974 }
11975
11976 #[gpui::test]
11977 fn test_auto_close_is_atomic_at_history_limit(cx: &mut TestAppContext) {
11978 let view = InputView::<EditorMode>::new(cx);
11979 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
11980 setup_cursors(&mut cx, &view.input, "|");
11981 cx.update(|window, cx| {
11982 view.input.update(cx, |state, cx| {
11983 for _ in 0..999 {
11984 state.replace_text_in_range(None, "a", window, cx);
11985 }
11986 state.replace_text_in_range(None, "(", window, cx);
11987 state.undo(&Undo, window, cx);
11988 assert!(!state.text.to_string().contains('('));
11989 assert!(!state.text.to_string().contains(')'));
11990 state.redo(&Redo, window, cx);
11991 });
11992 });
11993 assert_cursors(&mut cx, &view.input, &format!("{}(|)", "a".repeat(999)));
11994 }
11995
11996 #[gpui::test]
11997 fn test_comment_closer_is_inserted_literally(cx: &mut TestAppContext) {
11998 let view = InputView::<EditorMode>::new(cx);
11999 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12000 setup_cursors(&mut cx, &view.input, "// (|)");
12001 cx.update(|window, cx| {
12002 view.input.update(cx, |state, cx| {
12003 set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12004 state.replace_text_in_range(None, ")", window, cx);
12005 });
12006 });
12007 assert_cursors(&mut cx, &view.input, "// ()|)");
12008 }
12009
12010 #[gpui::test]
12011 fn test_explicit_range_skip_does_not_delete_existing_closer_on_undo(cx: &mut TestAppContext) {
12012 let view = InputView::<EditorMode>::new(cx);
12013 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12014 setup_cursors(&mut cx, &view.input, "(a|)");
12015 let before = view.input.read_with(&cx, |state, _| state.text.to_string());
12016 cx.update(|window, cx| {
12017 view.input.update(cx, |state, cx| {
12018 state.replace_text_in_range(Some(2..2), ")", window, cx);
12019 });
12020 });
12021 assert_cursors(&mut cx, &view.input, "(a)|");
12022 cx.update(|window, cx| {
12023 view.input
12024 .update(cx, |state, cx| state.undo(&Undo, window, cx));
12025 });
12026 view.input.read_with(&cx, |state, _| {
12027 assert_eq!(
12028 state.text.to_string(),
12029 before,
12030 "skip must not remove an existing closer on undo"
12031 );
12032 });
12033 }
12034
12035 #[gpui::test]
12036 fn test_pair_redo_restores_interior_cursor(cx: &mut TestAppContext) {
12037 let view = InputView::<EditorMode>::new(cx);
12038 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12039 setup_cursors(&mut cx, &view.input, "|");
12040 cx.update(|window, cx| {
12041 view.input.update(cx, |state, cx| {
12042 state.replace_text_in_range(None, "(", window, cx);
12043 });
12044 });
12045 assert_cursors(&mut cx, &view.input, "(|)");
12046 cx.update(|window, cx| {
12047 view.input.update(cx, |state, cx| {
12048 state.undo(&Undo, window, cx);
12049 state.redo(&Redo, window, cx);
12050 });
12051 });
12052 assert_cursors(&mut cx, &view.input, "(|)");
12053 }
12054
12055 #[gpui::test]
12056 fn test_pair_enter_redo_restores_interior_cursor(cx: &mut TestAppContext) {
12057 let view = InputView::<EditorMode>::new(cx);
12058 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12059 setup_cursors(&mut cx, &view.input, "{|}");
12060 cx.update(|window, cx| {
12061 view.input.update(cx, |state, cx| {
12062 state.enter(
12063 &Enter {
12064 secondary: false,
12065 shift: false,
12066 },
12067 window,
12068 cx,
12069 );
12070 });
12071 });
12072 assert_cursors(&mut cx, &view.input, "{\n |\n}");
12073 cx.update(|window, cx| {
12074 view.input.update(cx, |state, cx| {
12075 state.undo(&Undo, window, cx);
12076 });
12077 });
12078 assert_cursors(&mut cx, &view.input, "{|}");
12079 cx.update(|window, cx| {
12080 view.input
12081 .update(cx, |state, cx| state.redo(&Redo, window, cx));
12082 });
12083 assert_cursors(&mut cx, &view.input, "{\n |\n}");
12084 }
12085
12086 #[gpui::test]
12087 fn test_auto_close_parens(cx: &mut TestAppContext) {
12088 let view = InputView::<EditorMode>::new(cx);
12089 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12090 setup_cursors(&mut cx, &view.input, "|");
12091 cx.update(|window, cx| {
12092 view.input.update(cx, |state, cx| {
12093 state.replace_text_in_range(None, "(", window, cx);
12094 });
12095 });
12096 assert_cursors(&mut cx, &view.input, "(|)");
12097 cx.update(|window, cx| {
12099 view.input.update(cx, |state, cx| {
12100 state.replace_text_in_range(None, "x", window, cx);
12101 });
12102 });
12103 assert_cursors(&mut cx, &view.input, "(x|)");
12104 }
12105
12106 #[gpui::test]
12107 fn test_auto_close_skip_over_closer(cx: &mut TestAppContext) {
12108 let view = InputView::<EditorMode>::new(cx);
12109 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12110 setup_cursors(&mut cx, &view.input, "(|)");
12111 cx.update(|window, cx| {
12112 view.input.update(cx, |state, cx| {
12113 state.replace_text_in_range(None, ")", window, cx);
12114 });
12115 });
12116 assert_cursors(&mut cx, &view.input, "()|");
12118 view.input.read_with(&cx, |state, _| {
12120 assert!(state.active_selection().is_empty());
12121 });
12122 }
12123
12124 #[gpui::test]
12125 fn test_auto_close_no_pair_inside_word(cx: &mut TestAppContext) {
12126 let view = InputView::<EditorMode>::new(cx);
12127 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12128 setup_cursors(&mut cx, &view.input, "don|");
12129 cx.update(|window, cx| {
12130 view.input.update(cx, |state, cx| {
12131 state.replace_text_in_range(None, "'", window, cx);
12132 });
12133 });
12134 assert_cursors(&mut cx, &view.input, "don'|");
12136 }
12137
12138 #[gpui::test]
12139 fn test_auto_close_quote_after_cjk(cx: &mut TestAppContext) {
12140 let view = InputView::<EditorMode>::new(cx);
12141 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12142 setup_cursors(&mut cx, &view.input, "中|");
12145 cx.update(|window, cx| {
12146 view.input.update(cx, |state, cx| {
12147 state.replace_text_in_range(None, "'", window, cx);
12148 });
12149 });
12150 assert_cursors(&mut cx, &view.input, "中'|");
12151 }
12152
12153 #[gpui::test]
12154 fn test_auto_close_closer_skips_at_string_end(cx: &mut TestAppContext) {
12155 let view = InputView::<EditorMode>::new(cx);
12156 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12157 setup_cursors(&mut cx, &view.input, "\"hello|\"");
12159 cx.update(|window, cx| {
12160 view.input.update(cx, |state, cx| {
12161 state.replace_text_in_range(None, "\"", window, cx);
12162 });
12163 });
12164 assert_cursors(&mut cx, &view.input, "\"hello\"|");
12165 view.input.read_with(&cx, |state, _| {
12166 assert!(state.active_selection().is_empty());
12167 });
12168 }
12169
12170 #[gpui::test]
12171 fn test_backspace_pair_with_cjk_prefix(cx: &mut TestAppContext) {
12172 let view = InputView::<EditorMode>::new(cx);
12173 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12174 setup_cursors(&mut cx, &view.input, "中(|)abc");
12176 cx.update(|window, cx| {
12177 view.input
12178 .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12179 });
12180 assert_cursors(&mut cx, &view.input, "中|abc");
12181 }
12182
12183 #[gpui::test]
12184 fn test_enter_split_respects_smart_indent_off(cx: &mut TestAppContext) {
12185 let view = InputView::<EditorMode>::new(cx);
12186 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12187 setup_cursors(&mut cx, &view.input, "{|}");
12188 cx.update(|window, cx| {
12189 view.input.update(cx, |state, cx| {
12190 state.set_smart_indent(false, window, cx);
12191 state.enter(
12192 &Enter {
12193 secondary: false,
12194 shift: false,
12195 },
12196 window,
12197 cx,
12198 );
12199 });
12200 });
12201 assert_cursors(&mut cx, &view.input, "{\n|}");
12203 }
12204
12205 #[gpui::test]
12206 fn test_enter_split_is_independent_of_auto_close(cx: &mut TestAppContext) {
12207 let view = InputView::<EditorMode>::new(cx);
12208 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12209 setup_cursors(&mut cx, &view.input, "{|}");
12210 cx.update(|window, cx| {
12211 view.input.update(cx, |state, cx| {
12212 state.set_auto_close(false, window, cx);
12213 state.enter(
12214 &Enter {
12215 secondary: false,
12216 shift: false,
12217 },
12218 window,
12219 cx,
12220 );
12221 });
12222 });
12223 assert_cursors(&mut cx, &view.input, "{\n |\n}");
12225 }
12226
12227 #[gpui::test]
12228 fn test_language_config_applies_before_render_and_on_language_change(cx: &mut TestAppContext) {
12229 use crate::input::{AutoClosingPair, set_language_config};
12230 let view = InputView::<EditorMode>::new(cx);
12231 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12232 cx.update(|window, cx| {
12233 set_language_config(
12234 "alpha",
12235 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
12236 cx,
12237 );
12238 set_language_config(
12239 "beta",
12240 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("‹", "›")]),
12241 cx,
12242 );
12243 let first = cx.new(|cx| EditorState::new(window, cx).language("ALPHA"));
12244 let second = cx.new(|cx| EditorState::new(window, cx).language("beta"));
12245 first.update(cx, |state, cx| {
12246 state.replace_text_in_range(None, "«", window, cx);
12247 assert_eq!(state.text().to_string(), "«»");
12248 state.set_value("", window, cx);
12249 state.set_smart_indent(false, window, cx);
12250 state.set_highlighter("beta", cx);
12251 assert!(!state.mode.is_smart_indent());
12252 state.replace_text_in_range(None, "‹", window, cx);
12253 assert_eq!(state.text().to_string(), "‹›");
12254 state.set_value("", window, cx);
12255 state.set_highlighter("unknown", cx);
12256 state.replace_text_in_range(None, "(", window, cx);
12257 assert_eq!(state.text().to_string(), "()");
12258 });
12259 second.update(cx, |state, cx| {
12260 state.replace_text_in_range(None, "‹", window, cx);
12261 assert_eq!(state.text().to_string(), "‹›");
12262 });
12263 });
12264 }
12265
12266 #[gpui::test]
12267 fn test_language_service_replacement_updates_syntax_without_render(cx: &mut TestAppContext) {
12268 use crate::input::{LanguageProvider, SyntaxContextProvider, set_language_provider};
12269 struct StringLanguages(Rc<Cell<usize>>);
12270 impl LanguageProvider for StringLanguages {
12271 fn syntax_context_provider(&self, _: &str) -> Option<Rc<dyn SyntaxContextProvider>> {
12272 self.0.set(self.0.get() + 1);
12273 Some(Rc::new(StringAllProvider))
12274 }
12275 }
12276 struct CodeLanguages;
12277 impl LanguageProvider for CodeLanguages {}
12278 let view = InputView::<EditorMode>::new(cx);
12279 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12280 cx.update(|window, cx| {
12281 let creations = Rc::new(Cell::new(0));
12282 set_language_provider(Rc::new(StringLanguages(creations.clone())), cx);
12283 view.input.update(cx, |state, cx| {
12284 state.replace_text_in_range(None, "(", window, cx);
12285 state.replace_text_in_range(None, "[", window, cx);
12286 assert_eq!(state.text().to_string(), "([");
12287 assert_eq!(
12288 creations.get(),
12289 1,
12290 "retain the document provider between edits"
12291 );
12292 });
12293 set_language_provider(Rc::new(CodeLanguages), cx);
12294 view.input.update(cx, |state, cx| {
12295 state.replace_text_in_range(None, "{", window, cx);
12296 assert_eq!(state.text().to_string(), "([{}");
12297 });
12298 });
12299 }
12300
12301 #[gpui::test]
12302 fn test_language_config_updates_existing_editors(cx: &mut TestAppContext) {
12303 use crate::input::{AutoClosingPair, set_language_config};
12304 let view = InputView::<EditorMode>::new(cx);
12305 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12306 setup_cursors(&mut cx, &view.input, "|");
12307 cx.update(|window, cx| {
12308 view.input.update(cx, |state, cx| {
12309 state.set_highlighter("CUSTOM", cx);
12310 state.set_auto_close(false, window, cx);
12311 state.set_smart_indent(false, window, cx);
12312 });
12313 set_language_config(
12314 "custom",
12315 LanguageConfig::default().auto_closing_pairs([AutoClosingPair::new("«", "»")]),
12316 cx,
12317 );
12318 set_language_config("other", LanguageConfig::default(), cx);
12320 view.input.update(cx, |state, cx| {
12321 assert!(!state.mode.is_auto_close());
12322 assert!(!state.mode.is_smart_indent());
12323 state.set_auto_close(true, window, cx);
12324 state.replace_text_in_range(None, "«", window, cx);
12325 });
12326 });
12327 assert_cursors(&mut cx, &view.input, "«|»");
12328 }
12329
12330 #[gpui::test]
12331 fn test_auto_close_before_is_language_configurable(cx: &mut TestAppContext) {
12332 let view = InputView::<EditorMode>::new(cx);
12333 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12334 setup_cursors(&mut cx, &view.input, "|word");
12335 cx.update(|window, cx| {
12336 view.input.update(cx, |state, cx| {
12337 state.replace_text_in_range(None, "(", window, cx)
12338 });
12339 });
12340 assert_cursors(&mut cx, &view.input, "(|word");
12341 setup_cursors(&mut cx, &view.input, "|word");
12342 cx.update(|window, cx| {
12343 view.input.update(cx, |state, cx| {
12344 crate::input::set_language_config(
12345 state.language_name(),
12346 LanguageConfig::default().auto_close_before("w"),
12347 cx,
12348 );
12349 state.replace_text_in_range(None, "(", window, cx);
12350 });
12351 });
12352 assert_cursors(&mut cx, &view.input, "(|)word");
12353 }
12354
12355 #[gpui::test]
12356 fn test_pair_context_restrictions_are_per_pair(cx: &mut TestAppContext) {
12357 use crate::input::{AutoClosingPair, SyntaxContext};
12358 let view = InputView::<EditorMode>::new(cx);
12359 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12360 setup_cursors(&mut cx, &view.input, "|");
12361 cx.update(|window, cx| {
12362 view.input.update(cx, |state, cx| {
12363 set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12364 crate::input::set_language_config(
12365 state.language_name(),
12366 LanguageConfig::default().auto_closing_pairs([
12367 AutoClosingPair::new("(", ")").not_in([SyntaxContext::String]),
12368 AutoClosingPair::new("[", "]").not_in([SyntaxContext::Comment]),
12369 ]),
12370 cx,
12371 );
12372 state.replace_text_in_range(None, "(", window, cx);
12373 state.replace_text_in_range(None, "[", window, cx);
12374 });
12375 });
12376 assert_cursors(&mut cx, &view.input, "([|)");
12377 }
12378
12379 #[gpui::test]
12380 fn test_multichar_delimiters_insert_delete_and_skip(cx: &mut TestAppContext) {
12381 use crate::input::{AutoClosingPair, SyntaxContext};
12382 struct BlockComment;
12383 impl crate::input::SyntaxContextProvider for BlockComment {
12384 fn context_at(&self, text: &ropey::Rope, _: usize) -> SyntaxContext {
12385 if text.to_string().contains("/*") {
12386 SyntaxContext::Comment
12387 } else {
12388 SyntaxContext::Code
12389 }
12390 }
12391 }
12392 let view = InputView::<EditorMode>::new(cx);
12393 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12394 setup_cursors(&mut cx, &view.input, "|");
12395 cx.update(|window, cx| {
12396 view.input.update(cx, |state, cx| {
12397 set_test_syntax_provider(std::rc::Rc::new(BlockComment), cx);
12398 crate::input::set_language_config(
12399 state.language_name(),
12400 LanguageConfig::default()
12401 .auto_closing_pairs([AutoClosingPair::new("/*", "*/")
12402 .not_in([SyntaxContext::String, SyntaxContext::Comment])]),
12403 cx,
12404 );
12405 state.replace_text_in_range(None, "/", window, cx);
12406 state.replace_text_in_range(None, "*", window, cx);
12407 });
12408 });
12409 assert_cursors(&mut cx, &view.input, "/*|*/");
12410 cx.update(|window, cx| {
12411 view.input
12412 .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12413 });
12414 assert_cursors(&mut cx, &view.input, "|");
12415 cx.update(|window, cx| {
12416 view.input.update(cx, |state, cx| {
12417 state.undo(&Undo, window, cx);
12418 state.replace_text_in_range(None, "*", window, cx);
12419 state.replace_text_in_range(None, "/", window, cx);
12420 });
12421 });
12422 assert_cursors(&mut cx, &view.input, "/**/|");
12423 }
12424
12425 #[gpui::test]
12426 fn test_auto_closed_pairs_fallback_and_explicit_disable(cx: &mut TestAppContext) {
12427 use crate::input::BracketPair;
12428 let view = InputView::<EditorMode>::new(cx);
12429 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12430 setup_cursors(&mut cx, &view.input, "|");
12431 cx.update(|window, cx| {
12432 view.input.update(cx, |state, cx| {
12433 let mut rules = LanguageConfig::default().brackets([BracketPair::new("«", "»")]);
12434 rules.auto_closing_pairs = None;
12435 crate::input::set_language_config(state.language_name(), rules.clone(), cx);
12436 state.replace_text_in_range(None, "«", window, cx);
12437 crate::input::set_language_config(
12438 state.language_name(),
12439 rules.auto_closing_pairs([]),
12440 cx,
12441 );
12442 state.replace_text_in_range(None, "«", window, cx);
12443 });
12444 });
12445 assert_cursors(&mut cx, &view.input, "««|»");
12446 }
12447
12448 #[gpui::test]
12449 fn test_undo_open_composition_preserves_generated_pairs(cx: &mut TestAppContext) {
12450 use crate::input::{AutoClosingPair, SyntaxContext};
12451 let view = InputView::<EditorMode>::new(cx);
12452 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12453 setup_cursors(&mut cx, &view.input, "|");
12454 cx.update(|window, cx| {
12455 view.input.update(cx, |state, cx| {
12456 crate::input::set_language_config(
12457 state.language_name(),
12458 LanguageConfig::default()
12459 .auto_closing_pairs([
12460 AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12461 ]),
12462 cx,
12463 );
12464 state.replace_text_in_range(None, "/", window, cx);
12465 state.replace_text_in_range(None, "*", window, cx);
12466 set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12467 state.replace_and_mark_text_in_range(None, "x", Some(1..1), window, cx);
12468 state.undo(&Undo, window, cx);
12469 state.replace_text_in_range(None, "*", window, cx);
12470 state.replace_text_in_range(None, "/", window, cx);
12471 });
12472 });
12473 assert_cursors(&mut cx, &view.input, "/**/|");
12474 }
12475
12476 #[gpui::test]
12477 fn test_undo_does_not_promote_literal_comment_delimiters(cx: &mut TestAppContext) {
12478 use crate::input::{AutoClosingPair, SyntaxContext};
12479 let view = InputView::<EditorMode>::new(cx);
12480 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12481 setup_cursors(&mut cx, &view.input, "/*|*/");
12482 cx.update(|window, cx| {
12483 view.input.update(cx, |state, cx| {
12484 set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12485 crate::input::set_language_config(
12486 state.language_name(),
12487 LanguageConfig::default()
12488 .auto_closing_pairs([
12489 AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12490 ]),
12491 cx,
12492 );
12493 state.delete_to_end_of_line(&DeleteToEndOfLine, window, cx);
12494 state.undo(&Undo, window, cx);
12495 state.backspace(&Backspace, window, cx);
12496 });
12497 });
12498 assert_cursors(&mut cx, &view.input, "/|*/");
12499 }
12500
12501 #[gpui::test]
12502 fn test_multiple_generated_pairs_retain_their_identity(cx: &mut TestAppContext) {
12503 use crate::input::{AutoClosingPair, SyntaxContext};
12504 struct CommentScope;
12505 impl crate::input::SyntaxContextProvider for CommentScope {
12506 fn context_at(&self, text: &ropey::Rope, offset: usize) -> SyntaxContext {
12507 if text
12508 .to_string()
12509 .find("*/")
12510 .is_some_and(|end| offset < end + 2)
12511 {
12512 SyntaxContext::Comment
12513 } else {
12514 SyntaxContext::Code
12515 }
12516 }
12517 }
12518 let view = InputView::<EditorMode>::new(cx);
12519 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12520 setup_cursors(&mut cx, &view.input, "|");
12521 cx.update(|window, cx| {
12522 view.input.update(cx, |state, cx| {
12523 set_test_syntax_provider(std::rc::Rc::new(CommentScope), cx);
12524 crate::input::set_language_config(
12525 state.language_name(),
12526 LanguageConfig::default().auto_closing_pairs([
12527 AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment]),
12528 AutoClosingPair::new("(", ")").not_in([SyntaxContext::Comment]),
12529 ]),
12530 cx,
12531 );
12532 state.replace_text_in_range(None, "/", window, cx);
12533 state.replace_text_in_range(None, "*", window, cx);
12534 state.set_selected_range(4..4, cx);
12535 state.replace_text_in_range(None, "(", window, cx);
12536 state.set_selected_range(2..2, cx);
12537 state.replace_text_in_range(None, "*", window, cx);
12538 state.replace_text_in_range(None, "/", window, cx);
12539 });
12540 });
12541 assert_cursors(&mut cx, &view.input, "/**/|()");
12542 cx.update(|window, cx| {
12543 view.input.update(cx, |state, cx| {
12544 state.set_selected_range(2..2, cx);
12545 state.backspace(&Backspace, window, cx);
12546 state.undo(&Undo, window, cx);
12547 state.redo(&Redo, window, cx);
12548 });
12549 });
12550 assert_cursors(&mut cx, &view.input, "|()");
12551 }
12552
12553 #[gpui::test]
12554 fn test_replacing_generated_opener_invalidates_the_pair(cx: &mut TestAppContext) {
12555 use crate::input::{AutoClosingPair, SyntaxContext};
12556 let view = InputView::<EditorMode>::new(cx);
12557 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12558 setup_cursors(&mut cx, &view.input, "|");
12559 cx.update(|window, cx| {
12560 view.input.update(cx, |state, cx| {
12561 crate::input::set_language_config(
12562 state.language_name(),
12563 LanguageConfig::default()
12564 .auto_closing_pairs([
12565 AutoClosingPair::new("/*", "*/").not_in([SyntaxContext::Comment])
12566 ]),
12567 cx,
12568 );
12569 state.replace_text_in_range(None, "/", window, cx);
12570 state.replace_text_in_range(None, "*", window, cx);
12571 state.replace_text_in_range(Some(0..2), "//", window, cx);
12572 set_test_syntax_provider(std::rc::Rc::new(CommentAllProvider), cx);
12573 state.replace_text_in_range(None, "*", window, cx);
12574 });
12575 });
12576 assert_cursors(&mut cx, &view.input, "//*|*/");
12577 }
12578
12579 #[gpui::test]
12580 fn test_configuration_preserves_compiled_regex_options(cx: &mut TestAppContext) {
12581 use crate::input::IndentationRules;
12582 let view = InputView::<EditorMode>::new(cx);
12583 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12584 setup_cursors(&mut cx, &view.input, "BEGIN|");
12585 cx.update(|window, cx| {
12586 view.input.update(cx, |state, cx| {
12587 let rules = |insensitive| {
12588 LanguageConfig::default().indentation_rules(IndentationRules::new(
12589 regex::RegexBuilder::new("begin$")
12590 .case_insensitive(insensitive)
12591 .build()
12592 .unwrap(),
12593 regex::Regex::new("^end").unwrap(),
12594 ))
12595 };
12596 crate::input::set_language_config(state.language_name(), rules(false), cx);
12597 crate::input::set_language_config(state.language_name(), rules(true), cx);
12598 state.enter(
12599 &Enter {
12600 secondary: false,
12601 shift: false,
12602 },
12603 window,
12604 cx,
12605 );
12606 });
12607 });
12608 assert_cursors(&mut cx, &view.input, "BEGIN\n |");
12609 }
12610
12611 #[gpui::test]
12612 fn test_indent_patterns_are_applied_on_enter(cx: &mut TestAppContext) {
12613 use crate::input::IndentationRules;
12614 let view = InputView::<EditorMode>::new(cx);
12615 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12616 let rules = LanguageConfig::default().indentation_rules(IndentationRules::new(
12617 regex::Regex::new(r"\bbegin\s*$").unwrap(),
12618 regex::Regex::new(r"^\s*end\b").unwrap(),
12619 ));
12620 for (before, expected) in [("begin|", "begin\n |"), (" |end", " \n|end")] {
12621 setup_cursors(&mut cx, &view.input, before);
12622 cx.update(|window, cx| {
12623 view.input.update(cx, |state, cx| {
12624 crate::input::set_language_config(state.language_name(), rules.clone(), cx);
12625 state.enter(
12626 &Enter {
12627 secondary: false,
12628 shift: false,
12629 },
12630 window,
12631 cx,
12632 );
12633 });
12634 });
12635 assert_cursors(&mut cx, &view.input, expected);
12636 }
12637 }
12638
12639 #[gpui::test]
12640 fn test_custom_language_config(cx: &mut TestAppContext) {
12641 let view = InputView::<EditorMode>::new(cx);
12642 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12643 cx.update(|_window, cx| {
12644 view.input.update(cx, |state, cx| {
12645 crate::input::set_language_config(
12646 state.language_name(),
12647 crate::input::language_config::LanguageConfig::default()
12648 .brackets([crate::input::BracketPair::new("«", "»")])
12649 .auto_closing_pairs([crate::input::AutoClosingPair::new("«", "»")]),
12650 cx,
12651 );
12652 });
12653 });
12654 setup_cursors(&mut cx, &view.input, "|");
12656 cx.update(|window, cx| {
12657 view.input.update(cx, |state, cx| {
12658 state.replace_text_in_range(None, "«", window, cx);
12659 });
12660 });
12661 assert_cursors(&mut cx, &view.input, "«|»");
12662 cx.update(|window, cx| {
12664 view.input.update(cx, |state, cx| {
12665 state.set_value("\n", window, cx);
12666 state.set_selected_range(0..0, cx);
12667 state.replace_text_in_range(None, "(", window, cx);
12668 });
12669 });
12670 assert_cursors(&mut cx, &view.input, "(|");
12671 }
12672
12673 #[gpui::test]
12674 fn test_skip_records_no_history(cx: &mut TestAppContext) {
12675 let view = InputView::<EditorMode>::new(cx);
12676 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12677 setup_cursors(&mut cx, &view.input, "(a|)");
12678 cx.update(|window, cx| {
12679 view.input.update(cx, |state, cx| {
12680 state.replace_text_in_range(None, "b", window, cx);
12682 });
12683 });
12684 assert_cursors(&mut cx, &view.input, "(ab|)");
12685 cx.update(|window, cx| {
12686 view.input.update(cx, |state, cx| {
12687 state.replace_text_in_range(None, ")", window, cx);
12688 });
12689 });
12690 assert_cursors(&mut cx, &view.input, "(ab)|");
12692 cx.update(|window, cx| {
12694 view.input
12695 .update(cx, |state, cx| state.undo(&Undo, window, cx));
12696 });
12697 assert_cursors(&mut cx, &view.input, "(a|)");
12698 }
12699
12700 #[gpui::test]
12701 fn test_pair_insert_undo_removes_both(cx: &mut TestAppContext) {
12702 let view = InputView::<EditorMode>::new(cx);
12703 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12704 setup_cursors(&mut cx, &view.input, "|");
12705 cx.update(|window, cx| {
12706 view.input.update(cx, |state, cx| {
12707 state.replace_text_in_range(None, "(", window, cx);
12708 });
12709 });
12710 assert_cursors(&mut cx, &view.input, "(|)");
12711 cx.update(|window, cx| {
12713 view.input
12714 .update(cx, |state, cx| state.undo(&Undo, window, cx));
12715 });
12716 assert_cursors(&mut cx, &view.input, "|");
12717 }
12718
12719 #[gpui::test]
12720 fn test_escaped_quote_does_not_skip(cx: &mut TestAppContext) {
12721 let view = InputView::<EditorMode>::new(cx);
12722 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12723 setup_cursors(&mut cx, &view.input, "\"hello\\|\"");
12725 cx.update(|window, cx| {
12726 view.input.update(cx, |state, cx| {
12727 state.replace_text_in_range(None, "\"", window, cx);
12728 });
12729 });
12730 assert_cursors(&mut cx, &view.input, "\"hello\\\"|\"");
12731 }
12732
12733 #[gpui::test]
12734 fn test_even_backslashes_still_skip(cx: &mut TestAppContext) {
12735 let view = InputView::<EditorMode>::new(cx);
12736 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12737 setup_cursors(&mut cx, &view.input, "\"hello\\\\|\"");
12739 cx.update(|window, cx| {
12740 view.input.update(cx, |state, cx| {
12741 state.replace_text_in_range(None, "\"", window, cx);
12742 });
12743 });
12744 assert_cursors(&mut cx, &view.input, "\"hello\\\\\"|");
12745 }
12746
12747 #[gpui::test]
12748 fn test_editor_options_survive_configuration_replacement(cx: &mut TestAppContext) {
12749 use crate::input::{BracketPair, LanguageConfig};
12750
12751 let view = InputView::<EditorMode>::new(cx);
12752 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12753 cx.update(|window, cx| {
12754 view.input.update(cx, |state, cx| {
12755 state.set_smart_indent(false, window, cx);
12757 crate::input::set_language_config(
12758 state.language_name(),
12759 LanguageConfig::default().brackets([BracketPair::new("«", "»")]),
12760 cx,
12761 );
12762 });
12763 });
12764 view.input.read_with(&cx, |state, _| {
12765 assert!(!state.mode.is_smart_indent(), "editor option preserved");
12766 assert!(state.mode.is_auto_close());
12767 let pairs = &state.mode.language_config().unwrap().brackets;
12768 assert_eq!(pairs.len(), 1, "pairs follow configuration");
12769 assert_eq!(pairs[0].open.as_ref(), "«");
12770 });
12771 }
12772
12773 struct CommentAllProvider;
12774 impl crate::input::SyntaxContextProvider for CommentAllProvider {
12775 fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12776 crate::input::SyntaxContext::Comment
12777 }
12778 }
12779
12780 struct StringAllProvider;
12781 impl crate::input::SyntaxContextProvider for StringAllProvider {
12782 fn context_at(&self, _text: &ropey::Rope, _offset: usize) -> crate::input::SyntaxContext {
12783 crate::input::SyntaxContext::String
12784 }
12785 }
12786
12787 #[gpui::test]
12788 fn test_smart_indent_suppressed_in_strings(cx: &mut TestAppContext) {
12789 use std::rc::Rc;
12790
12791 let view = InputView::<EditorMode>::new(cx);
12792 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12793 cx.update(|_window, cx| {
12794 set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12795 });
12796 setup_cursors(&mut cx, &view.input, " x = {|");
12798 cx.update(|window, cx| {
12799 view.input.update(cx, |state, cx| {
12800 state.enter(
12801 &Enter {
12802 secondary: false,
12803 shift: false,
12804 },
12805 window,
12806 cx,
12807 );
12808 });
12809 });
12810 assert_cursors(&mut cx, &view.input, " x = {\n |");
12811 }
12812
12813 #[gpui::test]
12814 fn test_split_suppressed_in_strings(cx: &mut TestAppContext) {
12815 use std::rc::Rc;
12816
12817 let view = InputView::<EditorMode>::new(cx);
12818 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12819 cx.update(|_window, cx| {
12820 set_test_syntax_provider(Rc::new(StringAllProvider), cx);
12821 });
12822 setup_cursors(&mut cx, &view.input, "{|}");
12824 cx.update(|window, cx| {
12825 view.input.update(cx, |state, cx| {
12826 state.enter(
12827 &Enter {
12828 secondary: false,
12829 shift: false,
12830 },
12831 window,
12832 cx,
12833 );
12834 });
12835 });
12836 assert_cursors(&mut cx, &view.input, "{\n|}");
12837 }
12838
12839 #[gpui::test]
12840 fn test_comment_context_disables_pairing(cx: &mut TestAppContext) {
12841 use std::rc::Rc;
12842
12843 let view = InputView::<EditorMode>::new(cx);
12844 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12845 cx.update(|_window, cx| {
12846 set_test_syntax_provider(Rc::new(CommentAllProvider), cx);
12847 });
12848 setup_cursors(&mut cx, &view.input, "|");
12849 cx.update(|window, cx| {
12850 view.input.update(cx, |state, cx| {
12851 state.replace_text_in_range(None, "(", window, cx);
12852 });
12853 });
12854 assert_cursors(&mut cx, &view.input, "(|");
12856 }
12857
12858 #[gpui::test]
12859 fn test_backspace_deletes_empty_pair(cx: &mut TestAppContext) {
12860 let view = InputView::<EditorMode>::new(cx);
12861 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12862 setup_cursors(&mut cx, &view.input, "{|}");
12863 cx.update(|window, cx| {
12864 view.input
12865 .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12866 });
12867 assert_cursors(&mut cx, &view.input, "|");
12868 }
12869
12870 #[gpui::test]
12871 fn test_backspace_keeps_closer_with_content(cx: &mut TestAppContext) {
12872 let view = InputView::<EditorMode>::new(cx);
12873 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12874 setup_cursors(&mut cx, &view.input, "{d|}");
12875 cx.update(|window, cx| {
12876 view.input
12877 .update(cx, |state, cx| state.backspace(&Backspace, window, cx));
12878 });
12879 assert_cursors(&mut cx, &view.input, "{|}");
12881 }
12882
12883 #[gpui::test]
12884 fn test_enter_splits_brackets(cx: &mut TestAppContext) {
12885 let view = InputView::<EditorMode>::new(cx);
12886 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12887 setup_cursors(&mut cx, &view.input, "{|}");
12888 cx.update(|window, cx| {
12889 view.input.update(cx, |state, cx| {
12890 state.enter(
12891 &Enter {
12892 secondary: false,
12893 shift: false,
12894 },
12895 window,
12896 cx,
12897 );
12898 });
12899 });
12900 assert_cursors(&mut cx, &view.input, "{\n |\n}");
12901 view.input.read_with(&cx, |state, _| {
12903 assert!(state.active_selection().is_empty());
12904 });
12905 cx.update(|window, cx| {
12906 view.input.update(cx, |state, cx| {
12907 state.replace_text_in_range(None, "x", window, cx);
12908 });
12909 });
12910 assert_cursors(&mut cx, &view.input, "{\n x|\n}");
12911 }
12912
12913 #[gpui::test]
12914 fn test_enter_smart_indent_after_brace(cx: &mut TestAppContext) {
12915 let view = InputView::<EditorMode>::new(cx);
12916 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12917 setup_cursors(&mut cx, &view.input, "fn main() {|");
12918 cx.update(|window, cx| {
12919 view.input.update(cx, |state, cx| {
12920 state.enter(
12921 &Enter {
12922 secondary: false,
12923 shift: false,
12924 },
12925 window,
12926 cx,
12927 );
12928 });
12929 });
12930 assert_cursors(&mut cx, &view.input, "fn main() {\n |");
12931 }
12932
12933 #[gpui::test]
12934 fn test_block_indent_tracks_all_preceding_edits(cx: &mut TestAppContext) {
12935 let view = multi_line(cx);
12936 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12937 setup_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12938 cx.update(|window, cx| {
12939 view.input
12940 .update(cx, |state, cx| state.indent(true, window, cx));
12941 });
12942 assert_cursors(&mut cx, &view.input, " |ab\n |cd\n |ef");
12943 cx.update(|window, cx| {
12944 view.input
12945 .update(cx, |state, cx| state.outdent(true, window, cx));
12946 });
12947 assert_cursors(&mut cx, &view.input, "|ab\n|cd\n|ef");
12948 }
12949
12950 #[gpui::test]
12951 fn test_block_outdent_clamps_cursor_inside_indent(cx: &mut TestAppContext) {
12952 let view = multi_line(cx);
12953 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12954 setup_cursors(&mut cx, &view.input, "ab\n | cd");
12955 cx.update(|window, cx| {
12956 view.input
12957 .update(cx, |state, cx| state.outdent(true, window, cx));
12958 });
12959 assert_cursors(&mut cx, &view.input, "ab\n|cd");
12960 }
12961
12962 #[gpui::test]
12963 fn test_ime_restores_original_selection(cx: &mut TestAppContext) {
12964 let view = InputView::build(cx, |state| state);
12965 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12966 cx.update(|window, cx| {
12967 view.input.update(cx, |state, cx| {
12968 state.set_value("abc", window, cx);
12969 state.set_selected_range(1..2, cx);
12970 state.replace_and_mark_text_in_range(None, "ni", None, window, cx);
12971 state.replace_text_in_range(None, "你", window, cx);
12972 state.undo(&Undo, window, cx);
12973 assert_eq!(state.value(), "abc");
12974 assert_eq!(state.selected_range(), 1..2);
12975 state.redo(&Redo, window, cx);
12976 assert_eq!(state.selected_range(), 4..4);
12977 });
12978 });
12979 }
12980
12981 #[gpui::test]
12982 fn test_noop_does_not_change_redo_selection(cx: &mut TestAppContext) {
12983 let view = multi_line(cx);
12984 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
12985 cx.update(|window, cx| {
12986 view.input.update(cx, |state, cx| {
12987 state.set_value("abc", window, cx);
12988 state.set_selected_range(1..1, cx);
12989 state.replace_text_in_range(None, "X", window, cx);
12990 state.set_selected_range(0..0, cx);
12991 state.replace_text_in_range(None, "", window, cx);
12992 state.undo(&Undo, window, cx);
12993 state.redo(&Redo, window, cx);
12994 assert_eq!(state.value(), "aXbc");
12995 assert_eq!(state.selected_range(), 2..2);
12996 });
12997 });
12998 }
12999
13000 #[gpui::test]
13001 fn test_multi_cursor_insert_text(cx: &mut TestAppContext) {
13002 let view = multi_line(cx);
13003 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13004 let input = view.input;
13005
13006 setup_cursors(&mut cx, &input, "|hello |world|");
13007 cx.update(|window, cx| {
13008 input.update(cx, |state, cx| {
13009 state.replace_text_in_range(None, ">>>", window, cx);
13010 });
13011 });
13012 assert_cursors(&mut cx, &input, ">>>|hello >>>|world>>>|");
13013 }
13014
13015 #[gpui::test]
13016 fn test_multi_cursor_delete_backward(cx: &mut TestAppContext) {
13017 let view = multi_line(cx);
13018 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13019 let input = view.input;
13020
13021 setup_cursors(&mut cx, &input, "|islands| cars|");
13022 cx.update(|window, cx| {
13023 input.update(cx, |state, cx| {
13024 state.backspace(&Backspace, window, cx);
13025 });
13026 });
13027 assert_cursors(&mut cx, &input, "|island| car|");
13029 }
13030
13031 #[gpui::test]
13032 fn test_multi_cursor_delete_forward_merges(cx: &mut TestAppContext) {
13033 let view = multi_line(cx);
13034 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13035 let input = view.input;
13036
13037 setup_cursors(&mut cx, &input, "hello| |world");
13038 cx.update(|window, cx| {
13039 input.update(cx, |state, cx| {
13040 state.delete(&Delete, window, cx);
13041 });
13042 });
13043 assert_cursors(&mut cx, &input, "hello|orld");
13045 }
13046
13047 #[gpui::test]
13048 fn test_multi_cursor_multiline_insert_and_delete(cx: &mut TestAppContext) {
13049 let view = multi_line(cx);
13050 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13051 let input = view.input;
13052
13053 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13054 cx.update(|window, cx| {
13055 input.update(cx, |state, cx| {
13056 state.replace_text_in_range(None, "a", window, cx);
13057 });
13058 });
13059 assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
13060
13061 input.read_with(&cx, |state, _| {
13063 assert_eq!(state.undo_manager.undo_count(), 1);
13064 });
13065
13066 cx.update(|window, cx| {
13067 input.update(cx, |state, cx| {
13068 state.backspace(&Backspace, window, cx);
13069 });
13070 });
13071 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13072 }
13073
13074 #[gpui::test]
13075 fn test_add_cursor_below_preserves_column(cx: &mut TestAppContext) {
13076 let view = multi_line(cx);
13077 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13078 let input = view.input;
13079
13080 setup_cursors(&mut cx, &input, "ab|cd\nabcd");
13081 cx.update(|window, cx| {
13082 input.update(cx, |state, cx| {
13083 state.add_cursor_below(&AddCursorBelow, window, cx);
13084 });
13085 });
13086 assert_cursors(&mut cx, &input, "ab|cd\nab|cd");
13087 }
13088
13089 #[gpui::test]
13090 fn test_add_cursor_at_rejects_duplicates(cx: &mut TestAppContext) {
13091 let view = multi_line(cx);
13092 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13093 let input = view.input;
13094
13095 setup_cursors(&mut cx, &input, "he|llo");
13096 cx.update(|_, cx| {
13097 input.update(cx, |state, cx| {
13098 state.add_cursor_at(2, cx);
13100 assert_eq!(state.selections.len(), 1);
13101 state.add_cursor_at(4, cx);
13103 assert_eq!(state.selections.len(), 2);
13104 });
13105 });
13106 }
13107
13108 #[gpui::test]
13109 fn test_multi_cursor_undo_redo_restores_selections(cx: &mut TestAppContext) {
13110 let view = multi_line(cx);
13111 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13112 let input = view.input;
13113
13114 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13115 cx.update(|window, cx| {
13116 input.update(cx, |state, cx| {
13117 state.replace_text_in_range(None, "a", window, cx);
13118 });
13119 });
13120 assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
13121
13122 cx.update(|window, cx| {
13123 input.update(cx, |state, cx| {
13124 state.undo(&Undo, window, cx);
13125 });
13126 });
13127 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13128
13129 cx.update(|window, cx| {
13130 input.update(cx, |state, cx| {
13131 state.redo(&Redo, window, cx);
13132 });
13133 });
13134 assert_cursors(&mut cx, &input, "a|1\na|2\na|3");
13135 }
13136
13137 #[gpui::test]
13138 fn test_multi_cursor_undo_redo_different_line_lengths(cx: &mut TestAppContext) {
13139 let view = multi_line(cx);
13140 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13141 let input = view.input;
13142
13143 setup_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
13144 cx.update(|window, cx| {
13145 input.update(cx, |state, cx| {
13146 state.replace_text_in_range(None, "a", window, cx);
13147 });
13148 });
13149 assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
13150
13151 cx.update(|window, cx| {
13152 input.update(cx, |state, cx| {
13153 state.undo(&Undo, window, cx);
13154 });
13155 });
13156 assert_cursors(&mut cx, &input, "abc123|\nabc12345|\nabc1234567|");
13157
13158 cx.update(|window, cx| {
13159 input.update(cx, |state, cx| {
13160 state.redo(&Redo, window, cx);
13161 });
13162 });
13163 assert_cursors(&mut cx, &input, "abc123a|\nabc12345a|\nabc1234567a|");
13164 }
13165
13166 #[gpui::test]
13167 fn test_multi_cursor_undo_multiple_inserts(cx: &mut TestAppContext) {
13168 let view = multi_line(cx);
13169 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13170 let input = view.input;
13171
13172 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13173 for ch in ['a', 'b', 'c'] {
13174 cx.update(|window, cx| {
13175 input.update(cx, |state, cx| {
13176 state.replace_text_in_range(None, &ch.to_string(), window, cx);
13177 });
13178 });
13179 }
13180 assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
13181
13182 cx.update(|window, cx| {
13184 input.update(cx, |state, cx| {
13185 assert_eq!(state.undo_manager.undo_count(), 1);
13186 state.undo(&Undo, window, cx);
13187 });
13188 });
13189 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13190
13191 cx.update(|window, cx| {
13192 input.update(cx, |state, cx| {
13193 state.redo(&Redo, window, cx);
13194 });
13195 });
13196 assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
13197 }
13198
13199 #[gpui::test]
13200 fn test_multi_cursor_backspace_run_is_one_undo(cx: &mut TestAppContext) {
13201 let view = multi_line(cx);
13202 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13203 let input = view.input;
13204
13205 setup_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
13206 for _ in 0..3 {
13207 cx.update(|window, cx| {
13208 input.update(cx, |state, cx| {
13209 state.backspace(&Backspace, window, cx);
13210 });
13211 });
13212 }
13213 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13214
13215 cx.update(|window, cx| {
13216 input.update(cx, |state, cx| {
13217 assert_eq!(state.undo_manager.undo_count(), 1);
13218 state.undo(&Undo, window, cx);
13219 });
13220 });
13221 assert_cursors(&mut cx, &input, "abc|1\nabc|2\nabc|3");
13222 }
13223
13224 #[gpui::test]
13225 fn test_adding_a_cursor_splits_the_typing_gesture(cx: &mut TestAppContext) {
13226 let view = multi_line(cx);
13227 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13228 let input = view.input;
13229
13230 setup_cursors(&mut cx, &input, "|1\n2\n3");
13231 cx.update(|window, cx| {
13232 input.update(cx, |state, cx| {
13233 state.replace_text_in_range(None, "a", window, cx);
13234 state.add_cursor_below(&AddCursorBelow, window, cx);
13235 state.replace_text_in_range(None, "b", window, cx);
13236 });
13237 });
13238 assert_cursors(&mut cx, &input, "ab|1\n2b|\n3");
13239
13240 cx.update(|window, cx| {
13242 input.update(cx, |state, cx| {
13243 state.undo(&Undo, window, cx);
13244 });
13245 });
13246 assert_cursors(&mut cx, &input, "a|1\n2|\n3");
13247 }
13248
13249 #[gpui::test]
13250 fn test_multi_cursor_indent_is_one_undo(cx: &mut TestAppContext) {
13251 let view = multi_line(cx);
13252 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13253 let input = view.input;
13254
13255 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13256 cx.update(|window, cx| {
13257 input.update(cx, |state, cx| {
13258 state.indent_inline(&IndentInline, window, cx);
13259 assert_eq!(state.undo_manager.undo_count(), 1);
13260 state.undo(&Undo, window, cx);
13261 });
13262 });
13263 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13264 }
13265
13266 #[gpui::test]
13267 fn test_multi_cursor_indent_then_outdent_roundtrips(cx: &mut TestAppContext) {
13268 let view = multi_line(cx);
13269 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13270 let input = view.input;
13271
13272 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13274 cx.update(|window, cx| {
13275 input.update(cx, |state, cx| {
13276 state.indent(false, window, cx);
13277 });
13278 });
13279 assert_cursors(&mut cx, &input, " |1\n |2\n |3");
13280
13281 cx.update(|window, cx| {
13282 input.update(cx, |state, cx| {
13283 state.outdent(false, window, cx);
13284 });
13285 });
13286 assert_cursors(&mut cx, &input, "|1\n|2\n|3");
13287 }
13288
13289 #[gpui::test]
13290 fn test_inline_outdent_only_removes_line_indentation(cx: &mut TestAppContext) {
13291 let view = multi_line(cx);
13292 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13293 let input = view.input;
13294
13295 setup_cursors(&mut cx, &input, "1|2\n1|2");
13298 cx.update(|window, cx| {
13299 input.update(cx, |state, cx| {
13300 state.indent(false, window, cx);
13301 });
13302 });
13303 assert_cursors(&mut cx, &input, "1 |2\n1 |2");
13304
13305 cx.update(|window, cx| {
13306 input.update(cx, |state, cx| {
13307 state.outdent(false, window, cx);
13308 });
13309 });
13310 assert_cursors(&mut cx, &input, "1 |2\n1 |2");
13311
13312 setup_cursors(&mut cx, &input, " 1|2\n 1|2");
13314 cx.update(|window, cx| {
13315 input.update(cx, |state, cx| {
13316 state.outdent(false, window, cx);
13317 });
13318 });
13319 assert_cursors(&mut cx, &input, "1|2\n1|2");
13320 }
13321
13322 #[gpui::test]
13323 fn test_readonly_multi_cursor_commands_leave_state_unchanged(cx: &mut TestAppContext) {
13324 let view = multi_line(cx);
13325 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13326 let input = view.input;
13327
13328 setup_cursors(&mut cx, &input, "a|b\nc|d");
13329 cx.update(|window, cx| {
13330 input.update(cx, |state, cx| {
13331 let before: Vec<_> = state.selections.iter().copied().collect();
13332 state.set_readonly(true, cx);
13333 state.backspace(&Backspace, window, cx);
13334 state.indent_inline(&IndentInline, window, cx);
13335
13336 assert_eq!(state.value(), "ab\ncd\n");
13337 assert_eq!(state.selections.iter().copied().collect::<Vec<_>>(), before);
13338 });
13339 });
13340 }
13341
13342 #[gpui::test]
13343 fn test_multi_cursor_edit_preserves_the_active_cursor(cx: &mut TestAppContext) {
13344 let view = multi_line(cx);
13345 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13346 let input = view.input;
13347
13348 setup_cursors(&mut cx, &input, "x|\n|y");
13349 cx.update(|window, cx| {
13350 input.update(cx, |state, cx| {
13351 let mut selections: Vec<_> = state.selections.iter().copied().collect();
13352 selections.swap(0, 1);
13353 state.selections.replace_all(selections);
13354 let active_id = state.active_selection().id;
13355 state.replace_text_in_range(None, "!", window, cx);
13356 assert_eq!(state.active_selection().id, active_id);
13357 });
13358 });
13359 }
13360
13361 #[gpui::test]
13362 fn test_block_indent_outdent_with_selection(cx: &mut TestAppContext) {
13363 let view = multi_line(cx);
13364 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13365 let input = view.input;
13366
13367 cx.update(|window, cx| {
13368 input.update(cx, |state, cx| {
13369 state.set_value("line1\nline2\nline3", window, cx);
13370 let id = state.selections.generate_id();
13371 state
13372 .selections
13373 .replace_all(vec![CursorSelection::new(id, 0, 17)]);
13374 cx.notify();
13375 });
13376 });
13377
13378 cx.update(|window, cx| {
13379 input.update(cx, |state, cx| {
13380 state.indent(true, window, cx);
13381 });
13382 });
13383 input.read_with(&cx, |state, _| {
13384 assert_eq!(state.text.to_string(), " line1\n line2\n line3");
13385 });
13386
13387 cx.update(|window, cx| {
13388 input.update(cx, |state, cx| {
13389 state.outdent(true, window, cx);
13390 });
13391 });
13392 input.read_with(&cx, |state, _| {
13393 assert_eq!(state.text.to_string(), "line1\nline2\nline3");
13394 });
13395 }
13396
13397 #[gpui::test]
13398 fn test_multi_cursor_word_movement(cx: &mut TestAppContext) {
13399 let view = multi_line(cx);
13400 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13401 let input = view.input;
13402
13403 setup_cursors(
13404 &mut cx,
13405 &input,
13406 "on|e two three\none t|wo three\non|e two three",
13407 );
13408
13409 cx.update(|window, cx| {
13410 input.update(cx, |state, cx| {
13411 state.move_to_next_word(&MoveToNextWord, window, cx);
13412 });
13413 });
13414 assert_cursors(
13415 &mut cx,
13416 &input,
13417 "one| two three\none two| three\none| two three",
13418 );
13419
13420 cx.update(|window, cx| {
13421 input.update(cx, |state, cx| {
13422 state.move_to_previous_word(&MoveToPreviousWord, window, cx);
13423 });
13424 });
13425 assert_cursors(
13426 &mut cx,
13427 &input,
13428 "|one two three\none |two three\n|one two three",
13429 );
13430
13431 cx.update(|window, cx| {
13433 input.update(cx, |state, cx| {
13434 state.move_to_end(&MoveToEnd, window, cx);
13435 });
13436 });
13437 input.read_with(&cx, |state, _| {
13438 let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13439 assert_eq!(cursors, vec![state.text.len()]);
13440 });
13441
13442 cx.update(|window, cx| {
13443 input.update(cx, |state, cx| {
13444 state.move_to_start(&MoveToStart, window, cx);
13445 });
13446 });
13447 input.read_with(&cx, |state, _| {
13448 let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13449 assert_eq!(cursors, vec![0]);
13450 });
13451 }
13452
13453 #[gpui::test]
13454 fn test_rtl_arrow_keys_move_visually(cx: &mut TestAppContext) {
13455 let view = multi_line(cx);
13456 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13457 let input = view.input;
13458 let text = "مرحبا عالم";
13460 let place = |cx: &mut VisualTestContext, offset: usize| {
13461 cx.update(|window, cx| {
13462 input.update(cx, |state, cx| {
13463 state.set_value(text, window, cx);
13464 let id = state.selections.generate_id();
13465 state
13466 .selections
13467 .replace_all(vec![CursorSelection::new(id, offset, offset)]);
13468 });
13469 });
13470 };
13471 let selection = |cx: &mut VisualTestContext| {
13472 input.read_with(cx, |state, _| {
13473 let sel = state.active_selection();
13474 (sel.start, sel.end, sel.cursor_offset())
13475 })
13476 };
13477
13478 cx.update(|_, cx| crate::LayoutDirection::Rtl.set_global(cx));
13479
13480 place(&mut cx, 4);
13482 cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
13483 assert_eq!(selection(&mut cx).2, 2);
13484 cx.update(|window, cx| input.update(cx, |s, cx| s.left(&MoveLeft, window, cx)));
13485 assert_eq!(selection(&mut cx).2, 4);
13486
13487 cx.update(|window, cx| input.update(cx, |s, cx| s.select_right(&SelectRight, window, cx)));
13489 assert_eq!(selection(&mut cx), (2, 4, 2));
13490 place(&mut cx, 4);
13491 cx.update(|window, cx| input.update(cx, |s, cx| s.select_left(&SelectLeft, window, cx)));
13492 assert_eq!(selection(&mut cx), (4, 6, 6));
13493
13494 let second_word = text.find('ع').unwrap();
13496 place(&mut cx, text.len());
13497 cx.update(|window, cx| {
13498 input.update(cx, |s, cx| s.move_to_next_word(&MoveToNextWord, window, cx))
13499 });
13500 assert_eq!(selection(&mut cx).2, second_word);
13501 place(&mut cx, 0);
13502 cx.update(|window, cx| {
13503 input.update(cx, |s, cx| {
13504 s.move_to_previous_word(&MoveToPreviousWord, window, cx)
13505 })
13506 });
13507 assert_eq!(selection(&mut cx).2, text.find(' ').unwrap());
13508
13509 cx.update(|_, cx| crate::LayoutDirection::Ltr.set_global(cx));
13511 place(&mut cx, 4);
13512 cx.update(|window, cx| input.update(cx, |s, cx| s.right(&MoveRight, window, cx)));
13513 assert_eq!(selection(&mut cx).2, 6);
13514 }
13515
13516 #[gpui::test]
13517 fn test_multi_cursor_selection_commands(cx: &mut TestAppContext) {
13518 let view = multi_line(cx);
13519 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13520 let input = view.input;
13521
13522 setup_cursors(
13523 &mut cx,
13524 &input,
13525 "on|e two three\none t|wo three\non|e two three",
13526 );
13527 cx.update(|window, cx| {
13528 input.update(cx, |state, cx| {
13529 state.select_to_start_of_line(&SelectToStartOfLine, window, cx);
13530 });
13531 });
13532 assert_cursors(
13533 &mut cx,
13534 &input,
13535 "|one two three\n|one two three\n|one two three",
13536 );
13537
13538 setup_cursors(
13540 &mut cx,
13541 &input,
13542 "on|e two three\none t|wo three\non|e two three",
13543 );
13544 cx.update(|window, cx| {
13545 input.update(cx, |state, cx| {
13546 state.select_to_start(&SelectToStart, window, cx);
13547 });
13548 });
13549 input.read_with(&cx, |state, _| {
13550 let cursors: Vec<usize> = state.selections.iter().map(|s| s.cursor_offset()).collect();
13551 assert_eq!(cursors, vec![0]);
13552 });
13553 }
13554
13555 #[gpui::test]
13556 fn test_multi_cursor_replace_selection(cx: &mut TestAppContext) {
13557 let view = multi_line(cx);
13558 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13559 let input = view.input;
13560
13561 setup_cursors(&mut cx, &input, "|a\n|b\n|c");
13562 cx.update(|window, cx| {
13563 input.update(cx, |state, cx| {
13564 state.select_right(&SelectRight, window, cx);
13565 });
13566 });
13567 input.read_with(&cx, |state, _| {
13568 let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13569 assert_eq!(ranges, vec![(0, 1), (2, 3), (4, 5)]);
13570 });
13571
13572 cx.update(|window, cx| {
13573 input.update(cx, |state, cx| {
13574 state.replace_text_in_range(None, "x", window, cx);
13575 });
13576 });
13577 assert_cursors(&mut cx, &input, "x|\nx|\nx|");
13578 }
13579
13580 #[gpui::test]
13581 fn test_multi_cursor_escape_collapses(cx: &mut TestAppContext) {
13582 let view = multi_line(cx);
13583 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13584 let input = view.input;
13585
13586 setup_cursors(&mut cx, &input, "|a\n|b\n|c");
13587 cx.update(|window, cx| {
13588 input.update(cx, |state, cx| {
13589 state.escape(&Escape, window, cx);
13590 });
13591 });
13592 input.read_with(&cx, |state, _| {
13593 assert_eq!(state.selections.len(), 1);
13594 });
13595 }
13596
13597 #[gpui::test]
13598 fn test_build_columnar_selection(cx: &mut TestAppContext) {
13599 let view = multi_line(cx);
13600 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13601 let input = view.input;
13602
13603 setup_cursors(&mut cx, &input, "abcd\nabcd\nabcd");
13604 cx.update(|_, cx| {
13605 input.update(cx, |state, cx| {
13606 state.build_columnar_selection(
13608 ColumnarPoint::new(1, 0),
13609 ColumnarPoint::new(13, 0),
13610 cx,
13611 );
13612 let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13613 assert_eq!(ranges, vec![(1, 3), (6, 8), (11, 13)]);
13614 });
13615 });
13616 }
13617
13618 #[gpui::test]
13619 fn test_columnar_selection_keeps_width_over_short_rows(cx: &mut TestAppContext) {
13620 let view = multi_line(cx);
13621 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13622 let input = view.input;
13623
13624 setup_cursors(&mut cx, &input, "abcdef\nab\nabcdef");
13625 cx.update(|_, cx| {
13626 input.update(cx, |state, cx| {
13627 state.build_columnar_selection(
13630 ColumnarPoint::new(1, 0),
13631 ColumnarPoint::new(9, 3),
13632 cx,
13633 );
13634 let ranges: Vec<_> = state.selections.iter().map(|s| (s.start, s.end)).collect();
13635 assert_eq!(ranges, vec![(1, 5), (8, 9)]);
13636 });
13637 });
13638 }
13639
13640 #[gpui::test]
13641 fn test_multi_cursor_paste_distributes_lines(cx: &mut TestAppContext) {
13642 let view = multi_line(cx);
13643 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13644 let input = view.input;
13645
13646 setup_cursors(&mut cx, &input, "|1\n|2\n|3");
13647 cx.update(|_, cx| {
13648 cx.write_to_clipboard(ClipboardItem::new_string("x\ny\nz".to_string()));
13649 });
13650 cx.update(|window, cx| {
13651 input.update(cx, |state, cx| {
13652 state.paste(&Paste, window, cx);
13653 });
13654 });
13655 assert_cursors(&mut cx, &input, "x|1\ny|2\nz|3");
13657 }
13658
13659 #[gpui::test]
13660 fn test_paste_without_text_leaves_the_selection_alone(cx: &mut TestAppContext) {
13661 use gpui::{ClipboardEntry, Image, ImageFormat};
13662
13663 let input_view = InputView::build(cx, |state| state);
13664 let mut cx = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13665 let input = input_view.input;
13666
13667 cx.update(|window, cx| {
13668 input.update(cx, |state, cx| {
13669 state.set_value("hello world", window, cx);
13670 state.select_all(window, cx);
13671 cx.write_to_clipboard(ClipboardItem {
13672 entries: vec![ClipboardEntry::Image(Image::from_bytes(
13673 ImageFormat::Png,
13674 vec![0x89, b'P', b'N', b'G'],
13675 ))],
13676 });
13677
13678 state.paste(&Paste, window, cx);
13681 assert_eq!(state.value(), "hello world");
13682 assert_eq!(state.selected_range(), 0..11);
13683 });
13684 });
13685 }
13686
13687 #[gpui::test]
13688 fn test_paste_target_tracks_edits_and_selections(cx: &mut TestAppContext) {
13689 let view = multi_line(cx);
13690 let mut cx = VisualTestContext::from_window(view.window_handle.into(), cx);
13691 let input = view.input;
13692
13693 setup_cursors(&mut cx, &input, "ab|c");
13694 let target = input.read_with(&cx, |state, _| state.paste_target());
13695 assert_eq!(
13697 input.read_with(&cx, |state, _| state.paste_target()),
13698 target
13699 );
13700
13701 cx.update(|_, cx| {
13703 input.update(cx, |state, cx| {
13704 let id = state.selections.generate_id();
13705 state
13706 .selections
13707 .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13708 cx.notify();
13709 });
13710 });
13711 let moved = input.read_with(&cx, |state, _| state.paste_target());
13712 assert_ne!(moved, target);
13713
13714 cx.update(|window, cx| {
13716 input.update(cx, |state, cx| {
13717 state.replace_text_in_range_silent(None, "x", window, cx);
13718 let id = state.selections.generate_id();
13719 state
13720 .selections
13721 .replace_all(vec![CursorSelection::new(id, 1, 1)]);
13722 });
13723 });
13724 assert_ne!(input.read_with(&cx, |state, _| state.paste_target()), moved);
13725 }
13726
13727 #[gpui::test]
13728 fn character_index_for_point_finds_each_letter_where_it_is_drawn(cx: &mut TestAppContext) {
13729 for line_number in [true, false] {
13731 let input_view = InputView::build_editor(cx, move |state| {
13732 state
13733 .line_number(line_number)
13734 .default_value("Teh quick\nbrown fox\njumps")
13735 });
13736 let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13737 visual.update(|window, cx| window.draw(cx).clear(cx));
13738
13739 visual.update(|window, cx| {
13740 input_view.input.update(cx, |state, cx| {
13741 let bounds = state.text_bounds().unwrap();
13742 for index in [0, 5, 8, 10, 14, 18, 20, 24] {
13743 let middle = state
13744 .bounds_for_range(index..index + 1, bounds, window, cx)
13745 .unwrap()
13746 .center();
13747 assert_eq!(
13748 state.character_index_for_point(middle, window, cx),
13749 Some(index),
13750 "line numbers: {line_number}"
13751 );
13752 }
13753 });
13754 });
13755 }
13756 }
13757
13758 #[gpui::test]
13759 fn test_ime_candidate_bounds_fallback_before_repaint(cx: &mut TestAppContext) {
13760 let input_view = InputView::build_textarea(cx, |state| {
13761 state.default_value("这是一段已经输入的中文文字")
13762 });
13763 let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13764 visual.update(|window, cx| window.draw(cx).clear(cx));
13765
13766 visual.update(|window, cx| {
13767 input_view.input.update(cx, |state, cx| {
13768 state.focus(window, cx);
13769 let len = state.text.len();
13770 state.set_cursor_to(len);
13771 });
13772 });
13773 visual.update(|window, cx| window.draw(cx).clear(cx));
13774
13775 visual.update(|window, cx| {
13776 input_view.input.update(cx, |state, cx| {
13777 let bounds = state.text_bounds().unwrap_or_default();
13778 let before = state.selected_text_range(false, window, cx).unwrap().range;
13779 let previous = state
13780 .bounds_for_range(before.end..before.end, bounds, window, cx)
13781 .unwrap();
13782
13783 state.replace_and_mark_text_in_range(None, "n", None, window, cx);
13784
13785 let after = state.selected_text_range(false, window, cx).unwrap().range;
13786 let pending = state
13787 .bounds_for_range(after.end..after.end, bounds, window, cx)
13788 .unwrap();
13789
13790 assert!(
13791 (pending.origin.x - previous.origin.x).abs() < px(40.0),
13792 "pending origin.x {:?} must remain close to previous origin.x {:?}",
13793 pending.origin.x,
13794 previous.origin.x
13795 );
13796
13797 let range_bounds = state
13798 .bounds_for_range(before.end..after.end, bounds, window, cx)
13799 .unwrap();
13800 assert!(
13801 (range_bounds.origin.x - previous.origin.x).abs() < px(40.0),
13802 "range_bounds origin.x {:?} must remain close to previous origin.x {:?}",
13803 range_bounds.origin.x,
13804 previous.origin.x
13805 );
13806 assert!(range_bounds.size.width >= px(0.0));
13807 });
13808 });
13809 }
13810
13811 #[gpui::test]
13812 fn test_ime_candidate_bounds_multiline_line_end(cx: &mut TestAppContext) {
13813 let input_view =
13814 InputView::build_textarea(cx, |state| state.default_value("First line\nSecond line"));
13815 let mut visual = VisualTestContext::from_window(input_view.window_handle.into(), cx);
13816 visual.update(|window, cx| window.draw(cx).clear(cx));
13817
13818 visual.update(|window, cx| {
13819 input_view.input.update(cx, |state, cx| {
13820 state.focus(window, cx);
13821 state.set_cursor_to(10);
13823 });
13824 });
13825 visual.update(|window, cx| window.draw(cx).clear(cx));
13826
13827 visual.update(|window, cx| {
13828 input_view.input.update(cx, |state, cx| {
13829 let bounds = state.text_bounds().unwrap_or_default();
13830 let candidate_bounds = state.bounds_for_range(10..10, bounds, window, cx).unwrap();
13831
13832 let line_number_width = state
13835 .last_layout
13836 .as_ref()
13837 .map(|l| l.line_number_width)
13838 .unwrap_or_default();
13839 assert!(
13840 candidate_bounds.origin.x > bounds.origin.x + line_number_width,
13841 "candidate bounds at line end must be past the line start, got {:?}",
13842 candidate_bounds.origin.x
13843 );
13844
13845 let (line_idx, sub_line, pos) = state.line_and_position_for_offset(10);
13846 assert_eq!(line_idx, 0);
13847 assert_eq!(sub_line, 0);
13848 assert!(pos.is_some());
13849 assert!(pos.unwrap().x > line_number_width);
13850 });
13851 });
13852 }
13853}
13854
13855impl InputBaseState<crate::input::InputMode> {
13857 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
13859 Self::new_in_mode(window, cx)
13860 }
13861
13862 pub fn step_by(mut self, f: impl Fn(f64, StepAction, &mut App) -> f64 + 'static) -> Self {
13877 self.number_step = Some(NumberStep::by_value(f));
13878 self
13879 }
13880
13881 pub fn masked(mut self, masked: bool) -> Self {
13883 self.masked = masked;
13884 self
13885 }
13886
13887 pub fn set_masked(&mut self, masked: bool, _: &mut Window, cx: &mut Context<Self>) {
13889 self.masked = masked;
13890 cx.notify();
13891 }
13892
13893 pub fn pattern(mut self, pattern: regex::Regex) -> Self {
13895 self.pattern = Some(pattern);
13896 self
13897 }
13898
13899 pub fn set_pattern(
13901 &mut self,
13902 pattern: regex::Regex,
13903 _window: &mut Window,
13904 _cx: &mut Context<Self>,
13905 ) {
13906 self.pattern = Some(pattern);
13907 }
13908
13909 pub fn validate(mut self, f: impl Fn(&str, &mut App) -> bool + 'static) -> Self {
13911 self.validate = Some(Box::new(f));
13912 self
13913 }
13914
13915 pub fn set_validator(
13916 &mut self,
13917 validate: impl Fn(&str, &mut App) -> bool + 'static,
13918 _cx: &mut Context<Self>,
13919 ) {
13920 self.validate = Some(Box::new(validate));
13921 }
13922
13923 pub fn step(mut self, step: impl Into<NumberStep>) -> Self {
13933 self.number_step = Some(step.into());
13934 self
13935 }
13936
13937 pub fn min(mut self, min: f64) -> Self {
13943 self.number_min = Some(min);
13944 self
13945 }
13946
13947 pub fn max(mut self, max: f64) -> Self {
13953 self.number_max = Some(max);
13954 self
13955 }
13956
13957 pub fn set_step(
13962 &mut self,
13963 step: impl Into<Option<NumberStep>>,
13964 _: &mut Window,
13965 _: &mut Context<Self>,
13966 ) {
13967 self.number_step = step.into();
13968 }
13969
13970 pub fn set_min(&mut self, min: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13972 self.number_min = min;
13973 }
13974
13975 pub fn set_max(&mut self, max: Option<f64>, _: &mut Window, _: &mut Context<Self>) {
13977 self.number_max = max;
13978 }
13979
13980 pub fn set_loading(&mut self, loading: bool, _: &mut Window, cx: &mut Context<Self>) {
13982 self.loading = loading;
13983 cx.notify();
13984 }
13985}
13986
13987impl<M: crate::input::MultiLineMode> InputBaseState<M> {
13990 pub fn scroll_bounce(mut self, scroll_bounce: bool) -> Self {
13998 self.scroll_bounce = scroll_bounce;
13999 self
14000 }
14001
14002 pub fn set_scroll_bounce(&mut self, scroll_bounce: bool, cx: &mut Context<Self>) {
14006 if self.scroll_bounce != scroll_bounce {
14007 self.scroll_bounce = scroll_bounce;
14008 self.overscroll.reset();
14009 cx.notify();
14010 }
14011 }
14012
14013 pub fn searchable(mut self, searchable: bool) -> Self {
14021 self.searchable = searchable;
14022 self
14023 }
14024
14025 pub fn set_searchable(&mut self, searchable: bool, cx: &mut Context<Self>) {
14027 self.searchable = searchable;
14028 cx.notify();
14029 }
14030
14031 pub fn scrollbar_placement(mut self, placement: ScrollbarPlacement) -> Self {
14038 self.scrollbar_placement = placement;
14039 self
14040 }
14041
14042 pub fn set_scrollbar_placement(
14044 &mut self,
14045 placement: ScrollbarPlacement,
14046 cx: &mut Context<Self>,
14047 ) {
14048 self.scrollbar_placement = placement;
14049 cx.notify();
14050 }
14051
14052 pub fn gutter_side(mut self, side: Side) -> Self {
14062 self.gutter_side = side;
14063 self
14064 }
14065
14066 pub fn set_gutter_side(&mut self, side: Side, cx: &mut Context<Self>) {
14068 self.gutter_side = side;
14069 cx.notify();
14070 }
14071
14072 pub fn gutter_order(mut self, columns: impl IntoIterator<Item = GutterColumn>) -> Self {
14079 self.gutter_order = GutterColumn::order(columns);
14080 self
14081 }
14082
14083 pub fn set_gutter_order(
14085 &mut self,
14086 columns: impl IntoIterator<Item = GutterColumn>,
14087 cx: &mut Context<Self>,
14088 ) {
14089 self.gutter_order = GutterColumn::order(columns);
14090 cx.notify();
14091 }
14092
14093 #[doc(hidden)]
14095 pub fn soft_wrap(mut self, wrap: bool) -> Self {
14096 self.soft_wrap = wrap;
14097 self
14098 }
14099
14100 pub fn set_soft_wrap(&mut self, wrap: bool, _: &mut Window, cx: &mut Context<Self>) {
14102 self.soft_wrap = wrap;
14103 if wrap {
14104 let wrap_width = self
14105 .last_layout
14106 .as_ref()
14107 .and_then(|b| b.wrap_width)
14108 .unwrap_or(self.input_bounds.size.width);
14109
14110 self.display_map.on_layout_changed(Some(wrap_width), cx);
14111
14112 let mut offset = self.scroll_handle.offset();
14114 offset.x = px(0.);
14115 self.scroll_handle.set_offset(offset);
14116 } else {
14117 self.display_map.on_layout_changed(None, cx);
14118 }
14119 cx.notify();
14120 }
14121
14122 #[doc(hidden)]
14124 pub fn wrapping_indent(mut self, wrapping_indent: WrappingIndent) -> Self {
14125 self.wrapping_indent = wrapping_indent;
14126 self
14127 }
14128
14129 pub fn set_wrapping_indent(
14131 &mut self,
14132 wrapping_indent: WrappingIndent,
14133 _: &mut Window,
14134 cx: &mut Context<Self>,
14135 ) {
14136 self.wrapping_indent = wrapping_indent;
14137 self.display_map.set_wrapping_indent(wrapping_indent, cx);
14138 cx.notify();
14139 }
14140}
14141
14142impl InputBaseState<crate::input::TextareaMode> {
14144 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
14149 Self::new_in_mode(window, cx)
14150 }
14151
14152 pub fn set_auto_grow(&mut self, min_rows: usize, max_rows: usize, cx: &mut Context<Self>) {
14153 self.mode = LayoutMode::auto_grow(min_rows, max_rows.max(min_rows));
14154 self.mode.update_auto_grow(&self.display_map);
14155 cx.notify();
14156 }
14157
14158 #[doc(hidden)]
14165 pub fn rows(mut self, rows: usize) -> Self {
14166 match &mut self.mode {
14167 LayoutMode::PlainText { rows: r, .. } | LayoutMode::CodeEditor { rows: r, .. } => {
14168 *r = rows
14169 }
14170 LayoutMode::AutoGrow {
14171 max_rows: max_r,
14172 rows: r,
14173 ..
14174 } => {
14175 *r = rows;
14176 *max_r = rows;
14177 }
14178 }
14179 self
14180 }
14181
14182 pub fn set_rows(&mut self, rows: usize, cx: &mut Context<Self>) {
14183 match &mut self.mode {
14184 LayoutMode::PlainText { rows: value, .. }
14185 | LayoutMode::CodeEditor { rows: value, .. } => *value = rows,
14186 LayoutMode::AutoGrow {
14187 rows: value,
14188 max_rows,
14189 ..
14190 } => {
14191 *value = rows;
14192 *max_rows = rows;
14193 }
14194 }
14195 cx.notify();
14196 }
14197
14198 pub fn auto_grow(mut self, min_rows: usize, max_rows: usize) -> Self {
14200 self.mode = LayoutMode::auto_grow(min_rows, max_rows);
14201 self
14202 }
14203}
14204
14205impl InputBaseState<crate::input::EditorMode> {
14207 pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
14218 let mut state = Self::new_in_mode(window, cx);
14219 state.mode = LayoutMode::code_editor(super::EditorLanguage::new(cx));
14220 state.searchable = true;
14221 state
14222 }
14223
14224 pub fn language(mut self, language: impl Into<SharedString>) -> Self {
14228 if let LayoutMode::CodeEditor {
14229 language: l,
14230 highlighter,
14231 ..
14232 } = &mut self.mode
14233 {
14234 l.set_name(language.into());
14235 *highlighter.borrow_mut() = None;
14236 }
14237 self
14238 }
14239
14240 pub fn language_name(&self) -> SharedString {
14242 match &self.mode {
14243 LayoutMode::CodeEditor { language, .. } => language.name(),
14244 _ => SharedString::default(),
14245 }
14246 }
14247
14248 #[doc(hidden)]
14252 pub fn folding(mut self, folding: bool) -> Self {
14253 if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
14254 *f = folding;
14255 }
14256 self
14257 }
14258
14259 pub fn set_folding(&mut self, folding: bool, _: &mut Window, cx: &mut Context<Self>) {
14263 if let LayoutMode::CodeEditor { folding: f, .. } = &mut self.mode {
14264 *f = folding;
14265 }
14266 if !folding {
14267 self.display_map.clear_folds();
14268 }
14269 cx.notify();
14270 }
14271
14272 pub fn set_folded(&mut self, start_line: usize, folded: bool, cx: &mut Context<Self>) -> bool {
14276 if !self.mode.is_folding() || !self.display_map.is_fold_candidate(start_line) {
14277 return false;
14278 }
14279 self.display_map.set_folded(start_line, folded);
14280 cx.notify();
14281 true
14282 }
14283
14284 pub fn fold_all(&mut self, cx: &mut Context<Self>) {
14286 if !self.mode.is_folding() {
14287 return;
14288 }
14289 let lines: Vec<usize> = self
14290 .display_map
14291 .fold_candidates()
14292 .iter()
14293 .map(|c| c.start_line)
14294 .collect();
14295 self.display_map.set_folded_lines(lines);
14296 cx.notify();
14297 }
14298
14299 pub fn unfold_all(&mut self, cx: &mut Context<Self>) {
14301 if !self.mode.is_folding() {
14302 return;
14303 }
14304 self.display_map.clear_folds();
14305 cx.notify();
14306 }
14307
14308 pub fn fold_at_level(&mut self, level: usize, cx: &mut Context<Self>) {
14312 if !self.mode.is_folding() {
14313 return;
14314 }
14315 let mut open: Vec<usize> = Vec::new();
14319 let mut lines = Vec::new();
14320 for c in self.display_map.fold_candidates() {
14321 while open.last().is_some_and(|&end| end < c.end_line) {
14322 open.pop();
14323 }
14324 if open.len() + 1 == level {
14325 lines.push(c.start_line);
14326 }
14327 open.push(c.end_line);
14328 }
14329 self.display_map.set_folded_lines(lines);
14330 cx.notify();
14331 }
14332
14333 pub fn fold_candidates(&self) -> &[crate::input::FoldRange] {
14335 self.display_map.fold_candidates()
14336 }
14337
14338 pub fn unfold_at(&mut self, position: impl Into<Position>, cx: &mut Context<Self>) -> bool {
14351 let offset = self.text.position_to_offset(&position.into());
14352 let line = self.text.offset_to_point(offset).row;
14353 let covering: Vec<usize> = self
14356 .display_map
14357 .folded_ranges()
14358 .iter()
14359 .filter(|fold| line > fold.start_line && line < fold.end_line)
14360 .map(|fold| fold.start_line)
14361 .collect();
14362 if covering.is_empty() {
14363 return false;
14364 }
14365
14366 for start_line in covering {
14367 self.display_map.set_folded(start_line, false);
14368 }
14369 cx.notify();
14370 true
14371 }
14372
14373 pub fn text_origin_offset(&self) -> Option<Pixels> {
14386 self.last_layout.as_ref().map(|layout| layout.text_origin_x)
14387 }
14388
14389 #[doc(hidden)]
14391 pub fn line_number(mut self, line_number: bool) -> Self {
14392 if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
14393 *l = line_number;
14394 }
14395 self
14396 }
14397
14398 pub fn set_line_number(&mut self, line_number: bool, _: &mut Window, cx: &mut Context<Self>) {
14400 if let LayoutMode::CodeEditor { line_number: l, .. } = &mut self.mode {
14401 if *l == line_number {
14402 return;
14403 }
14404 *l = line_number;
14405 }
14406 cx.notify();
14407 }
14408
14409 #[doc(hidden)]
14413 pub fn active_line_only_when_focused(mut self, active_line_only_when_focused: bool) -> Self {
14414 if let LayoutMode::CodeEditor {
14415 active_line_only_when_focused: a,
14416 ..
14417 } = &mut self.mode
14418 {
14419 *a = active_line_only_when_focused;
14420 }
14421 self
14422 }
14423
14424 pub fn set_active_line_only_when_focused(
14426 &mut self,
14427 active_line_only_when_focused: bool,
14428 _: &mut Window,
14429 cx: &mut Context<Self>,
14430 ) {
14431 if let LayoutMode::CodeEditor {
14432 active_line_only_when_focused: a,
14433 ..
14434 } = &mut self.mode
14435 {
14436 if *a == active_line_only_when_focused {
14437 return;
14438 }
14439 *a = active_line_only_when_focused;
14440 }
14441 cx.notify();
14442 }
14443
14444 #[doc(hidden)]
14450 pub fn auto_close(mut self, auto_close: bool) -> Self {
14451 self.mode.set_auto_close(auto_close);
14452 self
14453 }
14454
14455 pub fn set_auto_close(&mut self, auto_close: bool, _: &mut Window, cx: &mut Context<Self>) {
14457 self.mode.set_auto_close(auto_close);
14458 cx.notify();
14459 }
14460
14461 #[doc(hidden)]
14467 pub fn smart_indent(mut self, smart_indent: bool) -> Self {
14468 self.mode.set_smart_indent(smart_indent);
14469 self
14470 }
14471
14472 pub fn set_smart_indent(&mut self, smart_indent: bool, _: &mut Window, cx: &mut Context<Self>) {
14474 self.mode.set_smart_indent(smart_indent);
14475 cx.notify();
14476 }
14477}