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