1use std::sync::Arc;
2
3use collections::HashMap;
4use editor::{
5 Bias, DisplayPoint, Editor, SelectionEffects,
6 display_map::{DisplaySnapshot, ToDisplayPoint},
7 movement,
8};
9use gpui::{Context, Window, actions};
10use language::{Point, Selection, SelectionGoal};
11use multi_buffer::MultiBufferRow;
12use search::BufferSearchBar;
13use util::ResultExt;
14use workspace::searchable::Direction;
15
16use crate::{
17 Vim,
18 motion::{Motion, MotionKind, first_non_whitespace, next_line_end, start_of_line},
19 object::Object,
20 state::{Mark, Mode, Operator},
21};
22
23actions!(
24 vim,
25 [
26 /// Toggles visual mode.
27 ToggleVisual,
28 /// Toggles visual line mode.
29 ToggleVisualLine,
30 /// Toggles visual block mode.
31 ToggleVisualBlock,
32 /// Deletes the visual selection.
33 VisualDelete,
34 /// Deletes entire lines in visual selection.
35 VisualDeleteLine,
36 /// Yanks (copies) the visual selection.
37 VisualYank,
38 /// Yanks entire lines in visual selection.
39 VisualYankLine,
40 /// Moves cursor to the other end of the selection.
41 OtherEnd,
42 /// Moves cursor to the other end of the selection (row-aware).
43 OtherEndRowAware,
44 /// Selects the next occurrence of the current selection.
45 SelectNext,
46 /// Selects the previous occurrence of the current selection.
47 SelectPrevious,
48 /// Selects the next match of the current selection.
49 SelectNextMatch,
50 /// Selects the previous match of the current selection.
51 SelectPreviousMatch,
52 /// Selects the next smaller syntax node.
53 SelectSmallerSyntaxNode,
54 /// Selects the next larger syntax node.
55 SelectLargerSyntaxNode,
56 /// Selects the next syntax node sibling.
57 SelectNextSyntaxNode,
58 /// Selects the previous syntax node sibling.
59 SelectPreviousSyntaxNode,
60 /// Restores the previous visual selection.
61 RestoreVisualSelection,
62 /// Inserts at the end of each line in visual selection.
63 VisualInsertEndOfLine,
64 /// Inserts at the first non-whitespace character of each line.
65 VisualInsertFirstNonWhiteSpace,
66 ]
67);
68
69pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
70 Vim::action(editor, cx, |vim, _: &ToggleVisual, window, cx| {
71 vim.toggle_mode(Mode::Visual, window, cx)
72 });
73 Vim::action(editor, cx, |vim, _: &ToggleVisualLine, window, cx| {
74 vim.toggle_mode(Mode::VisualLine, window, cx)
75 });
76 Vim::action(editor, cx, |vim, _: &ToggleVisualBlock, window, cx| {
77 vim.toggle_mode(Mode::VisualBlock, window, cx)
78 });
79 Vim::action(editor, cx, Vim::other_end);
80 Vim::action(editor, cx, Vim::other_end_row_aware);
81 Vim::action(editor, cx, Vim::visual_insert_end_of_line);
82 Vim::action(editor, cx, Vim::visual_insert_first_non_white_space);
83 Vim::action(editor, cx, |vim, _: &VisualDelete, window, cx| {
84 vim.record_current_action(cx);
85 vim.visual_delete(false, window, cx);
86 });
87 Vim::action(editor, cx, |vim, _: &VisualDeleteLine, window, cx| {
88 vim.record_current_action(cx);
89 vim.visual_delete(true, window, cx);
90 });
91 Vim::action(editor, cx, |vim, _: &VisualYank, window, cx| {
92 vim.visual_yank(false, window, cx)
93 });
94 Vim::action(editor, cx, |vim, _: &VisualYankLine, window, cx| {
95 vim.visual_yank(true, window, cx)
96 });
97
98 Vim::action(editor, cx, Vim::select_next);
99 Vim::action(editor, cx, Vim::select_previous);
100 Vim::action(editor, cx, |vim, _: &SelectNextMatch, window, cx| {
101 vim.select_match(Direction::Next, window, cx);
102 });
103 Vim::action(editor, cx, |vim, _: &SelectPreviousMatch, window, cx| {
104 vim.select_match(Direction::Prev, window, cx);
105 });
106
107 Vim::action(editor, cx, |vim, _: &SelectLargerSyntaxNode, window, cx| {
108 let count = Vim::take_count(cx).unwrap_or(1);
109 Vim::take_forced_motion(cx);
110 for _ in 0..count {
111 vim.update_editor(cx, |_, editor, cx| {
112 editor.select_larger_syntax_node(&Default::default(), window, cx);
113 });
114 }
115 });
116
117 Vim::action(editor, cx, |vim, _: &SelectNextSyntaxNode, window, cx| {
118 let count = Vim::take_count(cx).unwrap_or(1);
119 Vim::take_forced_motion(cx);
120 for _ in 0..count {
121 vim.update_editor(cx, |_, editor, cx| {
122 editor.select_next_syntax_node(&Default::default(), window, cx);
123 });
124 }
125 });
126
127 Vim::action(
128 editor,
129 cx,
130 |vim, _: &SelectPreviousSyntaxNode, window, cx| {
131 let count = Vim::take_count(cx).unwrap_or(1);
132 Vim::take_forced_motion(cx);
133 for _ in 0..count {
134 vim.update_editor(cx, |_, editor, cx| {
135 editor.select_prev_syntax_node(&Default::default(), window, cx);
136 });
137 }
138 },
139 );
140
141 Vim::action(
142 editor,
143 cx,
144 |vim, _: &SelectSmallerSyntaxNode, window, cx| {
145 let count = Vim::take_count(cx).unwrap_or(1);
146 Vim::take_forced_motion(cx);
147 for _ in 0..count {
148 vim.update_editor(cx, |_, editor, cx| {
149 editor.select_smaller_syntax_node(&Default::default(), window, cx);
150 });
151 }
152 },
153 );
154
155 Vim::action(editor, cx, |vim, _: &RestoreVisualSelection, window, cx| {
156 let Some((stored_mode, reversed)) = vim.stored_visual_mode.take() else {
157 return;
158 };
159 let marks = vim
160 .update_editor(cx, |vim, editor, cx| {
161 vim.get_mark("<", editor, window, cx)
162 .zip(vim.get_mark(">", editor, window, cx))
163 })
164 .flatten();
165 let Some((Mark::Local(start), Mark::Local(end))) = marks else {
166 return;
167 };
168 let ranges = start
169 .iter()
170 .zip(end)
171 .zip(reversed)
172 .map(|((start, end), reversed)| (*start, end, reversed))
173 .collect::<Vec<_>>();
174
175 if vim.mode.is_visual() {
176 vim.create_visual_marks(vim.mode, window, cx);
177 }
178
179 vim.update_editor(cx, |_, editor, cx| {
180 editor.set_clip_at_line_ends(false, cx);
181 editor.change_selections(Default::default(), window, cx, |s| {
182 let map = s.display_map();
183 let ranges = ranges
184 .into_iter()
185 .map(|(start, end, reversed)| {
186 let mut new_end =
187 movement::saturating_right(&map, end.to_display_point(&map));
188 let mut new_start = start.to_display_point(&map);
189 if new_start >= new_end {
190 if new_end.column() == 0 {
191 new_end = movement::right(&map, new_end)
192 } else {
193 new_start = movement::saturating_left(&map, new_end);
194 }
195 }
196 Selection {
197 id: s.new_selection_id(),
198 start: new_start.to_point(&map),
199 end: new_end.to_point(&map),
200 reversed,
201 goal: SelectionGoal::None,
202 }
203 })
204 .collect();
205 s.select(ranges);
206 })
207 });
208 vim.switch_mode(stored_mode, true, window, cx)
209 });
210}
211
212impl Vim {
213 pub fn visual_motion(
214 &mut self,
215 motion: Motion,
216 times: Option<usize>,
217 window: &mut Window,
218 cx: &mut Context<Self>,
219 ) {
220 self.update_editor(cx, |vim, editor, cx| {
221 let text_layout_details = editor.text_layout_details(window);
222 if vim.mode == Mode::VisualBlock
223 && !matches!(
224 motion,
225 Motion::EndOfLine {
226 display_lines: false
227 }
228 )
229 {
230 let is_up_or_down = matches!(motion, Motion::Up { .. } | Motion::Down { .. });
231 vim.visual_block_motion(is_up_or_down, editor, window, cx, |map, point, goal| {
232 motion.move_point(map, point, goal, times, &text_layout_details)
233 })
234 } else {
235 editor.change_selections(Default::default(), window, cx, |s| {
236 s.move_with(|map, selection| {
237 let was_reversed = selection.reversed;
238 let mut current_head = selection.head();
239
240 // our motions assume the current character is after the cursor,
241 // but in (forward) visual mode the current character is just
242 // before the end of the selection.
243
244 // If the file ends with a newline (which is common) we don't do this.
245 // so that if you go to the end of such a file you can use "up" to go
246 // to the previous line and have it work somewhat as expected.
247 if !selection.reversed
248 && !selection.is_empty()
249 && !(selection.end.column() == 0 && selection.end == map.max_point())
250 {
251 current_head = movement::left(map, selection.end)
252 }
253
254 let Some((new_head, goal)) = motion.move_point(
255 map,
256 current_head,
257 selection.goal,
258 times,
259 &text_layout_details,
260 ) else {
261 return;
262 };
263
264 selection.set_head(new_head, goal);
265
266 // ensure the current character is included in the selection.
267 if !selection.reversed {
268 let next_point = if vim.mode == Mode::VisualBlock {
269 movement::saturating_right(map, selection.end)
270 } else {
271 movement::right(map, selection.end)
272 };
273
274 if !(next_point.column() == 0 && next_point == map.max_point()) {
275 selection.end = next_point;
276 }
277 }
278
279 // vim always ensures the anchor character stays selected.
280 // if our selection has reversed, we need to move the opposite end
281 // to ensure the anchor is still selected.
282 if was_reversed && !selection.reversed {
283 selection.start = movement::left(map, selection.start);
284 } else if !was_reversed && selection.reversed {
285 selection.end = movement::right(map, selection.end);
286 }
287 })
288 });
289 }
290 });
291 }
292
293 pub fn visual_block_motion(
294 &mut self,
295 preserve_goal: bool,
296 editor: &mut Editor,
297 window: &mut Window,
298 cx: &mut Context<Editor>,
299 mut move_selection: impl FnMut(
300 &DisplaySnapshot,
301 DisplayPoint,
302 SelectionGoal,
303 ) -> Option<(DisplayPoint, SelectionGoal)>,
304 ) {
305 let text_layout_details = editor.text_layout_details(window);
306 editor.change_selections(Default::default(), window, cx, |s| {
307 let map = &s.display_map();
308 let mut head = s.newest_anchor().head().to_display_point(map);
309 let mut tail = s.oldest_anchor().tail().to_display_point(map);
310
311 let mut head_x = map.x_for_display_point(head, &text_layout_details);
312 let mut tail_x = map.x_for_display_point(tail, &text_layout_details);
313
314 let (start, end) = match s.newest_anchor().goal {
315 SelectionGoal::HorizontalRange { start, end } if preserve_goal => (start, end),
316 SelectionGoal::HorizontalPosition(start) if preserve_goal => (start, start),
317 _ => (tail_x.into(), head_x.into()),
318 };
319 let mut goal = SelectionGoal::HorizontalRange { start, end };
320
321 let was_reversed = tail_x > head_x;
322 if !was_reversed && !preserve_goal {
323 head = movement::saturating_left(map, head);
324 }
325
326 let reverse_aware_goal = if was_reversed {
327 SelectionGoal::HorizontalRange {
328 start: end,
329 end: start,
330 }
331 } else {
332 goal
333 };
334
335 let Some((new_head, _)) = move_selection(map, head, reverse_aware_goal) else {
336 return;
337 };
338 head = new_head;
339 head_x = map.x_for_display_point(head, &text_layout_details);
340
341 let is_reversed = tail_x > head_x;
342 if was_reversed && !is_reversed {
343 tail = movement::saturating_left(map, tail);
344 tail_x = map.x_for_display_point(tail, &text_layout_details);
345 } else if !was_reversed && is_reversed {
346 tail = movement::saturating_right(map, tail);
347 tail_x = map.x_for_display_point(tail, &text_layout_details);
348 }
349 if !is_reversed && !preserve_goal {
350 head = movement::saturating_right(map, head);
351 head_x = map.x_for_display_point(head, &text_layout_details);
352 }
353
354 let positions = if is_reversed {
355 head_x..tail_x
356 } else {
357 tail_x..head_x
358 };
359
360 if !preserve_goal {
361 goal = SelectionGoal::HorizontalRange {
362 start: f64::from(positions.start),
363 end: f64::from(positions.end),
364 };
365 }
366
367 let mut selections = Vec::new();
368 let mut row = tail.row();
369
370 loop {
371 let laid_out_line = map.layout_row(row, &text_layout_details);
372 let start = DisplayPoint::new(
373 row,
374 laid_out_line.closest_index_for_x(positions.start) as u32,
375 );
376 let mut end =
377 DisplayPoint::new(row, laid_out_line.closest_index_for_x(positions.end) as u32);
378 if end <= start {
379 if start.column() == map.line_len(start.row()) {
380 end = start;
381 } else {
382 end = movement::saturating_right(map, start);
383 }
384 }
385
386 if positions.start <= laid_out_line.width {
387 let selection = Selection {
388 id: s.new_selection_id(),
389 start: start.to_point(map),
390 end: end.to_point(map),
391 reversed: is_reversed &&
392 // For neovim parity: cursor is not reversed when column is a single character
393 end.column() - start.column() > 1,
394 goal,
395 };
396
397 selections.push(selection);
398 }
399 if row == head.row() {
400 break;
401 }
402
403 // Move to the next or previous buffer row, ensuring that
404 // wrapped lines are handled correctly.
405 let direction = if tail.row() > head.row() { -1 } else { 1 };
406 row = map
407 .start_of_relative_buffer_row(DisplayPoint::new(row, 0), direction)
408 .row();
409 }
410
411 s.select(selections);
412 })
413 }
414
415 pub fn visual_object(
416 &mut self,
417 object: Object,
418 count: Option<usize>,
419 window: &mut Window,
420 cx: &mut Context<Vim>,
421 ) {
422 if let Some(Operator::Object { around }) = self.active_operator() {
423 self.pop_operator(window, cx);
424 let current_mode = self.mode;
425 let target_mode = object.target_visual_mode(current_mode, around);
426 if target_mode != current_mode {
427 self.switch_mode(target_mode, true, window, cx);
428 }
429
430 self.update_editor(cx, |_, editor, cx| {
431 editor.change_selections(Default::default(), window, cx, |s| {
432 s.move_with(|map, selection| {
433 let mut mut_selection = selection.clone();
434
435 // all our motions assume that the current character is
436 // after the cursor; however in the case of a visual selection
437 // the current character is before the cursor.
438 // But this will affect the judgment of the html tag
439 // so the html tag needs to skip this logic.
440 if !selection.reversed && object != Object::Tag {
441 mut_selection.set_head(
442 movement::left(map, mut_selection.head()),
443 mut_selection.goal,
444 );
445 }
446
447 let original_point = selection.tail().to_point(map);
448
449 if let Some(range) = object.range(map, mut_selection, around, count) {
450 if !range.is_empty() {
451 let expand_both_ways = object.always_expands_both_ways()
452 || selection.is_empty()
453 || movement::right(map, selection.start) == selection.end;
454
455 if expand_both_ways {
456 if selection.start == range.start
457 && selection.end == range.end
458 && object.always_expands_both_ways()
459 {
460 if let Some(range) =
461 object.range(map, selection.clone(), around, count)
462 {
463 selection.start = range.start;
464 selection.end = range.end;
465 }
466 } else {
467 selection.start = range.start;
468 selection.end = range.end;
469 }
470 } else if selection.reversed {
471 selection.start = range.start;
472 } else {
473 selection.end = range.end;
474 }
475 }
476
477 // In the visual selection result of a paragraph object, the cursor is
478 // placed at the start of the last line. And in the visual mode, the
479 // selection end is located after the end character. So, adjustment of
480 // selection end is needed.
481 //
482 // We don't do this adjustment for a one-line blank paragraph since the
483 // trailing newline is included in its selection from the beginning.
484 if object == Object::Paragraph && range.start != range.end {
485 let row_of_selection_end_line = selection.end.to_point(map).row;
486 let new_selection_end = if map
487 .buffer_snapshot()
488 .line_len(MultiBufferRow(row_of_selection_end_line))
489 == 0
490 {
491 Point::new(row_of_selection_end_line + 1, 0)
492 } else {
493 Point::new(row_of_selection_end_line, 1)
494 };
495 selection.end = new_selection_end.to_display_point(map);
496 }
497
498 // To match vim, if the range starts of the same line as it originally
499 // did, we keep the tail of the selection in the same place instead of
500 // snapping it to the start of the line
501 if target_mode == Mode::VisualLine {
502 let new_start_point = selection.start.to_point(map);
503 if new_start_point.row == original_point.row {
504 if selection.end.to_point(map).row > new_start_point.row {
505 if original_point.column
506 == map
507 .buffer_snapshot()
508 .line_len(MultiBufferRow(original_point.row))
509 {
510 selection.start = movement::saturating_left(
511 map,
512 original_point.to_display_point(map),
513 )
514 } else {
515 selection.start = original_point.to_display_point(map)
516 }
517 } else {
518 selection.end = movement::saturating_right(
519 map,
520 original_point.to_display_point(map),
521 );
522 if original_point.column > 0 {
523 selection.reversed = true
524 }
525 }
526 }
527 }
528 }
529 });
530 });
531 });
532 }
533 }
534
535 fn visual_insert_end_of_line(
536 &mut self,
537 _: &VisualInsertEndOfLine,
538 window: &mut Window,
539 cx: &mut Context<Self>,
540 ) {
541 self.update_editor(cx, |_, editor, cx| {
542 editor.split_selection_into_lines(&Default::default(), window, cx);
543 editor.change_selections(Default::default(), window, cx, |s| {
544 s.move_cursors_with(|map, cursor, _| {
545 (next_line_end(map, cursor, 1), SelectionGoal::None)
546 });
547 });
548 });
549
550 self.switch_mode(Mode::Insert, false, window, cx);
551 }
552
553 fn visual_insert_first_non_white_space(
554 &mut self,
555 _: &VisualInsertFirstNonWhiteSpace,
556 window: &mut Window,
557 cx: &mut Context<Self>,
558 ) {
559 self.update_editor(cx, |_, editor, cx| {
560 editor.split_selection_into_lines(&Default::default(), window, cx);
561 editor.change_selections(Default::default(), window, cx, |s| {
562 s.move_cursors_with(|map, cursor, _| {
563 (
564 first_non_whitespace(map, false, cursor),
565 SelectionGoal::None,
566 )
567 });
568 });
569 });
570
571 self.switch_mode(Mode::Insert, false, window, cx);
572 }
573
574 fn toggle_mode(&mut self, mode: Mode, window: &mut Window, cx: &mut Context<Self>) {
575 if self.mode == mode {
576 self.switch_mode(Mode::Normal, false, window, cx);
577 } else {
578 self.switch_mode(mode, false, window, cx);
579 }
580 }
581
582 pub fn other_end(&mut self, _: &OtherEnd, window: &mut Window, cx: &mut Context<Self>) {
583 self.update_editor(cx, |_, editor, cx| {
584 editor.change_selections(Default::default(), window, cx, |s| {
585 s.move_with(|_, selection| {
586 selection.reversed = !selection.reversed;
587 });
588 })
589 });
590 }
591
592 pub fn other_end_row_aware(
593 &mut self,
594 _: &OtherEndRowAware,
595 window: &mut Window,
596 cx: &mut Context<Self>,
597 ) {
598 let mode = self.mode;
599 self.update_editor(cx, |_, editor, cx| {
600 editor.change_selections(Default::default(), window, cx, |s| {
601 s.move_with(|_, selection| {
602 selection.reversed = !selection.reversed;
603 });
604 if mode == Mode::VisualBlock {
605 s.reverse_selections();
606 }
607 })
608 });
609 }
610
611 pub fn visual_delete(&mut self, line_mode: bool, window: &mut Window, cx: &mut Context<Self>) {
612 self.store_visual_marks(window, cx);
613 self.update_editor(cx, |vim, editor, cx| {
614 let mut original_columns: HashMap<_, _> = Default::default();
615 let line_mode = line_mode || editor.selections.line_mode();
616 editor.selections.set_line_mode(false);
617
618 editor.transact(window, cx, |editor, window, cx| {
619 editor.change_selections(Default::default(), window, cx, |s| {
620 s.move_with(|map, selection| {
621 if line_mode {
622 let mut position = selection.head();
623 if !selection.reversed {
624 position = movement::left(map, position);
625 }
626 original_columns.insert(selection.id, position.to_point(map).column);
627 if vim.mode == Mode::VisualBlock {
628 *selection.end.column_mut() = map.line_len(selection.end.row())
629 } else {
630 let start = selection.start.to_point(map);
631 let end = selection.end.to_point(map);
632 selection.start = map.prev_line_boundary(start).1;
633 if end.column == 0 && end > start {
634 let row = end.row.saturating_sub(1);
635 selection.end = Point::new(
636 row,
637 map.buffer_snapshot().line_len(MultiBufferRow(row)),
638 )
639 .to_display_point(map)
640 } else {
641 selection.end = map.next_line_boundary(end).1;
642 }
643 }
644 }
645 selection.goal = SelectionGoal::None;
646 });
647 });
648 let kind = if line_mode {
649 MotionKind::Linewise
650 } else {
651 MotionKind::Exclusive
652 };
653 vim.copy_selections_content(editor, kind, window, cx);
654
655 if line_mode && vim.mode != Mode::VisualBlock {
656 editor.change_selections(Default::default(), window, cx, |s| {
657 s.move_with(|map, selection| {
658 let end = selection.end.to_point(map);
659 let start = selection.start.to_point(map);
660 if end.row < map.buffer_snapshot().max_point().row {
661 selection.end = Point::new(end.row + 1, 0).to_display_point(map)
662 } else if start.row > 0 {
663 selection.start = Point::new(
664 start.row - 1,
665 map.buffer_snapshot()
666 .line_len(MultiBufferRow(start.row - 1)),
667 )
668 .to_display_point(map)
669 }
670 });
671 });
672 }
673 editor.insert("", window, cx);
674
675 // Fixup cursor position after the deletion
676 editor.set_clip_at_line_ends(true, cx);
677 editor.change_selections(Default::default(), window, cx, |s| {
678 s.move_with(|map, selection| {
679 let mut cursor = selection.head().to_point(map);
680
681 if let Some(column) = original_columns.get(&selection.id) {
682 cursor.column = *column
683 }
684 let cursor = map.clip_point(cursor.to_display_point(map), Bias::Left);
685 selection.collapse_to(cursor, selection.goal)
686 });
687 if vim.mode == Mode::VisualBlock {
688 s.select_anchors(vec![s.first_anchor()])
689 }
690 });
691 })
692 });
693 self.switch_mode(Mode::Normal, true, window, cx);
694 }
695
696 pub fn visual_yank(&mut self, line_mode: bool, window: &mut Window, cx: &mut Context<Self>) {
697 self.store_visual_marks(window, cx);
698 self.update_editor(cx, |vim, editor, cx| {
699 let line_mode = line_mode || editor.selections.line_mode();
700
701 // For visual line mode, adjust selections to avoid yanking the next line when on \n
702 if line_mode && vim.mode != Mode::VisualBlock {
703 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
704 s.move_with(|map, selection| {
705 let start = selection.start.to_point(map);
706 let end = selection.end.to_point(map);
707 if end.column == 0 && end > start {
708 let row = end.row.saturating_sub(1);
709 selection.end = Point::new(
710 row,
711 map.buffer_snapshot().line_len(MultiBufferRow(row)),
712 )
713 .to_display_point(map);
714 }
715 });
716 });
717 }
718
719 editor.selections.set_line_mode(line_mode);
720 let kind = if line_mode {
721 MotionKind::Linewise
722 } else {
723 MotionKind::Exclusive
724 };
725 vim.yank_selections_content(editor, kind, window, cx);
726 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
727 s.move_with(|map, selection| {
728 if line_mode {
729 selection.start = start_of_line(map, false, selection.start);
730 };
731 selection.collapse_to(selection.start, SelectionGoal::None)
732 });
733 if vim.mode == Mode::VisualBlock {
734 s.select_anchors(vec![s.first_anchor()])
735 }
736 });
737 });
738 self.switch_mode(Mode::Normal, true, window, cx);
739 }
740
741 pub(crate) fn visual_replace(
742 &mut self,
743 text: Arc<str>,
744 window: &mut Window,
745 cx: &mut Context<Self>,
746 ) {
747 self.stop_recording(cx);
748 self.update_editor(cx, |_, editor, cx| {
749 editor.transact(window, cx, |editor, window, cx| {
750 let (display_map, selections) = editor.selections.all_adjusted_display(cx);
751
752 // Selections are biased right at the start. So we need to store
753 // anchors that are biased left so that we can restore the selections
754 // after the change
755 let stable_anchors = editor
756 .selections
757 .disjoint_anchors_arc()
758 .iter()
759 .map(|selection| {
760 let start = selection.start.bias_left(&display_map.buffer_snapshot());
761 start..start
762 })
763 .collect::<Vec<_>>();
764
765 let mut edits = Vec::new();
766 for selection in selections.iter() {
767 let selection = selection.clone();
768 for row_range in
769 movement::split_display_range_by_lines(&display_map, selection.range())
770 {
771 let range = row_range.start.to_offset(&display_map, Bias::Right)
772 ..row_range.end.to_offset(&display_map, Bias::Right);
773 let text = text.repeat(range.len());
774 edits.push((range, text));
775 }
776 }
777
778 editor.edit(edits, cx);
779 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
780 s.select_ranges(stable_anchors)
781 });
782 });
783 });
784 self.switch_mode(Mode::Normal, false, window, cx);
785 }
786
787 pub fn select_next(&mut self, _: &SelectNext, window: &mut Window, cx: &mut Context<Self>) {
788 Vim::take_forced_motion(cx);
789 let count =
790 Vim::take_count(cx).unwrap_or_else(|| if self.mode.is_visual() { 1 } else { 2 });
791 self.update_editor(cx, |_, editor, cx| {
792 editor.set_clip_at_line_ends(false, cx);
793 for _ in 0..count {
794 if editor
795 .select_next(&Default::default(), window, cx)
796 .log_err()
797 .is_none()
798 {
799 break;
800 }
801 }
802 });
803 }
804
805 pub fn select_previous(
806 &mut self,
807 _: &SelectPrevious,
808 window: &mut Window,
809 cx: &mut Context<Self>,
810 ) {
811 Vim::take_forced_motion(cx);
812 let count =
813 Vim::take_count(cx).unwrap_or_else(|| if self.mode.is_visual() { 1 } else { 2 });
814 self.update_editor(cx, |_, editor, cx| {
815 for _ in 0..count {
816 if editor
817 .select_previous(&Default::default(), window, cx)
818 .log_err()
819 .is_none()
820 {
821 break;
822 }
823 }
824 });
825 }
826
827 pub fn select_match(
828 &mut self,
829 direction: Direction,
830 window: &mut Window,
831 cx: &mut Context<Self>,
832 ) {
833 Vim::take_forced_motion(cx);
834 let count = Vim::take_count(cx).unwrap_or(1);
835 let Some(pane) = self.pane(window, cx) else {
836 return;
837 };
838 let vim_is_normal = self.mode == Mode::Normal;
839 let mut start_selection = 0usize;
840 let mut end_selection = 0usize;
841
842 self.update_editor(cx, |_, editor, _| {
843 editor.set_collapse_matches(false);
844 });
845 if vim_is_normal {
846 pane.update(cx, |pane, cx| {
847 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>()
848 {
849 search_bar.update(cx, |search_bar, cx| {
850 if !search_bar.has_active_match() || !search_bar.show(window, cx) {
851 return;
852 }
853 // without update_match_index there is a bug when the cursor is before the first match
854 search_bar.update_match_index(window, cx);
855 search_bar.select_match(direction.opposite(), 1, window, cx);
856 });
857 }
858 });
859 }
860 self.update_editor(cx, |_, editor, cx| {
861 let latest = editor.selections.newest::<usize>(cx);
862 start_selection = latest.start;
863 end_selection = latest.end;
864 });
865
866 let mut match_exists = false;
867 pane.update(cx, |pane, cx| {
868 if let Some(search_bar) = pane.toolbar().read(cx).item_of_type::<BufferSearchBar>() {
869 search_bar.update(cx, |search_bar, cx| {
870 search_bar.update_match_index(window, cx);
871 search_bar.select_match(direction, count, window, cx);
872 match_exists = search_bar.match_exists(window, cx);
873 });
874 }
875 });
876 if !match_exists {
877 self.clear_operator(window, cx);
878 self.stop_replaying(cx);
879 return;
880 }
881 self.update_editor(cx, |_, editor, cx| {
882 let latest = editor.selections.newest::<usize>(cx);
883 if vim_is_normal {
884 start_selection = latest.start;
885 end_selection = latest.end;
886 } else {
887 start_selection = start_selection.min(latest.start);
888 end_selection = end_selection.max(latest.end);
889 }
890 if direction == Direction::Prev {
891 std::mem::swap(&mut start_selection, &mut end_selection);
892 }
893 editor.change_selections(Default::default(), window, cx, |s| {
894 s.select_ranges([start_selection..end_selection]);
895 });
896 editor.set_collapse_matches(true);
897 });
898
899 match self.maybe_pop_operator() {
900 Some(Operator::Change) => self.substitute(None, false, window, cx),
901 Some(Operator::Delete) => {
902 self.stop_recording(cx);
903 self.visual_delete(false, window, cx)
904 }
905 Some(Operator::Yank) => self.visual_yank(false, window, cx),
906 _ => {} // Ignoring other operators
907 }
908 }
909}
910#[cfg(test)]
911mod test {
912 use indoc::indoc;
913 use workspace::item::Item;
914
915 use crate::{
916 state::Mode,
917 test::{NeovimBackedTestContext, VimTestContext},
918 };
919
920 #[gpui::test]
921 async fn test_enter_visual_mode(cx: &mut gpui::TestAppContext) {
922 let mut cx = NeovimBackedTestContext::new(cx).await;
923
924 cx.set_shared_state(indoc! {
925 "The ˇquick brown
926 fox jumps over
927 the lazy dog"
928 })
929 .await;
930 let cursor = cx.update_editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
931
932 // entering visual mode should select the character
933 // under cursor
934 cx.simulate_shared_keystrokes("v").await;
935 cx.shared_state()
936 .await
937 .assert_eq(indoc! { "The «qˇ»uick brown
938 fox jumps over
939 the lazy dog"});
940 cx.update_editor(|editor, _, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
941
942 // forwards motions should extend the selection
943 cx.simulate_shared_keystrokes("w j").await;
944 cx.shared_state().await.assert_eq(indoc! { "The «quick brown
945 fox jumps oˇ»ver
946 the lazy dog"});
947
948 cx.simulate_shared_keystrokes("escape").await;
949 cx.shared_state().await.assert_eq(indoc! { "The quick brown
950 fox jumps ˇover
951 the lazy dog"});
952
953 // motions work backwards
954 cx.simulate_shared_keystrokes("v k b").await;
955 cx.shared_state()
956 .await
957 .assert_eq(indoc! { "The «ˇquick brown
958 fox jumps o»ver
959 the lazy dog"});
960
961 // works on empty lines
962 cx.set_shared_state(indoc! {"
963 a
964 ˇ
965 b
966 "})
967 .await;
968 let cursor = cx.update_editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
969 cx.simulate_shared_keystrokes("v").await;
970 cx.shared_state().await.assert_eq(indoc! {"
971 a
972 «
973 ˇ»b
974 "});
975 cx.update_editor(|editor, _, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
976
977 // toggles off again
978 cx.simulate_shared_keystrokes("v").await;
979 cx.shared_state().await.assert_eq(indoc! {"
980 a
981 ˇ
982 b
983 "});
984
985 // works at the end of a document
986 cx.set_shared_state(indoc! {"
987 a
988 b
989 ˇ"})
990 .await;
991
992 cx.simulate_shared_keystrokes("v").await;
993 cx.shared_state().await.assert_eq(indoc! {"
994 a
995 b
996 ˇ"});
997 }
998
999 #[gpui::test]
1000 async fn test_visual_insert_first_non_whitespace(cx: &mut gpui::TestAppContext) {
1001 let mut cx = VimTestContext::new(cx, true).await;
1002
1003 cx.set_state(
1004 indoc! {
1005 "«The quick brown
1006 fox jumps over
1007 the lazy dogˇ»"
1008 },
1009 Mode::Visual,
1010 );
1011 cx.simulate_keystrokes("g shift-i");
1012 cx.assert_state(
1013 indoc! {
1014 "ˇThe quick brown
1015 ˇfox jumps over
1016 ˇthe lazy dog"
1017 },
1018 Mode::Insert,
1019 );
1020 }
1021
1022 #[gpui::test]
1023 async fn test_visual_insert_end_of_line(cx: &mut gpui::TestAppContext) {
1024 let mut cx = VimTestContext::new(cx, true).await;
1025
1026 cx.set_state(
1027 indoc! {
1028 "«The quick brown
1029 fox jumps over
1030 the lazy dogˇ»"
1031 },
1032 Mode::Visual,
1033 );
1034 cx.simulate_keystrokes("g shift-a");
1035 cx.assert_state(
1036 indoc! {
1037 "The quick brownˇ
1038 fox jumps overˇ
1039 the lazy dogˇ"
1040 },
1041 Mode::Insert,
1042 );
1043 }
1044
1045 #[gpui::test]
1046 async fn test_enter_visual_line_mode(cx: &mut gpui::TestAppContext) {
1047 let mut cx = NeovimBackedTestContext::new(cx).await;
1048
1049 cx.set_shared_state(indoc! {
1050 "The ˇquick brown
1051 fox jumps over
1052 the lazy dog"
1053 })
1054 .await;
1055 cx.simulate_shared_keystrokes("shift-v").await;
1056 cx.shared_state()
1057 .await
1058 .assert_eq(indoc! { "The «qˇ»uick brown
1059 fox jumps over
1060 the lazy dog"});
1061 cx.simulate_shared_keystrokes("x").await;
1062 cx.shared_state().await.assert_eq(indoc! { "fox ˇjumps over
1063 the lazy dog"});
1064
1065 // it should work on empty lines
1066 cx.set_shared_state(indoc! {"
1067 a
1068 ˇ
1069 b"})
1070 .await;
1071 cx.simulate_shared_keystrokes("shift-v").await;
1072 cx.shared_state().await.assert_eq(indoc! {"
1073 a
1074 «
1075 ˇ»b"});
1076 cx.simulate_shared_keystrokes("x").await;
1077 cx.shared_state().await.assert_eq(indoc! {"
1078 a
1079 ˇb"});
1080
1081 // it should work at the end of the document
1082 cx.set_shared_state(indoc! {"
1083 a
1084 b
1085 ˇ"})
1086 .await;
1087 let cursor = cx.update_editor(|editor, _, cx| editor.pixel_position_of_cursor(cx));
1088 cx.simulate_shared_keystrokes("shift-v").await;
1089 cx.shared_state().await.assert_eq(indoc! {"
1090 a
1091 b
1092 ˇ"});
1093 cx.update_editor(|editor, _, cx| assert_eq!(cursor, editor.pixel_position_of_cursor(cx)));
1094 cx.simulate_shared_keystrokes("x").await;
1095 cx.shared_state().await.assert_eq(indoc! {"
1096 a
1097 ˇb"});
1098 }
1099
1100 #[gpui::test]
1101 async fn test_visual_delete(cx: &mut gpui::TestAppContext) {
1102 let mut cx = NeovimBackedTestContext::new(cx).await;
1103
1104 cx.simulate("v w", "The quick ˇbrown")
1105 .await
1106 .assert_matches();
1107
1108 cx.simulate("v w x", "The quick ˇbrown")
1109 .await
1110 .assert_matches();
1111 cx.simulate(
1112 "v w j x",
1113 indoc! {"
1114 The ˇquick brown
1115 fox jumps over
1116 the lazy dog"},
1117 )
1118 .await
1119 .assert_matches();
1120 // Test pasting code copied on delete
1121 cx.simulate_shared_keystrokes("j p").await;
1122 cx.shared_state().await.assert_matches();
1123
1124 cx.simulate_at_each_offset(
1125 "v w j x",
1126 indoc! {"
1127 The ˇquick brown
1128 fox jumps over
1129 the ˇlazy dog"},
1130 )
1131 .await
1132 .assert_matches();
1133 cx.simulate_at_each_offset(
1134 "v b k x",
1135 indoc! {"
1136 The ˇquick brown
1137 fox jumps ˇover
1138 the ˇlazy dog"},
1139 )
1140 .await
1141 .assert_matches();
1142 }
1143
1144 #[gpui::test]
1145 async fn test_visual_line_delete(cx: &mut gpui::TestAppContext) {
1146 let mut cx = NeovimBackedTestContext::new(cx).await;
1147
1148 cx.set_shared_state(indoc! {"
1149 The quˇick brown
1150 fox jumps over
1151 the lazy dog"})
1152 .await;
1153 cx.simulate_shared_keystrokes("shift-v x").await;
1154 cx.shared_state().await.assert_matches();
1155
1156 // Test pasting code copied on delete
1157 cx.simulate_shared_keystrokes("p").await;
1158 cx.shared_state().await.assert_matches();
1159
1160 cx.set_shared_state(indoc! {"
1161 The quick brown
1162 fox jumps over
1163 the laˇzy dog"})
1164 .await;
1165 cx.simulate_shared_keystrokes("shift-v x").await;
1166 cx.shared_state().await.assert_matches();
1167 cx.shared_clipboard().await.assert_eq("the lazy dog\n");
1168
1169 cx.set_shared_state(indoc! {"
1170 The quˇick brown
1171 fox jumps over
1172 the lazy dog"})
1173 .await;
1174 cx.simulate_shared_keystrokes("shift-v j x").await;
1175 cx.shared_state().await.assert_matches();
1176 // Test pasting code copied on delete
1177 cx.simulate_shared_keystrokes("p").await;
1178 cx.shared_state().await.assert_matches();
1179
1180 cx.set_shared_state(indoc! {"
1181 The ˇlong line
1182 should not
1183 crash
1184 "})
1185 .await;
1186 cx.simulate_shared_keystrokes("shift-v $ x").await;
1187 cx.shared_state().await.assert_matches();
1188 }
1189
1190 #[gpui::test]
1191 async fn test_visual_yank(cx: &mut gpui::TestAppContext) {
1192 let mut cx = NeovimBackedTestContext::new(cx).await;
1193
1194 cx.set_shared_state("The quick ˇbrown").await;
1195 cx.simulate_shared_keystrokes("v w y").await;
1196 cx.shared_state().await.assert_eq("The quick ˇbrown");
1197 cx.shared_clipboard().await.assert_eq("brown");
1198
1199 cx.set_shared_state(indoc! {"
1200 The ˇquick brown
1201 fox jumps over
1202 the lazy dog"})
1203 .await;
1204 cx.simulate_shared_keystrokes("v w j y").await;
1205 cx.shared_state().await.assert_eq(indoc! {"
1206 The ˇquick brown
1207 fox jumps over
1208 the lazy dog"});
1209 cx.shared_clipboard().await.assert_eq(indoc! {"
1210 quick brown
1211 fox jumps o"});
1212
1213 cx.set_shared_state(indoc! {"
1214 The quick brown
1215 fox jumps over
1216 the ˇlazy dog"})
1217 .await;
1218 cx.simulate_shared_keystrokes("v w j y").await;
1219 cx.shared_state().await.assert_eq(indoc! {"
1220 The quick brown
1221 fox jumps over
1222 the ˇlazy dog"});
1223 cx.shared_clipboard().await.assert_eq("lazy d");
1224 cx.simulate_shared_keystrokes("shift-v y").await;
1225 cx.shared_clipboard().await.assert_eq("the lazy dog\n");
1226
1227 cx.set_shared_state(indoc! {"
1228 The ˇquick brown
1229 fox jumps over
1230 the lazy dog"})
1231 .await;
1232 cx.simulate_shared_keystrokes("v b k y").await;
1233 cx.shared_state().await.assert_eq(indoc! {"
1234 ˇThe quick brown
1235 fox jumps over
1236 the lazy dog"});
1237 assert_eq!(
1238 cx.read_from_clipboard()
1239 .map(|item| item.text().unwrap())
1240 .unwrap(),
1241 "The q"
1242 );
1243
1244 cx.set_shared_state(indoc! {"
1245 The quick brown
1246 fox ˇjumps over
1247 the lazy dog"})
1248 .await;
1249 cx.simulate_shared_keystrokes("shift-v shift-g shift-y")
1250 .await;
1251 cx.shared_state().await.assert_eq(indoc! {"
1252 The quick brown
1253 ˇfox jumps over
1254 the lazy dog"});
1255 cx.shared_clipboard()
1256 .await
1257 .assert_eq("fox jumps over\nthe lazy dog\n");
1258
1259 cx.set_shared_state(indoc! {"
1260 The quick brown
1261 fox ˇjumps over
1262 the lazy dog"})
1263 .await;
1264 cx.simulate_shared_keystrokes("shift-v $ shift-y").await;
1265 cx.shared_state().await.assert_eq(indoc! {"
1266 The quick brown
1267 ˇfox jumps over
1268 the lazy dog"});
1269 cx.shared_clipboard().await.assert_eq("fox jumps over\n");
1270 }
1271
1272 #[gpui::test]
1273 async fn test_visual_block_mode(cx: &mut gpui::TestAppContext) {
1274 let mut cx = NeovimBackedTestContext::new(cx).await;
1275
1276 cx.set_shared_state(indoc! {
1277 "The ˇquick brown
1278 fox jumps over
1279 the lazy dog"
1280 })
1281 .await;
1282 cx.simulate_shared_keystrokes("ctrl-v").await;
1283 cx.shared_state().await.assert_eq(indoc! {
1284 "The «qˇ»uick brown
1285 fox jumps over
1286 the lazy dog"
1287 });
1288 cx.simulate_shared_keystrokes("2 down").await;
1289 cx.shared_state().await.assert_eq(indoc! {
1290 "The «qˇ»uick brown
1291 fox «jˇ»umps over
1292 the «lˇ»azy dog"
1293 });
1294 cx.simulate_shared_keystrokes("e").await;
1295 cx.shared_state().await.assert_eq(indoc! {
1296 "The «quicˇ»k brown
1297 fox «jumpˇ»s over
1298 the «lazyˇ» dog"
1299 });
1300 cx.simulate_shared_keystrokes("^").await;
1301 cx.shared_state().await.assert_eq(indoc! {
1302 "«ˇThe q»uick brown
1303 «ˇfox j»umps over
1304 «ˇthe l»azy dog"
1305 });
1306 cx.simulate_shared_keystrokes("$").await;
1307 cx.shared_state().await.assert_eq(indoc! {
1308 "The «quick brownˇ»
1309 fox «jumps overˇ»
1310 the «lazy dogˇ»"
1311 });
1312 cx.simulate_shared_keystrokes("shift-f space").await;
1313 cx.shared_state().await.assert_eq(indoc! {
1314 "The «quickˇ» brown
1315 fox «jumpsˇ» over
1316 the «lazy ˇ»dog"
1317 });
1318
1319 // toggling through visual mode works as expected
1320 cx.simulate_shared_keystrokes("v").await;
1321 cx.shared_state().await.assert_eq(indoc! {
1322 "The «quick brown
1323 fox jumps over
1324 the lazy ˇ»dog"
1325 });
1326 cx.simulate_shared_keystrokes("ctrl-v").await;
1327 cx.shared_state().await.assert_eq(indoc! {
1328 "The «quickˇ» brown
1329 fox «jumpsˇ» over
1330 the «lazy ˇ»dog"
1331 });
1332
1333 cx.set_shared_state(indoc! {
1334 "The ˇquick
1335 brown
1336 fox
1337 jumps over the
1338
1339 lazy dog
1340 "
1341 })
1342 .await;
1343 cx.simulate_shared_keystrokes("ctrl-v down down").await;
1344 cx.shared_state().await.assert_eq(indoc! {
1345 "The«ˇ q»uick
1346 bro«ˇwn»
1347 foxˇ
1348 jumps over the
1349
1350 lazy dog
1351 "
1352 });
1353 cx.simulate_shared_keystrokes("down").await;
1354 cx.shared_state().await.assert_eq(indoc! {
1355 "The «qˇ»uick
1356 brow«nˇ»
1357 fox
1358 jump«sˇ» over the
1359
1360 lazy dog
1361 "
1362 });
1363 cx.simulate_shared_keystrokes("left").await;
1364 cx.shared_state().await.assert_eq(indoc! {
1365 "The«ˇ q»uick
1366 bro«ˇwn»
1367 foxˇ
1368 jum«ˇps» over the
1369
1370 lazy dog
1371 "
1372 });
1373 cx.simulate_shared_keystrokes("s o escape").await;
1374 cx.shared_state().await.assert_eq(indoc! {
1375 "Theˇouick
1376 broo
1377 foxo
1378 jumo over the
1379
1380 lazy dog
1381 "
1382 });
1383
1384 // https://github.com/zed-industries/zed/issues/6274
1385 cx.set_shared_state(indoc! {
1386 "Theˇ quick brown
1387
1388 fox jumps over
1389 the lazy dog
1390 "
1391 })
1392 .await;
1393 cx.simulate_shared_keystrokes("l ctrl-v j j").await;
1394 cx.shared_state().await.assert_eq(indoc! {
1395 "The «qˇ»uick brown
1396
1397 fox «jˇ»umps over
1398 the lazy dog
1399 "
1400 });
1401 }
1402
1403 #[gpui::test]
1404 async fn test_visual_block_issue_2123(cx: &mut gpui::TestAppContext) {
1405 let mut cx = NeovimBackedTestContext::new(cx).await;
1406
1407 cx.set_shared_state(indoc! {
1408 "The ˇquick brown
1409 fox jumps over
1410 the lazy dog
1411 "
1412 })
1413 .await;
1414 cx.simulate_shared_keystrokes("ctrl-v right down").await;
1415 cx.shared_state().await.assert_eq(indoc! {
1416 "The «quˇ»ick brown
1417 fox «juˇ»mps over
1418 the lazy dog
1419 "
1420 });
1421 }
1422 #[gpui::test]
1423 async fn test_visual_block_mode_down_right(cx: &mut gpui::TestAppContext) {
1424 let mut cx = NeovimBackedTestContext::new(cx).await;
1425 cx.set_shared_state(indoc! {"
1426 The ˇquick brown
1427 fox jumps over
1428 the lazy dog"})
1429 .await;
1430 cx.simulate_shared_keystrokes("ctrl-v l l l l l j").await;
1431 cx.shared_state().await.assert_eq(indoc! {"
1432 The «quick ˇ»brown
1433 fox «jumps ˇ»over
1434 the lazy dog"});
1435 }
1436
1437 #[gpui::test]
1438 async fn test_visual_block_mode_up_left(cx: &mut gpui::TestAppContext) {
1439 let mut cx = NeovimBackedTestContext::new(cx).await;
1440 cx.set_shared_state(indoc! {"
1441 The quick brown
1442 fox jumpsˇ over
1443 the lazy dog"})
1444 .await;
1445 cx.simulate_shared_keystrokes("ctrl-v h h h h h k").await;
1446 cx.shared_state().await.assert_eq(indoc! {"
1447 The «ˇquick »brown
1448 fox «ˇjumps »over
1449 the lazy dog"});
1450 }
1451
1452 #[gpui::test]
1453 async fn test_visual_block_mode_other_end(cx: &mut gpui::TestAppContext) {
1454 let mut cx = NeovimBackedTestContext::new(cx).await;
1455 cx.set_shared_state(indoc! {"
1456 The quick brown
1457 fox jˇumps over
1458 the lazy dog"})
1459 .await;
1460 cx.simulate_shared_keystrokes("ctrl-v l l l l j").await;
1461 cx.shared_state().await.assert_eq(indoc! {"
1462 The quick brown
1463 fox j«umps ˇ»over
1464 the l«azy dˇ»og"});
1465 cx.simulate_shared_keystrokes("o k").await;
1466 cx.shared_state().await.assert_eq(indoc! {"
1467 The q«ˇuick »brown
1468 fox j«ˇumps »over
1469 the l«ˇazy d»og"});
1470 }
1471
1472 #[gpui::test]
1473 async fn test_visual_block_mode_shift_other_end(cx: &mut gpui::TestAppContext) {
1474 let mut cx = NeovimBackedTestContext::new(cx).await;
1475 cx.set_shared_state(indoc! {"
1476 The quick brown
1477 fox jˇumps over
1478 the lazy dog"})
1479 .await;
1480 cx.simulate_shared_keystrokes("ctrl-v l l l l j").await;
1481 cx.shared_state().await.assert_eq(indoc! {"
1482 The quick brown
1483 fox j«umps ˇ»over
1484 the l«azy dˇ»og"});
1485 cx.simulate_shared_keystrokes("shift-o k").await;
1486 cx.shared_state().await.assert_eq(indoc! {"
1487 The quick brown
1488 fox j«ˇumps »over
1489 the lazy dog"});
1490 }
1491
1492 #[gpui::test]
1493 async fn test_visual_block_insert(cx: &mut gpui::TestAppContext) {
1494 let mut cx = NeovimBackedTestContext::new(cx).await;
1495
1496 cx.set_shared_state(indoc! {
1497 "ˇThe quick brown
1498 fox jumps over
1499 the lazy dog
1500 "
1501 })
1502 .await;
1503 cx.simulate_shared_keystrokes("ctrl-v 9 down").await;
1504 cx.shared_state().await.assert_eq(indoc! {
1505 "«Tˇ»he quick brown
1506 «fˇ»ox jumps over
1507 «tˇ»he lazy dog
1508 ˇ"
1509 });
1510
1511 cx.simulate_shared_keystrokes("shift-i k escape").await;
1512 cx.shared_state().await.assert_eq(indoc! {
1513 "ˇkThe quick brown
1514 kfox jumps over
1515 kthe lazy dog
1516 k"
1517 });
1518
1519 cx.set_shared_state(indoc! {
1520 "ˇThe quick brown
1521 fox jumps over
1522 the lazy dog
1523 "
1524 })
1525 .await;
1526 cx.simulate_shared_keystrokes("ctrl-v 9 down").await;
1527 cx.shared_state().await.assert_eq(indoc! {
1528 "«Tˇ»he quick brown
1529 «fˇ»ox jumps over
1530 «tˇ»he lazy dog
1531 ˇ"
1532 });
1533 cx.simulate_shared_keystrokes("c k escape").await;
1534 cx.shared_state().await.assert_eq(indoc! {
1535 "ˇkhe quick brown
1536 kox jumps over
1537 khe lazy dog
1538 k"
1539 });
1540 }
1541
1542 #[gpui::test]
1543 async fn test_visual_block_wrapping_selection(cx: &mut gpui::TestAppContext) {
1544 let mut cx = NeovimBackedTestContext::new(cx).await;
1545
1546 // Ensure that the editor is wrapping lines at 12 columns so that each
1547 // of the lines ends up being wrapped.
1548 cx.set_shared_wrap(12).await;
1549 cx.set_shared_state(indoc! {
1550 "ˇ12345678901234567890
1551 12345678901234567890
1552 12345678901234567890
1553 "
1554 })
1555 .await;
1556 cx.simulate_shared_keystrokes("ctrl-v j").await;
1557 cx.shared_state().await.assert_eq(indoc! {
1558 "«1ˇ»2345678901234567890
1559 «1ˇ»2345678901234567890
1560 12345678901234567890
1561 "
1562 });
1563
1564 // Test with lines taking up different amounts of display rows to ensure
1565 // that, even in that case, only the buffer rows are taken into account.
1566 cx.set_shared_state(indoc! {
1567 "ˇ123456789012345678901234567890123456789012345678901234567890
1568 1234567890123456789012345678901234567890
1569 12345678901234567890
1570 "
1571 })
1572 .await;
1573 cx.simulate_shared_keystrokes("ctrl-v 2 j").await;
1574 cx.shared_state().await.assert_eq(indoc! {
1575 "«1ˇ»23456789012345678901234567890123456789012345678901234567890
1576 «1ˇ»234567890123456789012345678901234567890
1577 «1ˇ»2345678901234567890
1578 "
1579 });
1580
1581 // Same scenario as above, but using the up motion to ensure that the
1582 // result is the same.
1583 cx.set_shared_state(indoc! {
1584 "123456789012345678901234567890123456789012345678901234567890
1585 1234567890123456789012345678901234567890
1586 ˇ12345678901234567890
1587 "
1588 })
1589 .await;
1590 cx.simulate_shared_keystrokes("ctrl-v 2 k").await;
1591 cx.shared_state().await.assert_eq(indoc! {
1592 "«1ˇ»23456789012345678901234567890123456789012345678901234567890
1593 «1ˇ»234567890123456789012345678901234567890
1594 «1ˇ»2345678901234567890
1595 "
1596 });
1597 }
1598
1599 #[gpui::test]
1600 async fn test_visual_object(cx: &mut gpui::TestAppContext) {
1601 let mut cx = NeovimBackedTestContext::new(cx).await;
1602
1603 cx.set_shared_state("hello (in [parˇens] o)").await;
1604 cx.simulate_shared_keystrokes("ctrl-v l").await;
1605 cx.simulate_shared_keystrokes("a ]").await;
1606 cx.shared_state()
1607 .await
1608 .assert_eq("hello (in «[parens]ˇ» o)");
1609 cx.simulate_shared_keystrokes("i (").await;
1610 cx.shared_state()
1611 .await
1612 .assert_eq("hello («in [parens] oˇ»)");
1613
1614 cx.set_shared_state("hello in a wˇord again.").await;
1615 cx.simulate_shared_keystrokes("ctrl-v l i w").await;
1616 cx.shared_state()
1617 .await
1618 .assert_eq("hello in a w«ordˇ» again.");
1619 assert_eq!(cx.mode(), Mode::VisualBlock);
1620 cx.simulate_shared_keystrokes("o a s").await;
1621 cx.shared_state()
1622 .await
1623 .assert_eq("«ˇhello in a word» again.");
1624 }
1625
1626 #[gpui::test]
1627 async fn test_visual_object_expands(cx: &mut gpui::TestAppContext) {
1628 let mut cx = NeovimBackedTestContext::new(cx).await;
1629
1630 cx.set_shared_state(indoc! {
1631 "{
1632 {
1633 ˇ }
1634 }
1635 {
1636 }
1637 "
1638 })
1639 .await;
1640 cx.simulate_shared_keystrokes("v l").await;
1641 cx.shared_state().await.assert_eq(indoc! {
1642 "{
1643 {
1644 « }ˇ»
1645 }
1646 {
1647 }
1648 "
1649 });
1650 cx.simulate_shared_keystrokes("a {").await;
1651 cx.shared_state().await.assert_eq(indoc! {
1652 "{
1653 «{
1654 }ˇ»
1655 }
1656 {
1657 }
1658 "
1659 });
1660 cx.simulate_shared_keystrokes("a {").await;
1661 cx.shared_state().await.assert_eq(indoc! {
1662 "«{
1663 {
1664 }
1665 }ˇ»
1666 {
1667 }
1668 "
1669 });
1670 // cx.simulate_shared_keystrokes("a {").await;
1671 // cx.shared_state().await.assert_eq(indoc! {
1672 // "{
1673 // «{
1674 // }ˇ»
1675 // }
1676 // {
1677 // }
1678 // "
1679 // });
1680 }
1681
1682 #[gpui::test]
1683 async fn test_mode_across_command(cx: &mut gpui::TestAppContext) {
1684 let mut cx = VimTestContext::new(cx, true).await;
1685
1686 cx.set_state("aˇbc", Mode::Normal);
1687 cx.simulate_keystrokes("ctrl-v");
1688 assert_eq!(cx.mode(), Mode::VisualBlock);
1689 cx.simulate_keystrokes("cmd-shift-p escape");
1690 assert_eq!(cx.mode(), Mode::VisualBlock);
1691 }
1692
1693 #[gpui::test]
1694 async fn test_gn(cx: &mut gpui::TestAppContext) {
1695 let mut cx = NeovimBackedTestContext::new(cx).await;
1696
1697 cx.set_shared_state("aaˇ aa aa aa aa").await;
1698 cx.simulate_shared_keystrokes("/ a a enter").await;
1699 cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1700 cx.simulate_shared_keystrokes("g n").await;
1701 cx.shared_state().await.assert_eq("aa «aaˇ» aa aa aa");
1702 cx.simulate_shared_keystrokes("g n").await;
1703 cx.shared_state().await.assert_eq("aa «aa aaˇ» aa aa");
1704 cx.simulate_shared_keystrokes("escape d g n").await;
1705 cx.shared_state().await.assert_eq("aa aa ˇ aa aa");
1706
1707 cx.set_shared_state("aaˇ aa aa aa aa").await;
1708 cx.simulate_shared_keystrokes("/ a a enter").await;
1709 cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1710 cx.simulate_shared_keystrokes("3 g n").await;
1711 cx.shared_state().await.assert_eq("aa aa aa «aaˇ» aa");
1712
1713 cx.set_shared_state("aaˇ aa aa aa aa").await;
1714 cx.simulate_shared_keystrokes("/ a a enter").await;
1715 cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1716 cx.simulate_shared_keystrokes("g shift-n").await;
1717 cx.shared_state().await.assert_eq("aa «ˇaa» aa aa aa");
1718 cx.simulate_shared_keystrokes("g shift-n").await;
1719 cx.shared_state().await.assert_eq("«ˇaa aa» aa aa aa");
1720 }
1721
1722 #[gpui::test]
1723 async fn test_gl(cx: &mut gpui::TestAppContext) {
1724 let mut cx = VimTestContext::new(cx, true).await;
1725
1726 cx.set_state("aaˇ aa\naa", Mode::Normal);
1727 cx.simulate_keystrokes("g l");
1728 cx.assert_state("«aaˇ» «aaˇ»\naa", Mode::Visual);
1729 cx.simulate_keystrokes("g >");
1730 cx.assert_state("«aaˇ» aa\n«aaˇ»", Mode::Visual);
1731 }
1732
1733 #[gpui::test]
1734 async fn test_dgn_repeat(cx: &mut gpui::TestAppContext) {
1735 let mut cx = NeovimBackedTestContext::new(cx).await;
1736
1737 cx.set_shared_state("aaˇ aa aa aa aa").await;
1738 cx.simulate_shared_keystrokes("/ a a enter").await;
1739 cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1740 cx.simulate_shared_keystrokes("d g n").await;
1741
1742 cx.shared_state().await.assert_eq("aa ˇ aa aa aa");
1743 cx.simulate_shared_keystrokes(".").await;
1744 cx.shared_state().await.assert_eq("aa ˇ aa aa");
1745 cx.simulate_shared_keystrokes(".").await;
1746 cx.shared_state().await.assert_eq("aa ˇ aa");
1747 }
1748
1749 #[gpui::test]
1750 async fn test_cgn_repeat(cx: &mut gpui::TestAppContext) {
1751 let mut cx = NeovimBackedTestContext::new(cx).await;
1752
1753 cx.set_shared_state("aaˇ aa aa aa aa").await;
1754 cx.simulate_shared_keystrokes("/ a a enter").await;
1755 cx.shared_state().await.assert_eq("aa ˇaa aa aa aa");
1756 cx.simulate_shared_keystrokes("c g n x escape").await;
1757 cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1758 cx.simulate_shared_keystrokes(".").await;
1759 cx.shared_state().await.assert_eq("aa x ˇx aa aa");
1760 }
1761
1762 #[gpui::test]
1763 async fn test_cgn_nomatch(cx: &mut gpui::TestAppContext) {
1764 let mut cx = NeovimBackedTestContext::new(cx).await;
1765
1766 cx.set_shared_state("aaˇ aa aa aa aa").await;
1767 cx.simulate_shared_keystrokes("/ b b enter").await;
1768 cx.shared_state().await.assert_eq("aaˇ aa aa aa aa");
1769 cx.simulate_shared_keystrokes("c g n x escape").await;
1770 cx.shared_state().await.assert_eq("aaˇaa aa aa aa");
1771 cx.simulate_shared_keystrokes(".").await;
1772 cx.shared_state().await.assert_eq("aaˇa aa aa aa");
1773
1774 cx.set_shared_state("aaˇ bb aa aa aa").await;
1775 cx.simulate_shared_keystrokes("/ b b enter").await;
1776 cx.shared_state().await.assert_eq("aa ˇbb aa aa aa");
1777 cx.simulate_shared_keystrokes("c g n x escape").await;
1778 cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1779 cx.simulate_shared_keystrokes(".").await;
1780 cx.shared_state().await.assert_eq("aa ˇx aa aa aa");
1781 }
1782
1783 #[gpui::test]
1784 async fn test_visual_shift_d(cx: &mut gpui::TestAppContext) {
1785 let mut cx = NeovimBackedTestContext::new(cx).await;
1786
1787 cx.set_shared_state(indoc! {
1788 "The ˇquick brown
1789 fox jumps over
1790 the lazy dog
1791 "
1792 })
1793 .await;
1794 cx.simulate_shared_keystrokes("v down shift-d").await;
1795 cx.shared_state().await.assert_eq(indoc! {
1796 "the ˇlazy dog\n"
1797 });
1798
1799 cx.set_shared_state(indoc! {
1800 "The ˇquick brown
1801 fox jumps over
1802 the lazy dog
1803 "
1804 })
1805 .await;
1806 cx.simulate_shared_keystrokes("ctrl-v down shift-d").await;
1807 cx.shared_state().await.assert_eq(indoc! {
1808 "Theˇ•
1809 fox•
1810 the lazy dog
1811 "
1812 });
1813 }
1814
1815 #[gpui::test]
1816 async fn test_shift_y(cx: &mut gpui::TestAppContext) {
1817 let mut cx = NeovimBackedTestContext::new(cx).await;
1818
1819 cx.set_shared_state(indoc! {
1820 "The ˇquick brown\n"
1821 })
1822 .await;
1823 cx.simulate_shared_keystrokes("v i w shift-y").await;
1824 cx.shared_clipboard().await.assert_eq(indoc! {
1825 "The quick brown\n"
1826 });
1827 }
1828
1829 #[gpui::test]
1830 async fn test_gv(cx: &mut gpui::TestAppContext) {
1831 let mut cx = NeovimBackedTestContext::new(cx).await;
1832
1833 cx.set_shared_state(indoc! {
1834 "The ˇquick brown"
1835 })
1836 .await;
1837 cx.simulate_shared_keystrokes("v i w escape g v").await;
1838 cx.shared_state().await.assert_eq(indoc! {
1839 "The «quickˇ» brown"
1840 });
1841
1842 cx.simulate_shared_keystrokes("o escape g v").await;
1843 cx.shared_state().await.assert_eq(indoc! {
1844 "The «ˇquick» brown"
1845 });
1846
1847 cx.simulate_shared_keystrokes("escape ^ ctrl-v l").await;
1848 cx.shared_state().await.assert_eq(indoc! {
1849 "«Thˇ»e quick brown"
1850 });
1851 cx.simulate_shared_keystrokes("g v").await;
1852 cx.shared_state().await.assert_eq(indoc! {
1853 "The «ˇquick» brown"
1854 });
1855 cx.simulate_shared_keystrokes("g v").await;
1856 cx.shared_state().await.assert_eq(indoc! {
1857 "«Thˇ»e quick brown"
1858 });
1859
1860 cx.set_state(
1861 indoc! {"
1862 fiˇsh one
1863 fish two
1864 fish red
1865 fish blue
1866 "},
1867 Mode::Normal,
1868 );
1869 cx.simulate_keystrokes("4 g l escape escape g v");
1870 cx.assert_state(
1871 indoc! {"
1872 «fishˇ» one
1873 «fishˇ» two
1874 «fishˇ» red
1875 «fishˇ» blue
1876 "},
1877 Mode::Visual,
1878 );
1879 cx.simulate_keystrokes("y g v");
1880 cx.assert_state(
1881 indoc! {"
1882 «fishˇ» one
1883 «fishˇ» two
1884 «fishˇ» red
1885 «fishˇ» blue
1886 "},
1887 Mode::Visual,
1888 );
1889 }
1890
1891 #[gpui::test]
1892 async fn test_p_g_v_y(cx: &mut gpui::TestAppContext) {
1893 let mut cx = NeovimBackedTestContext::new(cx).await;
1894
1895 cx.set_shared_state(indoc! {
1896 "The
1897 quicˇk
1898 brown
1899 fox"
1900 })
1901 .await;
1902 cx.simulate_shared_keystrokes("y y j shift-v p g v y").await;
1903 cx.shared_state().await.assert_eq(indoc! {
1904 "The
1905 quick
1906 ˇquick
1907 fox"
1908 });
1909 cx.shared_clipboard().await.assert_eq("quick\n");
1910 }
1911
1912 #[gpui::test]
1913 async fn test_v2ap(cx: &mut gpui::TestAppContext) {
1914 let mut cx = NeovimBackedTestContext::new(cx).await;
1915
1916 cx.set_shared_state(indoc! {
1917 "The
1918 quicˇk
1919
1920 brown
1921 fox"
1922 })
1923 .await;
1924 cx.simulate_shared_keystrokes("v 2 a p").await;
1925 cx.shared_state().await.assert_eq(indoc! {
1926 "«The
1927 quick
1928
1929 brown
1930 fˇ»ox"
1931 });
1932 }
1933
1934 #[gpui::test]
1935 async fn test_visual_syntax_sibling_selection(cx: &mut gpui::TestAppContext) {
1936 let mut cx = VimTestContext::new(cx, true).await;
1937
1938 cx.set_state(
1939 indoc! {"
1940 fn test() {
1941 let ˇa = 1;
1942 let b = 2;
1943 let c = 3;
1944 }
1945 "},
1946 Mode::Normal,
1947 );
1948
1949 // Enter visual mode and select the statement
1950 cx.simulate_keystrokes("v w w w");
1951 cx.assert_state(
1952 indoc! {"
1953 fn test() {
1954 let «a = 1;ˇ»
1955 let b = 2;
1956 let c = 3;
1957 }
1958 "},
1959 Mode::Visual,
1960 );
1961
1962 // The specific behavior of syntax sibling selection in vim mode
1963 // would depend on the key bindings configured, but the actions
1964 // are now available for use
1965 }
1966}