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