1use editor::{
2 Anchor, Bias, DisplayPoint, Editor, RowExt, ToOffset, ToPoint,
3 display_map::{DisplayRow, DisplaySnapshot, FoldPoint, ToDisplayPoint},
4 movement::{
5 self, FindRange, TextLayoutDetails, find_boundary, find_preceding_boundary_display_point,
6 },
7};
8use gpui::{Action, Context, Window, actions, px};
9use language::{CharKind, Point, Selection, SelectionGoal};
10use multi_buffer::MultiBufferRow;
11use schemars::JsonSchema;
12use serde::Deserialize;
13use std::ops::Range;
14use workspace::searchable::Direction;
15
16use crate::{
17 Vim,
18 normal::mark,
19 state::{Mode, Operator},
20 surrounds::SurroundsType,
21};
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub(crate) enum MotionKind {
25 Linewise,
26 Exclusive,
27 Inclusive,
28}
29
30impl MotionKind {
31 pub(crate) fn for_mode(mode: Mode) -> Self {
32 match mode {
33 Mode::VisualLine => MotionKind::Linewise,
34 _ => MotionKind::Exclusive,
35 }
36 }
37
38 pub(crate) fn linewise(&self) -> bool {
39 matches!(self, MotionKind::Linewise)
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub enum Motion {
45 Left,
46 WrappingLeft,
47 Down {
48 display_lines: bool,
49 },
50 Up {
51 display_lines: bool,
52 },
53 Right,
54 WrappingRight,
55 NextWordStart {
56 ignore_punctuation: bool,
57 },
58 NextWordEnd {
59 ignore_punctuation: bool,
60 },
61 PreviousWordStart {
62 ignore_punctuation: bool,
63 },
64 PreviousWordEnd {
65 ignore_punctuation: bool,
66 },
67 NextSubwordStart {
68 ignore_punctuation: bool,
69 },
70 NextSubwordEnd {
71 ignore_punctuation: bool,
72 },
73 PreviousSubwordStart {
74 ignore_punctuation: bool,
75 },
76 PreviousSubwordEnd {
77 ignore_punctuation: bool,
78 },
79 FirstNonWhitespace {
80 display_lines: bool,
81 },
82 CurrentLine,
83 StartOfLine {
84 display_lines: bool,
85 },
86 MiddleOfLine {
87 display_lines: bool,
88 },
89 EndOfLine {
90 display_lines: bool,
91 },
92 SentenceBackward,
93 SentenceForward,
94 StartOfParagraph,
95 EndOfParagraph,
96 StartOfDocument,
97 EndOfDocument,
98 Matching,
99 GoToPercentage,
100 UnmatchedForward {
101 char: char,
102 },
103 UnmatchedBackward {
104 char: char,
105 },
106 FindForward {
107 before: bool,
108 char: char,
109 mode: FindRange,
110 smartcase: bool,
111 },
112 FindBackward {
113 after: bool,
114 char: char,
115 mode: FindRange,
116 smartcase: bool,
117 },
118 Sneak {
119 first_char: char,
120 second_char: char,
121 smartcase: bool,
122 },
123 SneakBackward {
124 first_char: char,
125 second_char: char,
126 smartcase: bool,
127 },
128 RepeatFind {
129 last_find: Box<Motion>,
130 },
131 RepeatFindReversed {
132 last_find: Box<Motion>,
133 },
134 NextLineStart,
135 PreviousLineStart,
136 StartOfLineDownward,
137 EndOfLineDownward,
138 GoToColumn,
139 WindowTop,
140 WindowMiddle,
141 WindowBottom,
142 NextSectionStart,
143 NextSectionEnd,
144 PreviousSectionStart,
145 PreviousSectionEnd,
146 NextMethodStart,
147 NextMethodEnd,
148 PreviousMethodStart,
149 PreviousMethodEnd,
150 NextComment,
151 PreviousComment,
152 PreviousLesserIndent,
153 PreviousGreaterIndent,
154 PreviousSameIndent,
155 NextLesserIndent,
156 NextGreaterIndent,
157 NextSameIndent,
158
159 // we don't have a good way to run a search synchronously, so
160 // we handle search motions by running the search async and then
161 // calling back into motion with this
162 ZedSearchResult {
163 prior_selections: Vec<Range<Anchor>>,
164 new_selections: Vec<Range<Anchor>>,
165 },
166 Jump {
167 anchor: Anchor,
168 line: bool,
169 },
170}
171
172#[derive(Clone, Copy)]
173enum IndentType {
174 Lesser,
175 Greater,
176 Same,
177}
178
179/// Moves to the start of the next word.
180#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
181#[action(namespace = vim)]
182#[serde(deny_unknown_fields)]
183struct NextWordStart {
184 #[serde(default)]
185 ignore_punctuation: bool,
186}
187
188/// Moves to the end of the next word.
189#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
190#[action(namespace = vim)]
191#[serde(deny_unknown_fields)]
192struct NextWordEnd {
193 #[serde(default)]
194 ignore_punctuation: bool,
195}
196
197/// Moves to the start of the previous word.
198#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
199#[action(namespace = vim)]
200#[serde(deny_unknown_fields)]
201struct PreviousWordStart {
202 #[serde(default)]
203 ignore_punctuation: bool,
204}
205
206/// Moves to the end of the previous word.
207#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
208#[action(namespace = vim)]
209#[serde(deny_unknown_fields)]
210struct PreviousWordEnd {
211 #[serde(default)]
212 ignore_punctuation: bool,
213}
214
215/// Moves to the start of the next subword.
216#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
217#[action(namespace = vim)]
218#[serde(deny_unknown_fields)]
219pub(crate) struct NextSubwordStart {
220 #[serde(default)]
221 pub(crate) ignore_punctuation: bool,
222}
223
224/// Moves to the end of the next subword.
225#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
226#[action(namespace = vim)]
227#[serde(deny_unknown_fields)]
228pub(crate) struct NextSubwordEnd {
229 #[serde(default)]
230 pub(crate) ignore_punctuation: bool,
231}
232
233/// Moves to the start of the previous subword.
234#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
235#[action(namespace = vim)]
236#[serde(deny_unknown_fields)]
237pub(crate) struct PreviousSubwordStart {
238 #[serde(default)]
239 pub(crate) ignore_punctuation: bool,
240}
241
242/// Moves to the end of the previous subword.
243#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
244#[action(namespace = vim)]
245#[serde(deny_unknown_fields)]
246pub(crate) struct PreviousSubwordEnd {
247 #[serde(default)]
248 pub(crate) ignore_punctuation: bool,
249}
250
251/// Moves cursor up by the specified number of lines.
252#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
253#[action(namespace = vim)]
254#[serde(deny_unknown_fields)]
255pub(crate) struct Up {
256 #[serde(default)]
257 pub(crate) display_lines: bool,
258}
259
260/// Moves cursor down by the specified number of lines.
261#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
262#[action(namespace = vim)]
263#[serde(deny_unknown_fields)]
264pub(crate) struct Down {
265 #[serde(default)]
266 pub(crate) display_lines: bool,
267}
268
269/// Moves to the first non-whitespace character on the current line.
270#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
271#[action(namespace = vim)]
272#[serde(deny_unknown_fields)]
273struct FirstNonWhitespace {
274 #[serde(default)]
275 display_lines: bool,
276}
277
278/// Moves to the end of the current line.
279#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
280#[action(namespace = vim)]
281#[serde(deny_unknown_fields)]
282struct EndOfLine {
283 #[serde(default)]
284 display_lines: bool,
285}
286
287/// Moves to the start of the current line.
288#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
289#[action(namespace = vim)]
290#[serde(deny_unknown_fields)]
291pub struct StartOfLine {
292 #[serde(default)]
293 pub(crate) display_lines: bool,
294}
295
296/// Moves to the middle of the current line.
297#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
298#[action(namespace = vim)]
299#[serde(deny_unknown_fields)]
300struct MiddleOfLine {
301 #[serde(default)]
302 display_lines: bool,
303}
304
305/// Finds the next unmatched bracket or delimiter.
306#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
307#[action(namespace = vim)]
308#[serde(deny_unknown_fields)]
309struct UnmatchedForward {
310 #[serde(default)]
311 char: char,
312}
313
314/// Finds the previous unmatched bracket or delimiter.
315#[derive(Clone, Deserialize, JsonSchema, PartialEq, Action)]
316#[action(namespace = vim)]
317#[serde(deny_unknown_fields)]
318struct UnmatchedBackward {
319 #[serde(default)]
320 char: char,
321}
322
323actions!(
324 vim,
325 [
326 /// Moves cursor left one character.
327 Left,
328 /// Moves cursor left one character, wrapping to previous line.
329 #[action(deprecated_aliases = ["vim::Backspace"])]
330 WrappingLeft,
331 /// Moves cursor right one character.
332 Right,
333 /// Moves cursor right one character, wrapping to next line.
334 #[action(deprecated_aliases = ["vim::Space"])]
335 WrappingRight,
336 /// Selects the current line.
337 CurrentLine,
338 /// Moves to the start of the next sentence.
339 SentenceForward,
340 /// Moves to the start of the previous sentence.
341 SentenceBackward,
342 /// Moves to the start of the paragraph.
343 StartOfParagraph,
344 /// Moves to the end of the paragraph.
345 EndOfParagraph,
346 /// Moves to the start of the document.
347 StartOfDocument,
348 /// Moves to the end of the document.
349 EndOfDocument,
350 /// Moves to the matching bracket or delimiter.
351 Matching,
352 /// Goes to a percentage position in the file.
353 GoToPercentage,
354 /// Moves to the start of the next line.
355 NextLineStart,
356 /// Moves to the start of the previous line.
357 PreviousLineStart,
358 /// Moves to the start of a line downward.
359 StartOfLineDownward,
360 /// Moves to the end of a line downward.
361 EndOfLineDownward,
362 /// Goes to a specific column number.
363 GoToColumn,
364 /// Repeats the last character find.
365 RepeatFind,
366 /// Repeats the last character find in reverse.
367 RepeatFindReversed,
368 /// Moves to the top of the window.
369 WindowTop,
370 /// Moves to the middle of the window.
371 WindowMiddle,
372 /// Moves to the bottom of the window.
373 WindowBottom,
374 /// Moves to the start of the next section.
375 NextSectionStart,
376 /// Moves to the end of the next section.
377 NextSectionEnd,
378 /// Moves to the start of the previous section.
379 PreviousSectionStart,
380 /// Moves to the end of the previous section.
381 PreviousSectionEnd,
382 /// Moves to the start of the next method.
383 NextMethodStart,
384 /// Moves to the end of the next method.
385 NextMethodEnd,
386 /// Moves to the start of the previous method.
387 PreviousMethodStart,
388 /// Moves to the end of the previous method.
389 PreviousMethodEnd,
390 /// Moves to the next comment.
391 NextComment,
392 /// Moves to the previous comment.
393 PreviousComment,
394 /// Moves to the previous line with lesser indentation.
395 PreviousLesserIndent,
396 /// Moves to the previous line with greater indentation.
397 PreviousGreaterIndent,
398 /// Moves to the previous line with the same indentation.
399 PreviousSameIndent,
400 /// Moves to the next line with lesser indentation.
401 NextLesserIndent,
402 /// Moves to the next line with greater indentation.
403 NextGreaterIndent,
404 /// Moves to the next line with the same indentation.
405 NextSameIndent,
406 ]
407);
408
409pub fn register(editor: &mut Editor, cx: &mut Context<Vim>) {
410 Vim::action(editor, cx, |vim, _: &Left, window, cx| {
411 vim.motion(Motion::Left, window, cx)
412 });
413 Vim::action(editor, cx, |vim, _: &WrappingLeft, window, cx| {
414 vim.motion(Motion::WrappingLeft, window, cx)
415 });
416 Vim::action(editor, cx, |vim, action: &Down, window, cx| {
417 vim.motion(
418 Motion::Down {
419 display_lines: action.display_lines,
420 },
421 window,
422 cx,
423 )
424 });
425 Vim::action(editor, cx, |vim, action: &Up, window, cx| {
426 vim.motion(
427 Motion::Up {
428 display_lines: action.display_lines,
429 },
430 window,
431 cx,
432 )
433 });
434 Vim::action(editor, cx, |vim, _: &Right, window, cx| {
435 vim.motion(Motion::Right, window, cx)
436 });
437 Vim::action(editor, cx, |vim, _: &WrappingRight, window, cx| {
438 vim.motion(Motion::WrappingRight, window, cx)
439 });
440 Vim::action(
441 editor,
442 cx,
443 |vim, action: &FirstNonWhitespace, window, cx| {
444 vim.motion(
445 Motion::FirstNonWhitespace {
446 display_lines: action.display_lines,
447 },
448 window,
449 cx,
450 )
451 },
452 );
453 Vim::action(editor, cx, |vim, action: &StartOfLine, window, cx| {
454 vim.motion(
455 Motion::StartOfLine {
456 display_lines: action.display_lines,
457 },
458 window,
459 cx,
460 )
461 });
462 Vim::action(editor, cx, |vim, action: &MiddleOfLine, window, cx| {
463 vim.motion(
464 Motion::MiddleOfLine {
465 display_lines: action.display_lines,
466 },
467 window,
468 cx,
469 )
470 });
471 Vim::action(editor, cx, |vim, action: &EndOfLine, window, cx| {
472 vim.motion(
473 Motion::EndOfLine {
474 display_lines: action.display_lines,
475 },
476 window,
477 cx,
478 )
479 });
480 Vim::action(editor, cx, |vim, _: &CurrentLine, window, cx| {
481 vim.motion(Motion::CurrentLine, window, cx)
482 });
483 Vim::action(editor, cx, |vim, _: &StartOfParagraph, window, cx| {
484 vim.motion(Motion::StartOfParagraph, window, cx)
485 });
486 Vim::action(editor, cx, |vim, _: &EndOfParagraph, window, cx| {
487 vim.motion(Motion::EndOfParagraph, window, cx)
488 });
489
490 Vim::action(editor, cx, |vim, _: &SentenceForward, window, cx| {
491 vim.motion(Motion::SentenceForward, window, cx)
492 });
493 Vim::action(editor, cx, |vim, _: &SentenceBackward, window, cx| {
494 vim.motion(Motion::SentenceBackward, window, cx)
495 });
496 Vim::action(editor, cx, |vim, _: &StartOfDocument, window, cx| {
497 vim.motion(Motion::StartOfDocument, window, cx)
498 });
499 Vim::action(editor, cx, |vim, _: &EndOfDocument, window, cx| {
500 vim.motion(Motion::EndOfDocument, window, cx)
501 });
502 Vim::action(editor, cx, |vim, _: &Matching, window, cx| {
503 vim.motion(Motion::Matching, window, cx)
504 });
505 Vim::action(editor, cx, |vim, _: &GoToPercentage, window, cx| {
506 vim.motion(Motion::GoToPercentage, window, cx)
507 });
508 Vim::action(
509 editor,
510 cx,
511 |vim, &UnmatchedForward { char }: &UnmatchedForward, window, cx| {
512 vim.motion(Motion::UnmatchedForward { char }, window, cx)
513 },
514 );
515 Vim::action(
516 editor,
517 cx,
518 |vim, &UnmatchedBackward { char }: &UnmatchedBackward, window, cx| {
519 vim.motion(Motion::UnmatchedBackward { char }, window, cx)
520 },
521 );
522 Vim::action(
523 editor,
524 cx,
525 |vim, &NextWordStart { ignore_punctuation }: &NextWordStart, window, cx| {
526 vim.motion(Motion::NextWordStart { ignore_punctuation }, window, cx)
527 },
528 );
529 Vim::action(
530 editor,
531 cx,
532 |vim, &NextWordEnd { ignore_punctuation }: &NextWordEnd, window, cx| {
533 vim.motion(Motion::NextWordEnd { ignore_punctuation }, window, cx)
534 },
535 );
536 Vim::action(
537 editor,
538 cx,
539 |vim, &PreviousWordStart { ignore_punctuation }: &PreviousWordStart, window, cx| {
540 vim.motion(Motion::PreviousWordStart { ignore_punctuation }, window, cx)
541 },
542 );
543 Vim::action(
544 editor,
545 cx,
546 |vim, &PreviousWordEnd { ignore_punctuation }, window, cx| {
547 vim.motion(Motion::PreviousWordEnd { ignore_punctuation }, window, cx)
548 },
549 );
550 Vim::action(
551 editor,
552 cx,
553 |vim, &NextSubwordStart { ignore_punctuation }: &NextSubwordStart, window, cx| {
554 vim.motion(Motion::NextSubwordStart { ignore_punctuation }, window, cx)
555 },
556 );
557 Vim::action(
558 editor,
559 cx,
560 |vim, &NextSubwordEnd { ignore_punctuation }: &NextSubwordEnd, window, cx| {
561 vim.motion(Motion::NextSubwordEnd { ignore_punctuation }, window, cx)
562 },
563 );
564 Vim::action(
565 editor,
566 cx,
567 |vim, &PreviousSubwordStart { ignore_punctuation }: &PreviousSubwordStart, window, cx| {
568 vim.motion(
569 Motion::PreviousSubwordStart { ignore_punctuation },
570 window,
571 cx,
572 )
573 },
574 );
575 Vim::action(
576 editor,
577 cx,
578 |vim, &PreviousSubwordEnd { ignore_punctuation }, window, cx| {
579 vim.motion(
580 Motion::PreviousSubwordEnd { ignore_punctuation },
581 window,
582 cx,
583 )
584 },
585 );
586 Vim::action(editor, cx, |vim, &NextLineStart, window, cx| {
587 vim.motion(Motion::NextLineStart, window, cx)
588 });
589 Vim::action(editor, cx, |vim, &PreviousLineStart, window, cx| {
590 vim.motion(Motion::PreviousLineStart, window, cx)
591 });
592 Vim::action(editor, cx, |vim, &StartOfLineDownward, window, cx| {
593 vim.motion(Motion::StartOfLineDownward, window, cx)
594 });
595 Vim::action(editor, cx, |vim, &EndOfLineDownward, window, cx| {
596 vim.motion(Motion::EndOfLineDownward, window, cx)
597 });
598 Vim::action(editor, cx, |vim, &GoToColumn, window, cx| {
599 vim.motion(Motion::GoToColumn, window, cx)
600 });
601
602 Vim::action(editor, cx, |vim, _: &RepeatFind, window, cx| {
603 if let Some(last_find) = Vim::globals(cx).last_find.clone().map(Box::new) {
604 vim.motion(Motion::RepeatFind { last_find }, window, cx);
605 }
606 });
607
608 Vim::action(editor, cx, |vim, _: &RepeatFindReversed, window, cx| {
609 if let Some(last_find) = Vim::globals(cx).last_find.clone().map(Box::new) {
610 vim.motion(Motion::RepeatFindReversed { last_find }, window, cx);
611 }
612 });
613 Vim::action(editor, cx, |vim, &WindowTop, window, cx| {
614 vim.motion(Motion::WindowTop, window, cx)
615 });
616 Vim::action(editor, cx, |vim, &WindowMiddle, window, cx| {
617 vim.motion(Motion::WindowMiddle, window, cx)
618 });
619 Vim::action(editor, cx, |vim, &WindowBottom, window, cx| {
620 vim.motion(Motion::WindowBottom, window, cx)
621 });
622
623 Vim::action(editor, cx, |vim, &PreviousSectionStart, window, cx| {
624 vim.motion(Motion::PreviousSectionStart, window, cx)
625 });
626 Vim::action(editor, cx, |vim, &NextSectionStart, window, cx| {
627 vim.motion(Motion::NextSectionStart, window, cx)
628 });
629 Vim::action(editor, cx, |vim, &PreviousSectionEnd, window, cx| {
630 vim.motion(Motion::PreviousSectionEnd, window, cx)
631 });
632 Vim::action(editor, cx, |vim, &NextSectionEnd, window, cx| {
633 vim.motion(Motion::NextSectionEnd, window, cx)
634 });
635 Vim::action(editor, cx, |vim, &PreviousMethodStart, window, cx| {
636 vim.motion(Motion::PreviousMethodStart, window, cx)
637 });
638 Vim::action(editor, cx, |vim, &NextMethodStart, window, cx| {
639 vim.motion(Motion::NextMethodStart, window, cx)
640 });
641 Vim::action(editor, cx, |vim, &PreviousMethodEnd, window, cx| {
642 vim.motion(Motion::PreviousMethodEnd, window, cx)
643 });
644 Vim::action(editor, cx, |vim, &NextMethodEnd, window, cx| {
645 vim.motion(Motion::NextMethodEnd, window, cx)
646 });
647 Vim::action(editor, cx, |vim, &NextComment, window, cx| {
648 vim.motion(Motion::NextComment, window, cx)
649 });
650 Vim::action(editor, cx, |vim, &PreviousComment, window, cx| {
651 vim.motion(Motion::PreviousComment, window, cx)
652 });
653 Vim::action(editor, cx, |vim, &PreviousLesserIndent, window, cx| {
654 vim.motion(Motion::PreviousLesserIndent, window, cx)
655 });
656 Vim::action(editor, cx, |vim, &PreviousGreaterIndent, window, cx| {
657 vim.motion(Motion::PreviousGreaterIndent, window, cx)
658 });
659 Vim::action(editor, cx, |vim, &PreviousSameIndent, window, cx| {
660 vim.motion(Motion::PreviousSameIndent, window, cx)
661 });
662 Vim::action(editor, cx, |vim, &NextLesserIndent, window, cx| {
663 vim.motion(Motion::NextLesserIndent, window, cx)
664 });
665 Vim::action(editor, cx, |vim, &NextGreaterIndent, window, cx| {
666 vim.motion(Motion::NextGreaterIndent, window, cx)
667 });
668 Vim::action(editor, cx, |vim, &NextSameIndent, window, cx| {
669 vim.motion(Motion::NextSameIndent, window, cx)
670 });
671}
672
673impl Vim {
674 pub(crate) fn search_motion(&mut self, m: Motion, window: &mut Window, cx: &mut Context<Self>) {
675 if let Motion::ZedSearchResult {
676 prior_selections, ..
677 } = &m
678 {
679 match self.mode {
680 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
681 if !prior_selections.is_empty() {
682 self.update_editor(cx, |_, editor, cx| {
683 editor.change_selections(Default::default(), window, cx, |s| {
684 s.select_ranges(prior_selections.iter().cloned())
685 })
686 });
687 }
688 }
689 Mode::Normal | Mode::Replace | Mode::Insert => {
690 if self.active_operator().is_none() {
691 return;
692 }
693 }
694
695 Mode::HelixNormal => {}
696 }
697 }
698
699 self.motion(m, window, cx)
700 }
701
702 pub(crate) fn motion(&mut self, motion: Motion, window: &mut Window, cx: &mut Context<Self>) {
703 if let Some(Operator::FindForward { .. })
704 | Some(Operator::Sneak { .. })
705 | Some(Operator::SneakBackward { .. })
706 | Some(Operator::FindBackward { .. }) = self.active_operator()
707 {
708 self.pop_operator(window, cx);
709 }
710
711 let count = Vim::take_count(cx);
712 let forced_motion = Vim::take_forced_motion(cx);
713 let active_operator = self.active_operator();
714 let mut waiting_operator: Option<Operator> = None;
715 match self.mode {
716 Mode::Normal | Mode::Replace | Mode::Insert => {
717 if active_operator == Some(Operator::AddSurrounds { target: None }) {
718 waiting_operator = Some(Operator::AddSurrounds {
719 target: Some(SurroundsType::Motion(motion)),
720 });
721 } else {
722 self.normal_motion(motion, active_operator, count, forced_motion, window, cx)
723 }
724 }
725 Mode::Visual | Mode::VisualLine | Mode::VisualBlock => {
726 self.visual_motion(motion, count, window, cx)
727 }
728
729 Mode::HelixNormal => self.helix_normal_motion(motion, count, window, cx),
730 }
731 self.clear_operator(window, cx);
732 if let Some(operator) = waiting_operator {
733 self.push_operator(operator, window, cx);
734 Vim::globals(cx).pre_count = count
735 }
736 }
737}
738
739// Motion handling is specified here:
740// https://github.com/vim/vim/blob/master/runtime/doc/motion.txt
741impl Motion {
742 fn default_kind(&self) -> MotionKind {
743 use Motion::*;
744 match self {
745 Down { .. }
746 | Up { .. }
747 | StartOfDocument
748 | EndOfDocument
749 | CurrentLine
750 | NextLineStart
751 | PreviousLineStart
752 | StartOfLineDownward
753 | WindowTop
754 | WindowMiddle
755 | WindowBottom
756 | NextSectionStart
757 | NextSectionEnd
758 | PreviousSectionStart
759 | PreviousSectionEnd
760 | NextMethodStart
761 | NextMethodEnd
762 | PreviousMethodStart
763 | PreviousMethodEnd
764 | NextComment
765 | PreviousComment
766 | PreviousLesserIndent
767 | PreviousGreaterIndent
768 | PreviousSameIndent
769 | NextLesserIndent
770 | NextGreaterIndent
771 | NextSameIndent
772 | GoToPercentage
773 | Jump { line: true, .. } => MotionKind::Linewise,
774 EndOfLine { .. }
775 | EndOfLineDownward
776 | Matching
777 | FindForward { .. }
778 | NextWordEnd { .. }
779 | PreviousWordEnd { .. }
780 | NextSubwordEnd { .. }
781 | PreviousSubwordEnd { .. } => MotionKind::Inclusive,
782 Left
783 | WrappingLeft
784 | Right
785 | WrappingRight
786 | StartOfLine { .. }
787 | StartOfParagraph
788 | EndOfParagraph
789 | SentenceBackward
790 | SentenceForward
791 | GoToColumn
792 | MiddleOfLine { .. }
793 | UnmatchedForward { .. }
794 | UnmatchedBackward { .. }
795 | NextWordStart { .. }
796 | PreviousWordStart { .. }
797 | NextSubwordStart { .. }
798 | PreviousSubwordStart { .. }
799 | FirstNonWhitespace { .. }
800 | FindBackward { .. }
801 | Sneak { .. }
802 | SneakBackward { .. }
803 | Jump { .. }
804 | ZedSearchResult { .. } => MotionKind::Exclusive,
805 RepeatFind { last_find: motion } | RepeatFindReversed { last_find: motion } => {
806 motion.default_kind()
807 }
808 }
809 }
810
811 fn skip_exclusive_special_case(&self) -> bool {
812 matches!(self, Motion::WrappingLeft | Motion::WrappingRight)
813 }
814
815 pub(crate) fn push_to_jump_list(&self) -> bool {
816 use Motion::*;
817 match self {
818 CurrentLine
819 | Down { .. }
820 | EndOfLine { .. }
821 | EndOfLineDownward
822 | FindBackward { .. }
823 | FindForward { .. }
824 | FirstNonWhitespace { .. }
825 | GoToColumn
826 | Left
827 | MiddleOfLine { .. }
828 | NextLineStart
829 | NextSubwordEnd { .. }
830 | NextSubwordStart { .. }
831 | NextWordEnd { .. }
832 | NextWordStart { .. }
833 | PreviousLineStart
834 | PreviousSubwordEnd { .. }
835 | PreviousSubwordStart { .. }
836 | PreviousWordEnd { .. }
837 | PreviousWordStart { .. }
838 | RepeatFind { .. }
839 | RepeatFindReversed { .. }
840 | Right
841 | StartOfLine { .. }
842 | StartOfLineDownward
843 | Up { .. }
844 | WrappingLeft
845 | WrappingRight => false,
846 EndOfDocument
847 | EndOfParagraph
848 | GoToPercentage
849 | Jump { .. }
850 | Matching
851 | NextComment
852 | NextGreaterIndent
853 | NextLesserIndent
854 | NextMethodEnd
855 | NextMethodStart
856 | NextSameIndent
857 | NextSectionEnd
858 | NextSectionStart
859 | PreviousComment
860 | PreviousGreaterIndent
861 | PreviousLesserIndent
862 | PreviousMethodEnd
863 | PreviousMethodStart
864 | PreviousSameIndent
865 | PreviousSectionEnd
866 | PreviousSectionStart
867 | SentenceBackward
868 | SentenceForward
869 | Sneak { .. }
870 | SneakBackward { .. }
871 | StartOfDocument
872 | StartOfParagraph
873 | UnmatchedBackward { .. }
874 | UnmatchedForward { .. }
875 | WindowBottom
876 | WindowMiddle
877 | WindowTop
878 | ZedSearchResult { .. } => true,
879 }
880 }
881
882 pub fn infallible(&self) -> bool {
883 use Motion::*;
884 match self {
885 StartOfDocument | EndOfDocument | CurrentLine => true,
886 Down { .. }
887 | Up { .. }
888 | EndOfLine { .. }
889 | MiddleOfLine { .. }
890 | Matching
891 | UnmatchedForward { .. }
892 | UnmatchedBackward { .. }
893 | FindForward { .. }
894 | RepeatFind { .. }
895 | Left
896 | WrappingLeft
897 | Right
898 | WrappingRight
899 | StartOfLine { .. }
900 | StartOfParagraph
901 | EndOfParagraph
902 | SentenceBackward
903 | SentenceForward
904 | StartOfLineDownward
905 | EndOfLineDownward
906 | GoToColumn
907 | GoToPercentage
908 | NextWordStart { .. }
909 | NextWordEnd { .. }
910 | PreviousWordStart { .. }
911 | PreviousWordEnd { .. }
912 | NextSubwordStart { .. }
913 | NextSubwordEnd { .. }
914 | PreviousSubwordStart { .. }
915 | PreviousSubwordEnd { .. }
916 | FirstNonWhitespace { .. }
917 | FindBackward { .. }
918 | Sneak { .. }
919 | SneakBackward { .. }
920 | RepeatFindReversed { .. }
921 | WindowTop
922 | WindowMiddle
923 | WindowBottom
924 | NextLineStart
925 | PreviousLineStart
926 | ZedSearchResult { .. }
927 | NextSectionStart
928 | NextSectionEnd
929 | PreviousSectionStart
930 | PreviousSectionEnd
931 | NextMethodStart
932 | NextMethodEnd
933 | PreviousMethodStart
934 | PreviousMethodEnd
935 | NextComment
936 | PreviousComment
937 | PreviousLesserIndent
938 | PreviousGreaterIndent
939 | PreviousSameIndent
940 | NextLesserIndent
941 | NextGreaterIndent
942 | NextSameIndent
943 | Jump { .. } => false,
944 }
945 }
946
947 pub fn move_point(
948 &self,
949 map: &DisplaySnapshot,
950 point: DisplayPoint,
951 goal: SelectionGoal,
952 maybe_times: Option<usize>,
953 text_layout_details: &TextLayoutDetails,
954 ) -> Option<(DisplayPoint, SelectionGoal)> {
955 let times = maybe_times.unwrap_or(1);
956 use Motion::*;
957 let infallible = self.infallible();
958 let (new_point, goal) = match self {
959 Left => (left(map, point, times), SelectionGoal::None),
960 WrappingLeft => (wrapping_left(map, point, times), SelectionGoal::None),
961 Down {
962 display_lines: false,
963 } => up_down_buffer_rows(map, point, goal, times as isize, text_layout_details),
964 Down {
965 display_lines: true,
966 } => down_display(map, point, goal, times, text_layout_details),
967 Up {
968 display_lines: false,
969 } => up_down_buffer_rows(map, point, goal, 0 - times as isize, text_layout_details),
970 Up {
971 display_lines: true,
972 } => up_display(map, point, goal, times, text_layout_details),
973 Right => (right(map, point, times), SelectionGoal::None),
974 WrappingRight => (wrapping_right(map, point, times), SelectionGoal::None),
975 NextWordStart { ignore_punctuation } => (
976 next_word_start(map, point, *ignore_punctuation, times),
977 SelectionGoal::None,
978 ),
979 NextWordEnd { ignore_punctuation } => (
980 next_word_end(map, point, *ignore_punctuation, times, true, true),
981 SelectionGoal::None,
982 ),
983 PreviousWordStart { ignore_punctuation } => (
984 previous_word_start(map, point, *ignore_punctuation, times),
985 SelectionGoal::None,
986 ),
987 PreviousWordEnd { ignore_punctuation } => (
988 previous_word_end(map, point, *ignore_punctuation, times),
989 SelectionGoal::None,
990 ),
991 NextSubwordStart { ignore_punctuation } => (
992 next_subword_start(map, point, *ignore_punctuation, times),
993 SelectionGoal::None,
994 ),
995 NextSubwordEnd { ignore_punctuation } => (
996 next_subword_end(map, point, *ignore_punctuation, times, true),
997 SelectionGoal::None,
998 ),
999 PreviousSubwordStart { ignore_punctuation } => (
1000 previous_subword_start(map, point, *ignore_punctuation, times),
1001 SelectionGoal::None,
1002 ),
1003 PreviousSubwordEnd { ignore_punctuation } => (
1004 previous_subword_end(map, point, *ignore_punctuation, times),
1005 SelectionGoal::None,
1006 ),
1007 FirstNonWhitespace { display_lines } => (
1008 first_non_whitespace(map, *display_lines, point),
1009 SelectionGoal::None,
1010 ),
1011 StartOfLine { display_lines } => (
1012 start_of_line(map, *display_lines, point),
1013 SelectionGoal::None,
1014 ),
1015 MiddleOfLine { display_lines } => (
1016 middle_of_line(map, *display_lines, point, maybe_times),
1017 SelectionGoal::None,
1018 ),
1019 EndOfLine { display_lines } => (
1020 end_of_line(map, *display_lines, point, times),
1021 SelectionGoal::None,
1022 ),
1023 SentenceBackward => (sentence_backwards(map, point, times), SelectionGoal::None),
1024 SentenceForward => (sentence_forwards(map, point, times), SelectionGoal::None),
1025 StartOfParagraph => (
1026 movement::start_of_paragraph(map, point, times),
1027 SelectionGoal::None,
1028 ),
1029 EndOfParagraph => (
1030 map.clip_at_line_end(movement::end_of_paragraph(map, point, times)),
1031 SelectionGoal::None,
1032 ),
1033 CurrentLine => (next_line_end(map, point, times), SelectionGoal::None),
1034 StartOfDocument => (
1035 start_of_document(map, point, maybe_times),
1036 SelectionGoal::None,
1037 ),
1038 EndOfDocument => (
1039 end_of_document(map, point, maybe_times),
1040 SelectionGoal::None,
1041 ),
1042 Matching => (matching(map, point), SelectionGoal::None),
1043 GoToPercentage => (go_to_percentage(map, point, times), SelectionGoal::None),
1044 UnmatchedForward { char } => (
1045 unmatched_forward(map, point, *char, times),
1046 SelectionGoal::None,
1047 ),
1048 UnmatchedBackward { char } => (
1049 unmatched_backward(map, point, *char, times),
1050 SelectionGoal::None,
1051 ),
1052 // t f
1053 FindForward {
1054 before,
1055 char,
1056 mode,
1057 smartcase,
1058 } => {
1059 return find_forward(map, point, *before, *char, times, *mode, *smartcase)
1060 .map(|new_point| (new_point, SelectionGoal::None));
1061 }
1062 // T F
1063 FindBackward {
1064 after,
1065 char,
1066 mode,
1067 smartcase,
1068 } => (
1069 find_backward(map, point, *after, *char, times, *mode, *smartcase),
1070 SelectionGoal::None,
1071 ),
1072 Sneak {
1073 first_char,
1074 second_char,
1075 smartcase,
1076 } => {
1077 return sneak(map, point, *first_char, *second_char, times, *smartcase)
1078 .map(|new_point| (new_point, SelectionGoal::None));
1079 }
1080 SneakBackward {
1081 first_char,
1082 second_char,
1083 smartcase,
1084 } => {
1085 return sneak_backward(map, point, *first_char, *second_char, times, *smartcase)
1086 .map(|new_point| (new_point, SelectionGoal::None));
1087 }
1088 // ; -- repeat the last find done with t, f, T, F
1089 RepeatFind { last_find } => match **last_find {
1090 Motion::FindForward {
1091 before,
1092 char,
1093 mode,
1094 smartcase,
1095 } => {
1096 let mut new_point =
1097 find_forward(map, point, before, char, times, mode, smartcase);
1098 if new_point == Some(point) {
1099 new_point =
1100 find_forward(map, point, before, char, times + 1, mode, smartcase);
1101 }
1102
1103 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1104 }
1105
1106 Motion::FindBackward {
1107 after,
1108 char,
1109 mode,
1110 smartcase,
1111 } => {
1112 let mut new_point =
1113 find_backward(map, point, after, char, times, mode, smartcase);
1114 if new_point == point {
1115 new_point =
1116 find_backward(map, point, after, char, times + 1, mode, smartcase);
1117 }
1118
1119 (new_point, SelectionGoal::None)
1120 }
1121 Motion::Sneak {
1122 first_char,
1123 second_char,
1124 smartcase,
1125 } => {
1126 let mut new_point =
1127 sneak(map, point, first_char, second_char, times, smartcase);
1128 if new_point == Some(point) {
1129 new_point =
1130 sneak(map, point, first_char, second_char, times + 1, smartcase);
1131 }
1132
1133 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1134 }
1135
1136 Motion::SneakBackward {
1137 first_char,
1138 second_char,
1139 smartcase,
1140 } => {
1141 let mut new_point =
1142 sneak_backward(map, point, first_char, second_char, times, smartcase);
1143 if new_point == Some(point) {
1144 new_point = sneak_backward(
1145 map,
1146 point,
1147 first_char,
1148 second_char,
1149 times + 1,
1150 smartcase,
1151 );
1152 }
1153
1154 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1155 }
1156 _ => return None,
1157 },
1158 // , -- repeat the last find done with t, f, T, F, s, S, in opposite direction
1159 RepeatFindReversed { last_find } => match **last_find {
1160 Motion::FindForward {
1161 before,
1162 char,
1163 mode,
1164 smartcase,
1165 } => {
1166 let mut new_point =
1167 find_backward(map, point, before, char, times, mode, smartcase);
1168 if new_point == point {
1169 new_point =
1170 find_backward(map, point, before, char, times + 1, mode, smartcase);
1171 }
1172
1173 (new_point, SelectionGoal::None)
1174 }
1175
1176 Motion::FindBackward {
1177 after,
1178 char,
1179 mode,
1180 smartcase,
1181 } => {
1182 let mut new_point =
1183 find_forward(map, point, after, char, times, mode, smartcase);
1184 if new_point == Some(point) {
1185 new_point =
1186 find_forward(map, point, after, char, times + 1, mode, smartcase);
1187 }
1188
1189 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1190 }
1191
1192 Motion::Sneak {
1193 first_char,
1194 second_char,
1195 smartcase,
1196 } => {
1197 let mut new_point =
1198 sneak_backward(map, point, first_char, second_char, times, smartcase);
1199 if new_point == Some(point) {
1200 new_point = sneak_backward(
1201 map,
1202 point,
1203 first_char,
1204 second_char,
1205 times + 1,
1206 smartcase,
1207 );
1208 }
1209
1210 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1211 }
1212
1213 Motion::SneakBackward {
1214 first_char,
1215 second_char,
1216 smartcase,
1217 } => {
1218 let mut new_point =
1219 sneak(map, point, first_char, second_char, times, smartcase);
1220 if new_point == Some(point) {
1221 new_point =
1222 sneak(map, point, first_char, second_char, times + 1, smartcase);
1223 }
1224
1225 return new_point.map(|new_point| (new_point, SelectionGoal::None));
1226 }
1227 _ => return None,
1228 },
1229 NextLineStart => (next_line_start(map, point, times), SelectionGoal::None),
1230 PreviousLineStart => (previous_line_start(map, point, times), SelectionGoal::None),
1231 StartOfLineDownward => (next_line_start(map, point, times - 1), SelectionGoal::None),
1232 EndOfLineDownward => (last_non_whitespace(map, point, times), SelectionGoal::None),
1233 GoToColumn => (go_to_column(map, point, times), SelectionGoal::None),
1234 WindowTop => window_top(map, point, text_layout_details, times - 1),
1235 WindowMiddle => window_middle(map, point, text_layout_details),
1236 WindowBottom => window_bottom(map, point, text_layout_details, times - 1),
1237 Jump { line, anchor } => mark::jump_motion(map, *anchor, *line),
1238 ZedSearchResult { new_selections, .. } => {
1239 // There will be only one selection, as
1240 // Search::SelectNextMatch selects a single match.
1241 if let Some(new_selection) = new_selections.first() {
1242 (
1243 new_selection.start.to_display_point(map),
1244 SelectionGoal::None,
1245 )
1246 } else {
1247 return None;
1248 }
1249 }
1250 NextSectionStart => (
1251 section_motion(map, point, times, Direction::Next, true),
1252 SelectionGoal::None,
1253 ),
1254 NextSectionEnd => (
1255 section_motion(map, point, times, Direction::Next, false),
1256 SelectionGoal::None,
1257 ),
1258 PreviousSectionStart => (
1259 section_motion(map, point, times, Direction::Prev, true),
1260 SelectionGoal::None,
1261 ),
1262 PreviousSectionEnd => (
1263 section_motion(map, point, times, Direction::Prev, false),
1264 SelectionGoal::None,
1265 ),
1266
1267 NextMethodStart => (
1268 method_motion(map, point, times, Direction::Next, true),
1269 SelectionGoal::None,
1270 ),
1271 NextMethodEnd => (
1272 method_motion(map, point, times, Direction::Next, false),
1273 SelectionGoal::None,
1274 ),
1275 PreviousMethodStart => (
1276 method_motion(map, point, times, Direction::Prev, true),
1277 SelectionGoal::None,
1278 ),
1279 PreviousMethodEnd => (
1280 method_motion(map, point, times, Direction::Prev, false),
1281 SelectionGoal::None,
1282 ),
1283 NextComment => (
1284 comment_motion(map, point, times, Direction::Next),
1285 SelectionGoal::None,
1286 ),
1287 PreviousComment => (
1288 comment_motion(map, point, times, Direction::Prev),
1289 SelectionGoal::None,
1290 ),
1291 PreviousLesserIndent => (
1292 indent_motion(map, point, times, Direction::Prev, IndentType::Lesser),
1293 SelectionGoal::None,
1294 ),
1295 PreviousGreaterIndent => (
1296 indent_motion(map, point, times, Direction::Prev, IndentType::Greater),
1297 SelectionGoal::None,
1298 ),
1299 PreviousSameIndent => (
1300 indent_motion(map, point, times, Direction::Prev, IndentType::Same),
1301 SelectionGoal::None,
1302 ),
1303 NextLesserIndent => (
1304 indent_motion(map, point, times, Direction::Next, IndentType::Lesser),
1305 SelectionGoal::None,
1306 ),
1307 NextGreaterIndent => (
1308 indent_motion(map, point, times, Direction::Next, IndentType::Greater),
1309 SelectionGoal::None,
1310 ),
1311 NextSameIndent => (
1312 indent_motion(map, point, times, Direction::Next, IndentType::Same),
1313 SelectionGoal::None,
1314 ),
1315 };
1316 (new_point != point || infallible).then_some((new_point, goal))
1317 }
1318
1319 // Get the range value after self is applied to the specified selection.
1320 pub fn range(
1321 &self,
1322 map: &DisplaySnapshot,
1323 mut selection: Selection<DisplayPoint>,
1324 times: Option<usize>,
1325 text_layout_details: &TextLayoutDetails,
1326 forced_motion: bool,
1327 ) -> Option<(Range<DisplayPoint>, MotionKind)> {
1328 if let Motion::ZedSearchResult {
1329 prior_selections,
1330 new_selections,
1331 } = self
1332 {
1333 if let Some((prior_selection, new_selection)) =
1334 prior_selections.first().zip(new_selections.first())
1335 {
1336 let start = prior_selection
1337 .start
1338 .to_display_point(map)
1339 .min(new_selection.start.to_display_point(map));
1340 let end = new_selection
1341 .end
1342 .to_display_point(map)
1343 .max(prior_selection.end.to_display_point(map));
1344
1345 if start < end {
1346 return Some((start..end, MotionKind::Exclusive));
1347 } else {
1348 return Some((end..start, MotionKind::Exclusive));
1349 }
1350 } else {
1351 return None;
1352 }
1353 }
1354 let maybe_new_point = self.move_point(
1355 map,
1356 selection.head(),
1357 selection.goal,
1358 times,
1359 text_layout_details,
1360 );
1361
1362 let (new_head, goal) = match (maybe_new_point, forced_motion) {
1363 (Some((p, g)), _) => Some((p, g)),
1364 (None, false) => None,
1365 (None, true) => Some((selection.head(), selection.goal)),
1366 }?;
1367
1368 selection.set_head(new_head, goal);
1369
1370 let mut kind = match (self.default_kind(), forced_motion) {
1371 (MotionKind::Linewise, true) => MotionKind::Exclusive,
1372 (MotionKind::Exclusive, true) => MotionKind::Inclusive,
1373 (MotionKind::Inclusive, true) => MotionKind::Exclusive,
1374 (kind, false) => kind,
1375 };
1376
1377 if let Motion::NextWordStart {
1378 ignore_punctuation: _,
1379 } = self
1380 {
1381 // Another special case: When using the "w" motion in combination with an
1382 // operator and the last word moved over is at the end of a line, the end of
1383 // that word becomes the end of the operated text, not the first word in the
1384 // next line.
1385 let start = selection.start.to_point(map);
1386 let end = selection.end.to_point(map);
1387 let start_row = MultiBufferRow(selection.start.to_point(map).row);
1388 if end.row > start.row {
1389 selection.end = Point::new(start_row.0, map.buffer_snapshot.line_len(start_row))
1390 .to_display_point(map);
1391
1392 // a bit of a hack, we need `cw` on a blank line to not delete the newline,
1393 // but dw on a blank line should. The `Linewise` returned from this method
1394 // causes the `d` operator to include the trailing newline.
1395 if selection.start == selection.end {
1396 return Some((selection.start..selection.end, MotionKind::Linewise));
1397 }
1398 }
1399 } else if kind == MotionKind::Exclusive && !self.skip_exclusive_special_case() {
1400 let start_point = selection.start.to_point(map);
1401 let mut end_point = selection.end.to_point(map);
1402 let mut next_point = selection.end;
1403 *next_point.column_mut() += 1;
1404 next_point = map.clip_point(next_point, Bias::Right);
1405 if next_point.to_point(map) == end_point && forced_motion {
1406 selection.end = movement::saturating_left(map, selection.end);
1407 }
1408
1409 if end_point.row > start_point.row {
1410 let first_non_blank_of_start_row = map
1411 .line_indent_for_buffer_row(MultiBufferRow(start_point.row))
1412 .raw_len();
1413 // https://github.com/neovim/neovim/blob/ee143aaf65a0e662c42c636aa4a959682858b3e7/src/nvim/ops.c#L6178-L6203
1414 if end_point.column == 0 {
1415 // If the motion is exclusive and the end of the motion is in column 1, the
1416 // end of the motion is moved to the end of the previous line and the motion
1417 // becomes inclusive. Example: "}" moves to the first line after a paragraph,
1418 // but "d}" will not include that line.
1419 //
1420 // If the motion is exclusive, the end of the motion is in column 1 and the
1421 // start of the motion was at or before the first non-blank in the line, the
1422 // motion becomes linewise. Example: If a paragraph begins with some blanks
1423 // and you do "d}" while standing on the first non-blank, all the lines of
1424 // the paragraph are deleted, including the blanks.
1425 if start_point.column <= first_non_blank_of_start_row {
1426 kind = MotionKind::Linewise;
1427 } else {
1428 kind = MotionKind::Inclusive;
1429 }
1430 end_point.row -= 1;
1431 end_point.column = 0;
1432 selection.end = map.clip_point(map.next_line_boundary(end_point).1, Bias::Left);
1433 } else if let Motion::EndOfParagraph = self {
1434 // Special case: When using the "}" motion, it's possible
1435 // that there's no blank lines after the paragraph the
1436 // cursor is currently on.
1437 // In this situation the `end_point.column` value will be
1438 // greater than 0, so the selection doesn't actually end on
1439 // the first character of a blank line. In that case, we'll
1440 // want to move one column to the right, to actually include
1441 // all characters of the last non-blank line.
1442 selection.end = movement::saturating_right(map, selection.end)
1443 }
1444 }
1445 } else if kind == MotionKind::Inclusive {
1446 selection.end = movement::saturating_right(map, selection.end)
1447 }
1448
1449 if kind == MotionKind::Linewise {
1450 selection.start = map.prev_line_boundary(selection.start.to_point(map)).1;
1451 selection.end = map.next_line_boundary(selection.end.to_point(map)).1;
1452 }
1453 Some((selection.start..selection.end, kind))
1454 }
1455
1456 // Expands a selection using self for an operator
1457 pub fn expand_selection(
1458 &self,
1459 map: &DisplaySnapshot,
1460 selection: &mut Selection<DisplayPoint>,
1461 times: Option<usize>,
1462 text_layout_details: &TextLayoutDetails,
1463 forced_motion: bool,
1464 ) -> Option<MotionKind> {
1465 let (range, kind) = self.range(
1466 map,
1467 selection.clone(),
1468 times,
1469 text_layout_details,
1470 forced_motion,
1471 )?;
1472 selection.start = range.start;
1473 selection.end = range.end;
1474 Some(kind)
1475 }
1476}
1477
1478fn left(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
1479 for _ in 0..times {
1480 point = movement::saturating_left(map, point);
1481 if point.column() == 0 {
1482 break;
1483 }
1484 }
1485 point
1486}
1487
1488pub(crate) fn wrapping_left(
1489 map: &DisplaySnapshot,
1490 mut point: DisplayPoint,
1491 times: usize,
1492) -> DisplayPoint {
1493 for _ in 0..times {
1494 point = movement::left(map, point);
1495 if point.is_zero() {
1496 break;
1497 }
1498 }
1499 point
1500}
1501
1502fn wrapping_right(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
1503 for _ in 0..times {
1504 point = wrapping_right_single(map, point);
1505 if point == map.max_point() {
1506 break;
1507 }
1508 }
1509 point
1510}
1511
1512fn wrapping_right_single(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
1513 let mut next_point = point;
1514 *next_point.column_mut() += 1;
1515 next_point = map.clip_point(next_point, Bias::Right);
1516 if next_point == point {
1517 if next_point.row() == map.max_point().row() {
1518 next_point
1519 } else {
1520 DisplayPoint::new(next_point.row().next_row(), 0)
1521 }
1522 } else {
1523 next_point
1524 }
1525}
1526
1527pub(crate) fn start_of_relative_buffer_row(
1528 map: &DisplaySnapshot,
1529 point: DisplayPoint,
1530 times: isize,
1531) -> DisplayPoint {
1532 let start = map.display_point_to_fold_point(point, Bias::Left);
1533 let target = start.row() as isize + times;
1534 let new_row = (target.max(0) as u32).min(map.fold_snapshot.max_point().row());
1535
1536 map.clip_point(
1537 map.fold_point_to_display_point(
1538 map.fold_snapshot
1539 .clip_point(FoldPoint::new(new_row, 0), Bias::Right),
1540 ),
1541 Bias::Right,
1542 )
1543}
1544
1545fn up_down_buffer_rows(
1546 map: &DisplaySnapshot,
1547 mut point: DisplayPoint,
1548 mut goal: SelectionGoal,
1549 mut times: isize,
1550 text_layout_details: &TextLayoutDetails,
1551) -> (DisplayPoint, SelectionGoal) {
1552 let bias = if times < 0 { Bias::Left } else { Bias::Right };
1553
1554 while map.is_folded_buffer_header(point.row()) {
1555 if times < 0 {
1556 (point, _) = movement::up(map, point, goal, true, text_layout_details);
1557 times += 1;
1558 } else if times > 0 {
1559 (point, _) = movement::down(map, point, goal, true, text_layout_details);
1560 times -= 1;
1561 } else {
1562 break;
1563 }
1564 }
1565
1566 let start = map.display_point_to_fold_point(point, Bias::Left);
1567 let begin_folded_line = map.fold_point_to_display_point(
1568 map.fold_snapshot
1569 .clip_point(FoldPoint::new(start.row(), 0), Bias::Left),
1570 );
1571 let select_nth_wrapped_row = point.row().0 - begin_folded_line.row().0;
1572
1573 let (goal_wrap, goal_x) = match goal {
1574 SelectionGoal::WrappedHorizontalPosition((row, x)) => (row, x),
1575 SelectionGoal::HorizontalRange { end, .. } => (select_nth_wrapped_row, end),
1576 SelectionGoal::HorizontalPosition(x) => (select_nth_wrapped_row, x),
1577 _ => {
1578 let x = map.x_for_display_point(point, text_layout_details);
1579 goal = SelectionGoal::WrappedHorizontalPosition((select_nth_wrapped_row, x.0));
1580 (select_nth_wrapped_row, x.0)
1581 }
1582 };
1583
1584 let target = start.row() as isize + times;
1585 let new_row = (target.max(0) as u32).min(map.fold_snapshot.max_point().row());
1586
1587 let mut begin_folded_line = map.fold_point_to_display_point(
1588 map.fold_snapshot
1589 .clip_point(FoldPoint::new(new_row, 0), bias),
1590 );
1591
1592 let mut i = 0;
1593 while i < goal_wrap && begin_folded_line.row() < map.max_point().row() {
1594 let next_folded_line = DisplayPoint::new(begin_folded_line.row().next_row(), 0);
1595 if map
1596 .display_point_to_fold_point(next_folded_line, bias)
1597 .row()
1598 == new_row
1599 {
1600 i += 1;
1601 begin_folded_line = next_folded_line;
1602 } else {
1603 break;
1604 }
1605 }
1606
1607 let new_col = if i == goal_wrap {
1608 map.display_column_for_x(begin_folded_line.row(), px(goal_x), text_layout_details)
1609 } else {
1610 map.line_len(begin_folded_line.row())
1611 };
1612
1613 (
1614 map.clip_point(DisplayPoint::new(begin_folded_line.row(), new_col), bias),
1615 goal,
1616 )
1617}
1618
1619fn down_display(
1620 map: &DisplaySnapshot,
1621 mut point: DisplayPoint,
1622 mut goal: SelectionGoal,
1623 times: usize,
1624 text_layout_details: &TextLayoutDetails,
1625) -> (DisplayPoint, SelectionGoal) {
1626 for _ in 0..times {
1627 (point, goal) = movement::down(map, point, goal, true, text_layout_details);
1628 }
1629
1630 (point, goal)
1631}
1632
1633fn up_display(
1634 map: &DisplaySnapshot,
1635 mut point: DisplayPoint,
1636 mut goal: SelectionGoal,
1637 times: usize,
1638 text_layout_details: &TextLayoutDetails,
1639) -> (DisplayPoint, SelectionGoal) {
1640 for _ in 0..times {
1641 (point, goal) = movement::up(map, point, goal, true, text_layout_details);
1642 }
1643
1644 (point, goal)
1645}
1646
1647pub(crate) fn right(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
1648 for _ in 0..times {
1649 let new_point = movement::saturating_right(map, point);
1650 if point == new_point {
1651 break;
1652 }
1653 point = new_point;
1654 }
1655 point
1656}
1657
1658pub(crate) fn next_char(
1659 map: &DisplaySnapshot,
1660 point: DisplayPoint,
1661 allow_cross_newline: bool,
1662) -> DisplayPoint {
1663 let mut new_point = point;
1664 let mut max_column = map.line_len(new_point.row());
1665 if !allow_cross_newline {
1666 max_column -= 1;
1667 }
1668 if new_point.column() < max_column {
1669 *new_point.column_mut() += 1;
1670 } else if new_point < map.max_point() && allow_cross_newline {
1671 *new_point.row_mut() += 1;
1672 *new_point.column_mut() = 0;
1673 }
1674 map.clip_ignoring_line_ends(new_point, Bias::Right)
1675}
1676
1677pub(crate) fn next_word_start(
1678 map: &DisplaySnapshot,
1679 mut point: DisplayPoint,
1680 ignore_punctuation: bool,
1681 times: usize,
1682) -> DisplayPoint {
1683 let classifier = map
1684 .buffer_snapshot
1685 .char_classifier_at(point.to_point(map))
1686 .ignore_punctuation(ignore_punctuation);
1687 for _ in 0..times {
1688 let mut crossed_newline = false;
1689 let new_point = movement::find_boundary(map, point, FindRange::MultiLine, |left, right| {
1690 let left_kind = classifier.kind(left);
1691 let right_kind = classifier.kind(right);
1692 let at_newline = right == '\n';
1693
1694 let found = (left_kind != right_kind && right_kind != CharKind::Whitespace)
1695 || at_newline && crossed_newline
1696 || at_newline && left == '\n'; // Prevents skipping repeated empty lines
1697
1698 crossed_newline |= at_newline;
1699 found
1700 });
1701 if point == new_point {
1702 break;
1703 }
1704 point = new_point;
1705 }
1706 point
1707}
1708
1709pub(crate) fn next_word_end(
1710 map: &DisplaySnapshot,
1711 mut point: DisplayPoint,
1712 ignore_punctuation: bool,
1713 times: usize,
1714 allow_cross_newline: bool,
1715 always_advance: bool,
1716) -> DisplayPoint {
1717 let classifier = map
1718 .buffer_snapshot
1719 .char_classifier_at(point.to_point(map))
1720 .ignore_punctuation(ignore_punctuation);
1721 for _ in 0..times {
1722 let mut need_next_char = false;
1723 let new_point = if always_advance {
1724 next_char(map, point, allow_cross_newline)
1725 } else {
1726 point
1727 };
1728 let new_point = movement::find_boundary_exclusive(
1729 map,
1730 new_point,
1731 FindRange::MultiLine,
1732 |left, right| {
1733 let left_kind = classifier.kind(left);
1734 let right_kind = classifier.kind(right);
1735 let at_newline = right == '\n';
1736
1737 if !allow_cross_newline && at_newline {
1738 need_next_char = true;
1739 return true;
1740 }
1741
1742 left_kind != right_kind && left_kind != CharKind::Whitespace
1743 },
1744 );
1745 let new_point = if need_next_char {
1746 next_char(map, new_point, true)
1747 } else {
1748 new_point
1749 };
1750 let new_point = map.clip_point(new_point, Bias::Left);
1751 if point == new_point {
1752 break;
1753 }
1754 point = new_point;
1755 }
1756 point
1757}
1758
1759fn previous_word_start(
1760 map: &DisplaySnapshot,
1761 mut point: DisplayPoint,
1762 ignore_punctuation: bool,
1763 times: usize,
1764) -> DisplayPoint {
1765 let classifier = map
1766 .buffer_snapshot
1767 .char_classifier_at(point.to_point(map))
1768 .ignore_punctuation(ignore_punctuation);
1769 for _ in 0..times {
1770 // This works even though find_preceding_boundary is called for every character in the line containing
1771 // cursor because the newline is checked only once.
1772 let new_point = movement::find_preceding_boundary_display_point(
1773 map,
1774 point,
1775 FindRange::MultiLine,
1776 |left, right| {
1777 let left_kind = classifier.kind(left);
1778 let right_kind = classifier.kind(right);
1779
1780 (left_kind != right_kind && !right.is_whitespace()) || left == '\n'
1781 },
1782 );
1783 if point == new_point {
1784 break;
1785 }
1786 point = new_point;
1787 }
1788 point
1789}
1790
1791fn previous_word_end(
1792 map: &DisplaySnapshot,
1793 point: DisplayPoint,
1794 ignore_punctuation: bool,
1795 times: usize,
1796) -> DisplayPoint {
1797 let classifier = map
1798 .buffer_snapshot
1799 .char_classifier_at(point.to_point(map))
1800 .ignore_punctuation(ignore_punctuation);
1801 let mut point = point.to_point(map);
1802
1803 if point.column < map.buffer_snapshot.line_len(MultiBufferRow(point.row))
1804 && let Some(ch) = map.buffer_snapshot.chars_at(point).next()
1805 {
1806 point.column += ch.len_utf8() as u32;
1807 }
1808 for _ in 0..times {
1809 let new_point = movement::find_preceding_boundary_point(
1810 &map.buffer_snapshot,
1811 point,
1812 FindRange::MultiLine,
1813 |left, right| {
1814 let left_kind = classifier.kind(left);
1815 let right_kind = classifier.kind(right);
1816 match (left_kind, right_kind) {
1817 (CharKind::Punctuation, CharKind::Whitespace)
1818 | (CharKind::Punctuation, CharKind::Word)
1819 | (CharKind::Word, CharKind::Whitespace)
1820 | (CharKind::Word, CharKind::Punctuation) => true,
1821 (CharKind::Whitespace, CharKind::Whitespace) => left == '\n' && right == '\n',
1822 _ => false,
1823 }
1824 },
1825 );
1826 if new_point == point {
1827 break;
1828 }
1829 point = new_point;
1830 }
1831 movement::saturating_left(map, point.to_display_point(map))
1832}
1833
1834fn next_subword_start(
1835 map: &DisplaySnapshot,
1836 mut point: DisplayPoint,
1837 ignore_punctuation: bool,
1838 times: usize,
1839) -> DisplayPoint {
1840 let classifier = map
1841 .buffer_snapshot
1842 .char_classifier_at(point.to_point(map))
1843 .ignore_punctuation(ignore_punctuation);
1844 for _ in 0..times {
1845 let mut crossed_newline = false;
1846 let new_point = movement::find_boundary(map, point, FindRange::MultiLine, |left, right| {
1847 let left_kind = classifier.kind(left);
1848 let right_kind = classifier.kind(right);
1849 let at_newline = right == '\n';
1850
1851 let is_word_start = (left_kind != right_kind) && !left.is_alphanumeric();
1852 let is_subword_start =
1853 left == '_' && right != '_' || left.is_lowercase() && right.is_uppercase();
1854
1855 let found = (!right.is_whitespace() && (is_word_start || is_subword_start))
1856 || at_newline && crossed_newline
1857 || at_newline && left == '\n'; // Prevents skipping repeated empty lines
1858
1859 crossed_newline |= at_newline;
1860 found
1861 });
1862 if point == new_point {
1863 break;
1864 }
1865 point = new_point;
1866 }
1867 point
1868}
1869
1870pub(crate) fn next_subword_end(
1871 map: &DisplaySnapshot,
1872 mut point: DisplayPoint,
1873 ignore_punctuation: bool,
1874 times: usize,
1875 allow_cross_newline: bool,
1876) -> DisplayPoint {
1877 let classifier = map
1878 .buffer_snapshot
1879 .char_classifier_at(point.to_point(map))
1880 .ignore_punctuation(ignore_punctuation);
1881 for _ in 0..times {
1882 let new_point = next_char(map, point, allow_cross_newline);
1883
1884 let mut crossed_newline = false;
1885 let mut need_backtrack = false;
1886 let new_point =
1887 movement::find_boundary(map, new_point, FindRange::MultiLine, |left, right| {
1888 let left_kind = classifier.kind(left);
1889 let right_kind = classifier.kind(right);
1890 let at_newline = right == '\n';
1891
1892 if !allow_cross_newline && at_newline {
1893 return true;
1894 }
1895
1896 let is_word_end = (left_kind != right_kind) && !right.is_alphanumeric();
1897 let is_subword_end =
1898 left != '_' && right == '_' || left.is_lowercase() && right.is_uppercase();
1899
1900 let found = !left.is_whitespace() && !at_newline && (is_word_end || is_subword_end);
1901
1902 if found && (is_word_end || is_subword_end) {
1903 need_backtrack = true;
1904 }
1905
1906 crossed_newline |= at_newline;
1907 found
1908 });
1909 let mut new_point = map.clip_point(new_point, Bias::Left);
1910 if need_backtrack {
1911 *new_point.column_mut() -= 1;
1912 }
1913 let new_point = map.clip_point(new_point, Bias::Left);
1914 if point == new_point {
1915 break;
1916 }
1917 point = new_point;
1918 }
1919 point
1920}
1921
1922fn previous_subword_start(
1923 map: &DisplaySnapshot,
1924 mut point: DisplayPoint,
1925 ignore_punctuation: bool,
1926 times: usize,
1927) -> DisplayPoint {
1928 let classifier = map
1929 .buffer_snapshot
1930 .char_classifier_at(point.to_point(map))
1931 .ignore_punctuation(ignore_punctuation);
1932 for _ in 0..times {
1933 let mut crossed_newline = false;
1934 // This works even though find_preceding_boundary is called for every character in the line containing
1935 // cursor because the newline is checked only once.
1936 let new_point = movement::find_preceding_boundary_display_point(
1937 map,
1938 point,
1939 FindRange::MultiLine,
1940 |left, right| {
1941 let left_kind = classifier.kind(left);
1942 let right_kind = classifier.kind(right);
1943 let at_newline = right == '\n';
1944
1945 let is_word_start = (left_kind != right_kind) && !left.is_alphanumeric();
1946 let is_subword_start =
1947 left == '_' && right != '_' || left.is_lowercase() && right.is_uppercase();
1948
1949 let found = (!right.is_whitespace() && (is_word_start || is_subword_start))
1950 || at_newline && crossed_newline
1951 || at_newline && left == '\n'; // Prevents skipping repeated empty lines
1952
1953 crossed_newline |= at_newline;
1954
1955 found
1956 },
1957 );
1958 if point == new_point {
1959 break;
1960 }
1961 point = new_point;
1962 }
1963 point
1964}
1965
1966fn previous_subword_end(
1967 map: &DisplaySnapshot,
1968 point: DisplayPoint,
1969 ignore_punctuation: bool,
1970 times: usize,
1971) -> DisplayPoint {
1972 let classifier = map
1973 .buffer_snapshot
1974 .char_classifier_at(point.to_point(map))
1975 .ignore_punctuation(ignore_punctuation);
1976 let mut point = point.to_point(map);
1977
1978 if point.column < map.buffer_snapshot.line_len(MultiBufferRow(point.row))
1979 && let Some(ch) = map.buffer_snapshot.chars_at(point).next()
1980 {
1981 point.column += ch.len_utf8() as u32;
1982 }
1983 for _ in 0..times {
1984 let new_point = movement::find_preceding_boundary_point(
1985 &map.buffer_snapshot,
1986 point,
1987 FindRange::MultiLine,
1988 |left, right| {
1989 let left_kind = classifier.kind(left);
1990 let right_kind = classifier.kind(right);
1991
1992 let is_subword_end =
1993 left != '_' && right == '_' || left.is_lowercase() && right.is_uppercase();
1994
1995 if is_subword_end {
1996 return true;
1997 }
1998
1999 match (left_kind, right_kind) {
2000 (CharKind::Word, CharKind::Whitespace)
2001 | (CharKind::Word, CharKind::Punctuation) => true,
2002 (CharKind::Whitespace, CharKind::Whitespace) => left == '\n' && right == '\n',
2003 _ => false,
2004 }
2005 },
2006 );
2007 if new_point == point {
2008 break;
2009 }
2010 point = new_point;
2011 }
2012 movement::saturating_left(map, point.to_display_point(map))
2013}
2014
2015pub(crate) fn first_non_whitespace(
2016 map: &DisplaySnapshot,
2017 display_lines: bool,
2018 from: DisplayPoint,
2019) -> DisplayPoint {
2020 let mut start_offset = start_of_line(map, display_lines, from).to_offset(map, Bias::Left);
2021 let classifier = map.buffer_snapshot.char_classifier_at(from.to_point(map));
2022 for (ch, offset) in map.buffer_chars_at(start_offset) {
2023 if ch == '\n' {
2024 return from;
2025 }
2026
2027 start_offset = offset;
2028
2029 if classifier.kind(ch) != CharKind::Whitespace {
2030 break;
2031 }
2032 }
2033
2034 start_offset.to_display_point(map)
2035}
2036
2037pub(crate) fn last_non_whitespace(
2038 map: &DisplaySnapshot,
2039 from: DisplayPoint,
2040 count: usize,
2041) -> DisplayPoint {
2042 let mut end_of_line = end_of_line(map, false, from, count).to_offset(map, Bias::Left);
2043 let classifier = map.buffer_snapshot.char_classifier_at(from.to_point(map));
2044
2045 // NOTE: depending on clip_at_line_end we may already be one char back from the end.
2046 if let Some((ch, _)) = map.buffer_chars_at(end_of_line).next()
2047 && classifier.kind(ch) != CharKind::Whitespace
2048 {
2049 return end_of_line.to_display_point(map);
2050 }
2051
2052 for (ch, offset) in map.reverse_buffer_chars_at(end_of_line) {
2053 if ch == '\n' {
2054 break;
2055 }
2056 end_of_line = offset;
2057 if classifier.kind(ch) != CharKind::Whitespace || ch == '\n' {
2058 break;
2059 }
2060 }
2061
2062 end_of_line.to_display_point(map)
2063}
2064
2065pub(crate) fn start_of_line(
2066 map: &DisplaySnapshot,
2067 display_lines: bool,
2068 point: DisplayPoint,
2069) -> DisplayPoint {
2070 if display_lines {
2071 map.clip_point(DisplayPoint::new(point.row(), 0), Bias::Right)
2072 } else {
2073 map.prev_line_boundary(point.to_point(map)).1
2074 }
2075}
2076
2077pub(crate) fn middle_of_line(
2078 map: &DisplaySnapshot,
2079 display_lines: bool,
2080 point: DisplayPoint,
2081 times: Option<usize>,
2082) -> DisplayPoint {
2083 let percent = if let Some(times) = times.filter(|&t| t <= 100) {
2084 times as f64 / 100.
2085 } else {
2086 0.5
2087 };
2088 if display_lines {
2089 map.clip_point(
2090 DisplayPoint::new(
2091 point.row(),
2092 (map.line_len(point.row()) as f64 * percent) as u32,
2093 ),
2094 Bias::Left,
2095 )
2096 } else {
2097 let mut buffer_point = point.to_point(map);
2098 buffer_point.column = (map
2099 .buffer_snapshot
2100 .line_len(MultiBufferRow(buffer_point.row)) as f64
2101 * percent) as u32;
2102
2103 map.clip_point(buffer_point.to_display_point(map), Bias::Left)
2104 }
2105}
2106
2107pub(crate) fn end_of_line(
2108 map: &DisplaySnapshot,
2109 display_lines: bool,
2110 mut point: DisplayPoint,
2111 times: usize,
2112) -> DisplayPoint {
2113 if times > 1 {
2114 point = start_of_relative_buffer_row(map, point, times as isize - 1);
2115 }
2116 if display_lines {
2117 map.clip_point(
2118 DisplayPoint::new(point.row(), map.line_len(point.row())),
2119 Bias::Left,
2120 )
2121 } else {
2122 map.clip_point(map.next_line_boundary(point.to_point(map)).1, Bias::Left)
2123 }
2124}
2125
2126pub(crate) fn sentence_backwards(
2127 map: &DisplaySnapshot,
2128 point: DisplayPoint,
2129 mut times: usize,
2130) -> DisplayPoint {
2131 let mut start = point.to_point(map).to_offset(&map.buffer_snapshot);
2132 let mut chars = map.reverse_buffer_chars_at(start).peekable();
2133
2134 let mut was_newline = map
2135 .buffer_chars_at(start)
2136 .next()
2137 .is_some_and(|(c, _)| c == '\n');
2138
2139 while let Some((ch, offset)) = chars.next() {
2140 let start_of_next_sentence = if was_newline && ch == '\n' {
2141 Some(offset + ch.len_utf8())
2142 } else if ch == '\n' && chars.peek().is_some_and(|(c, _)| *c == '\n') {
2143 Some(next_non_blank(map, offset + ch.len_utf8()))
2144 } else if ch == '.' || ch == '?' || ch == '!' {
2145 start_of_next_sentence(map, offset + ch.len_utf8())
2146 } else {
2147 None
2148 };
2149
2150 if let Some(start_of_next_sentence) = start_of_next_sentence {
2151 if start_of_next_sentence < start {
2152 times = times.saturating_sub(1);
2153 }
2154 if times == 0 || offset == 0 {
2155 return map.clip_point(
2156 start_of_next_sentence
2157 .to_offset(&map.buffer_snapshot)
2158 .to_display_point(map),
2159 Bias::Left,
2160 );
2161 }
2162 }
2163 if was_newline {
2164 start = offset;
2165 }
2166 was_newline = ch == '\n';
2167 }
2168
2169 DisplayPoint::zero()
2170}
2171
2172pub(crate) fn sentence_forwards(
2173 map: &DisplaySnapshot,
2174 point: DisplayPoint,
2175 mut times: usize,
2176) -> DisplayPoint {
2177 let start = point.to_point(map).to_offset(&map.buffer_snapshot);
2178 let mut chars = map.buffer_chars_at(start).peekable();
2179
2180 let mut was_newline = map
2181 .reverse_buffer_chars_at(start)
2182 .next()
2183 .is_some_and(|(c, _)| c == '\n')
2184 && chars.peek().is_some_and(|(c, _)| *c == '\n');
2185
2186 while let Some((ch, offset)) = chars.next() {
2187 if was_newline && ch == '\n' {
2188 continue;
2189 }
2190 let start_of_next_sentence = if was_newline {
2191 Some(next_non_blank(map, offset))
2192 } else if ch == '\n' && chars.peek().is_some_and(|(c, _)| *c == '\n') {
2193 Some(next_non_blank(map, offset + ch.len_utf8()))
2194 } else if ch == '.' || ch == '?' || ch == '!' {
2195 start_of_next_sentence(map, offset + ch.len_utf8())
2196 } else {
2197 None
2198 };
2199
2200 if let Some(start_of_next_sentence) = start_of_next_sentence {
2201 times = times.saturating_sub(1);
2202 if times == 0 {
2203 return map.clip_point(
2204 start_of_next_sentence
2205 .to_offset(&map.buffer_snapshot)
2206 .to_display_point(map),
2207 Bias::Right,
2208 );
2209 }
2210 }
2211
2212 was_newline = ch == '\n' && chars.peek().is_some_and(|(c, _)| *c == '\n');
2213 }
2214
2215 map.max_point()
2216}
2217
2218fn next_non_blank(map: &DisplaySnapshot, start: usize) -> usize {
2219 for (c, o) in map.buffer_chars_at(start) {
2220 if c == '\n' || !c.is_whitespace() {
2221 return o;
2222 }
2223 }
2224
2225 map.buffer_snapshot.len()
2226}
2227
2228// given the offset after a ., !, or ? find the start of the next sentence.
2229// if this is not a sentence boundary, returns None.
2230fn start_of_next_sentence(map: &DisplaySnapshot, end_of_sentence: usize) -> Option<usize> {
2231 let chars = map.buffer_chars_at(end_of_sentence);
2232 let mut seen_space = false;
2233
2234 for (char, offset) in chars {
2235 if !seen_space && (char == ')' || char == ']' || char == '"' || char == '\'') {
2236 continue;
2237 }
2238
2239 if char == '\n' && seen_space {
2240 return Some(offset);
2241 } else if char.is_whitespace() {
2242 seen_space = true;
2243 } else if seen_space {
2244 return Some(offset);
2245 } else {
2246 return None;
2247 }
2248 }
2249
2250 Some(map.buffer_snapshot.len())
2251}
2252
2253fn go_to_line(map: &DisplaySnapshot, display_point: DisplayPoint, line: usize) -> DisplayPoint {
2254 let point = map.display_point_to_point(display_point, Bias::Left);
2255 let Some(mut excerpt) = map.buffer_snapshot.excerpt_containing(point..point) else {
2256 return display_point;
2257 };
2258 let offset = excerpt.buffer().point_to_offset(
2259 excerpt
2260 .buffer()
2261 .clip_point(Point::new((line - 1) as u32, point.column), Bias::Left),
2262 );
2263 let buffer_range = excerpt.buffer_range();
2264 if offset >= buffer_range.start && offset <= buffer_range.end {
2265 let point = map
2266 .buffer_snapshot
2267 .offset_to_point(excerpt.map_offset_from_buffer(offset));
2268 return map.clip_point(map.point_to_display_point(point, Bias::Left), Bias::Left);
2269 }
2270 let mut last_position = None;
2271 for (excerpt, buffer, range) in map.buffer_snapshot.excerpts() {
2272 let excerpt_range = language::ToOffset::to_offset(&range.context.start, buffer)
2273 ..language::ToOffset::to_offset(&range.context.end, buffer);
2274 if offset >= excerpt_range.start && offset <= excerpt_range.end {
2275 let text_anchor = buffer.anchor_after(offset);
2276 let anchor = Anchor::in_buffer(excerpt, buffer.remote_id(), text_anchor);
2277 return anchor.to_display_point(map);
2278 } else if offset <= excerpt_range.start {
2279 let anchor = Anchor::in_buffer(excerpt, buffer.remote_id(), range.context.start);
2280 return anchor.to_display_point(map);
2281 } else {
2282 last_position = Some(Anchor::in_buffer(
2283 excerpt,
2284 buffer.remote_id(),
2285 range.context.end,
2286 ));
2287 }
2288 }
2289
2290 let mut last_point = last_position.unwrap().to_point(&map.buffer_snapshot);
2291 last_point.column = point.column;
2292
2293 map.clip_point(
2294 map.point_to_display_point(
2295 map.buffer_snapshot.clip_point(point, Bias::Left),
2296 Bias::Left,
2297 ),
2298 Bias::Left,
2299 )
2300}
2301
2302fn start_of_document(
2303 map: &DisplaySnapshot,
2304 display_point: DisplayPoint,
2305 maybe_times: Option<usize>,
2306) -> DisplayPoint {
2307 if let Some(times) = maybe_times {
2308 return go_to_line(map, display_point, times);
2309 }
2310
2311 let point = map.display_point_to_point(display_point, Bias::Left);
2312 let mut first_point = Point::zero();
2313 first_point.column = point.column;
2314
2315 map.clip_point(
2316 map.point_to_display_point(
2317 map.buffer_snapshot.clip_point(first_point, Bias::Left),
2318 Bias::Left,
2319 ),
2320 Bias::Left,
2321 )
2322}
2323
2324fn end_of_document(
2325 map: &DisplaySnapshot,
2326 display_point: DisplayPoint,
2327 maybe_times: Option<usize>,
2328) -> DisplayPoint {
2329 if let Some(times) = maybe_times {
2330 return go_to_line(map, display_point, times);
2331 };
2332 let point = map.display_point_to_point(display_point, Bias::Left);
2333 let mut last_point = map.buffer_snapshot.max_point();
2334 last_point.column = point.column;
2335
2336 map.clip_point(
2337 map.point_to_display_point(
2338 map.buffer_snapshot.clip_point(last_point, Bias::Left),
2339 Bias::Left,
2340 ),
2341 Bias::Left,
2342 )
2343}
2344
2345fn matching_tag(map: &DisplaySnapshot, head: DisplayPoint) -> Option<DisplayPoint> {
2346 let inner = crate::object::surrounding_html_tag(map, head, head..head, false)?;
2347 let outer = crate::object::surrounding_html_tag(map, head, head..head, true)?;
2348
2349 if head > outer.start && head < inner.start {
2350 let mut offset = inner.end.to_offset(map, Bias::Left);
2351 for c in map.buffer_snapshot.chars_at(offset) {
2352 if c == '/' || c == '\n' || c == '>' {
2353 return Some(offset.to_display_point(map));
2354 }
2355 offset += c.len_utf8();
2356 }
2357 } else {
2358 let mut offset = outer.start.to_offset(map, Bias::Left);
2359 for c in map.buffer_snapshot.chars_at(offset) {
2360 offset += c.len_utf8();
2361 if c == '<' || c == '\n' {
2362 return Some(offset.to_display_point(map));
2363 }
2364 }
2365 }
2366
2367 None
2368}
2369
2370fn matching(map: &DisplaySnapshot, display_point: DisplayPoint) -> DisplayPoint {
2371 // https://github.com/vim/vim/blob/1d87e11a1ef201b26ed87585fba70182ad0c468a/runtime/doc/motion.txt#L1200
2372 let display_point = map.clip_at_line_end(display_point);
2373 let point = display_point.to_point(map);
2374 let offset = point.to_offset(&map.buffer_snapshot);
2375
2376 // Ensure the range is contained by the current line.
2377 let mut line_end = map.next_line_boundary(point).0;
2378 if line_end == point {
2379 line_end = map.max_point().to_point(map);
2380 }
2381
2382 if let Some((opening_range, closing_range)) = map
2383 .buffer_snapshot
2384 .innermost_enclosing_bracket_ranges(offset..offset, None)
2385 {
2386 if opening_range.contains(&offset) {
2387 return closing_range.start.to_display_point(map);
2388 } else if closing_range.contains(&offset) {
2389 return opening_range.start.to_display_point(map);
2390 }
2391 }
2392
2393 let line_range = map.prev_line_boundary(point).0..line_end;
2394 let visible_line_range =
2395 line_range.start..Point::new(line_range.end.row, line_range.end.column.saturating_sub(1));
2396 let ranges = map.buffer_snapshot.bracket_ranges(visible_line_range);
2397 if let Some(ranges) = ranges {
2398 let line_range = line_range.start.to_offset(&map.buffer_snapshot)
2399 ..line_range.end.to_offset(&map.buffer_snapshot);
2400 let mut closest_pair_destination = None;
2401 let mut closest_distance = usize::MAX;
2402
2403 for (open_range, close_range) in ranges {
2404 if map.buffer_snapshot.chars_at(open_range.start).next() == Some('<') {
2405 if offset > open_range.start && offset < close_range.start {
2406 let mut chars = map.buffer_snapshot.chars_at(close_range.start);
2407 if (Some('/'), Some('>')) == (chars.next(), chars.next()) {
2408 return display_point;
2409 }
2410 if let Some(tag) = matching_tag(map, display_point) {
2411 return tag;
2412 }
2413 } else if close_range.contains(&offset) {
2414 return open_range.start.to_display_point(map);
2415 } else if open_range.contains(&offset) {
2416 return (close_range.end - 1).to_display_point(map);
2417 }
2418 }
2419
2420 if (open_range.contains(&offset) || open_range.start >= offset)
2421 && line_range.contains(&open_range.start)
2422 {
2423 let distance = open_range.start.saturating_sub(offset);
2424 if distance < closest_distance {
2425 closest_pair_destination = Some(close_range.start);
2426 closest_distance = distance;
2427 continue;
2428 }
2429 }
2430
2431 if (close_range.contains(&offset) || close_range.start >= offset)
2432 && line_range.contains(&close_range.start)
2433 {
2434 let distance = close_range.start.saturating_sub(offset);
2435 if distance < closest_distance {
2436 closest_pair_destination = Some(open_range.start);
2437 closest_distance = distance;
2438 continue;
2439 }
2440 }
2441
2442 continue;
2443 }
2444
2445 closest_pair_destination
2446 .map(|destination| destination.to_display_point(map))
2447 .unwrap_or(display_point)
2448 } else {
2449 display_point
2450 }
2451}
2452
2453// Go to {count} percentage in the file, on the first
2454// non-blank in the line linewise. To compute the new
2455// line number this formula is used:
2456// ({count} * number-of-lines + 99) / 100
2457//
2458// https://neovim.io/doc/user/motion.html#N%25
2459fn go_to_percentage(map: &DisplaySnapshot, point: DisplayPoint, count: usize) -> DisplayPoint {
2460 let total_lines = map.buffer_snapshot.max_point().row + 1;
2461 let target_line = (count * total_lines as usize).div_ceil(100);
2462 let target_point = DisplayPoint::new(
2463 DisplayRow(target_line.saturating_sub(1) as u32),
2464 point.column(),
2465 );
2466 map.clip_point(target_point, Bias::Left)
2467}
2468
2469fn unmatched_forward(
2470 map: &DisplaySnapshot,
2471 mut display_point: DisplayPoint,
2472 char: char,
2473 times: usize,
2474) -> DisplayPoint {
2475 for _ in 0..times {
2476 // https://github.com/vim/vim/blob/1d87e11a1ef201b26ed87585fba70182ad0c468a/runtime/doc/motion.txt#L1245
2477 let point = display_point.to_point(map);
2478 let offset = point.to_offset(&map.buffer_snapshot);
2479
2480 let ranges = map.buffer_snapshot.enclosing_bracket_ranges(point..point);
2481 let Some(ranges) = ranges else { break };
2482 let mut closest_closing_destination = None;
2483 let mut closest_distance = usize::MAX;
2484
2485 for (_, close_range) in ranges {
2486 if close_range.start > offset {
2487 let mut chars = map.buffer_snapshot.chars_at(close_range.start);
2488 if Some(char) == chars.next() {
2489 let distance = close_range.start - offset;
2490 if distance < closest_distance {
2491 closest_closing_destination = Some(close_range.start);
2492 closest_distance = distance;
2493 continue;
2494 }
2495 }
2496 }
2497 }
2498
2499 let new_point = closest_closing_destination
2500 .map(|destination| destination.to_display_point(map))
2501 .unwrap_or(display_point);
2502 if new_point == display_point {
2503 break;
2504 }
2505 display_point = new_point;
2506 }
2507 display_point
2508}
2509
2510fn unmatched_backward(
2511 map: &DisplaySnapshot,
2512 mut display_point: DisplayPoint,
2513 char: char,
2514 times: usize,
2515) -> DisplayPoint {
2516 for _ in 0..times {
2517 // https://github.com/vim/vim/blob/1d87e11a1ef201b26ed87585fba70182ad0c468a/runtime/doc/motion.txt#L1239
2518 let point = display_point.to_point(map);
2519 let offset = point.to_offset(&map.buffer_snapshot);
2520
2521 let ranges = map.buffer_snapshot.enclosing_bracket_ranges(point..point);
2522 let Some(ranges) = ranges else {
2523 break;
2524 };
2525
2526 let mut closest_starting_destination = None;
2527 let mut closest_distance = usize::MAX;
2528
2529 for (start_range, _) in ranges {
2530 if start_range.start < offset {
2531 let mut chars = map.buffer_snapshot.chars_at(start_range.start);
2532 if Some(char) == chars.next() {
2533 let distance = offset - start_range.start;
2534 if distance < closest_distance {
2535 closest_starting_destination = Some(start_range.start);
2536 closest_distance = distance;
2537 continue;
2538 }
2539 }
2540 }
2541 }
2542
2543 let new_point = closest_starting_destination
2544 .map(|destination| destination.to_display_point(map))
2545 .unwrap_or(display_point);
2546 if new_point == display_point {
2547 break;
2548 } else {
2549 display_point = new_point;
2550 }
2551 }
2552 display_point
2553}
2554
2555fn find_forward(
2556 map: &DisplaySnapshot,
2557 from: DisplayPoint,
2558 before: bool,
2559 target: char,
2560 times: usize,
2561 mode: FindRange,
2562 smartcase: bool,
2563) -> Option<DisplayPoint> {
2564 let mut to = from;
2565 let mut found = false;
2566
2567 for _ in 0..times {
2568 found = false;
2569 let new_to = find_boundary(map, to, mode, |_, right| {
2570 found = is_character_match(target, right, smartcase);
2571 found
2572 });
2573 if to == new_to {
2574 break;
2575 }
2576 to = new_to;
2577 }
2578
2579 if found {
2580 if before && to.column() > 0 {
2581 *to.column_mut() -= 1;
2582 Some(map.clip_point(to, Bias::Left))
2583 } else if before && to.row().0 > 0 {
2584 *to.row_mut() -= 1;
2585 *to.column_mut() = map.line(to.row()).len() as u32;
2586 Some(map.clip_point(to, Bias::Left))
2587 } else {
2588 Some(to)
2589 }
2590 } else {
2591 None
2592 }
2593}
2594
2595fn find_backward(
2596 map: &DisplaySnapshot,
2597 from: DisplayPoint,
2598 after: bool,
2599 target: char,
2600 times: usize,
2601 mode: FindRange,
2602 smartcase: bool,
2603) -> DisplayPoint {
2604 let mut to = from;
2605
2606 for _ in 0..times {
2607 let new_to = find_preceding_boundary_display_point(map, to, mode, |_, right| {
2608 is_character_match(target, right, smartcase)
2609 });
2610 if to == new_to {
2611 break;
2612 }
2613 to = new_to;
2614 }
2615
2616 let next = map.buffer_snapshot.chars_at(to.to_point(map)).next();
2617 if next.is_some() && is_character_match(target, next.unwrap(), smartcase) {
2618 if after {
2619 *to.column_mut() += 1;
2620 map.clip_point(to, Bias::Right)
2621 } else {
2622 to
2623 }
2624 } else {
2625 from
2626 }
2627}
2628
2629/// Returns true if one char is equal to the other or its uppercase variant (if smartcase is true).
2630pub fn is_character_match(target: char, other: char, smartcase: bool) -> bool {
2631 if smartcase {
2632 if target.is_uppercase() {
2633 target == other
2634 } else {
2635 target == other.to_ascii_lowercase()
2636 }
2637 } else {
2638 target == other
2639 }
2640}
2641
2642fn sneak(
2643 map: &DisplaySnapshot,
2644 from: DisplayPoint,
2645 first_target: char,
2646 second_target: char,
2647 times: usize,
2648 smartcase: bool,
2649) -> Option<DisplayPoint> {
2650 let mut to = from;
2651 let mut found = false;
2652
2653 for _ in 0..times {
2654 found = false;
2655 let new_to = find_boundary(
2656 map,
2657 movement::right(map, to),
2658 FindRange::MultiLine,
2659 |left, right| {
2660 found = is_character_match(first_target, left, smartcase)
2661 && is_character_match(second_target, right, smartcase);
2662 found
2663 },
2664 );
2665 if to == new_to {
2666 break;
2667 }
2668 to = new_to;
2669 }
2670
2671 if found {
2672 Some(movement::left(map, to))
2673 } else {
2674 None
2675 }
2676}
2677
2678fn sneak_backward(
2679 map: &DisplaySnapshot,
2680 from: DisplayPoint,
2681 first_target: char,
2682 second_target: char,
2683 times: usize,
2684 smartcase: bool,
2685) -> Option<DisplayPoint> {
2686 let mut to = from;
2687 let mut found = false;
2688
2689 for _ in 0..times {
2690 found = false;
2691 let new_to =
2692 find_preceding_boundary_display_point(map, to, FindRange::MultiLine, |left, right| {
2693 found = is_character_match(first_target, left, smartcase)
2694 && is_character_match(second_target, right, smartcase);
2695 found
2696 });
2697 if to == new_to {
2698 break;
2699 }
2700 to = new_to;
2701 }
2702
2703 if found {
2704 Some(movement::left(map, to))
2705 } else {
2706 None
2707 }
2708}
2709
2710fn next_line_start(map: &DisplaySnapshot, point: DisplayPoint, times: usize) -> DisplayPoint {
2711 let correct_line = start_of_relative_buffer_row(map, point, times as isize);
2712 first_non_whitespace(map, false, correct_line)
2713}
2714
2715fn previous_line_start(map: &DisplaySnapshot, point: DisplayPoint, times: usize) -> DisplayPoint {
2716 let correct_line = start_of_relative_buffer_row(map, point, -(times as isize));
2717 first_non_whitespace(map, false, correct_line)
2718}
2719
2720fn go_to_column(map: &DisplaySnapshot, point: DisplayPoint, times: usize) -> DisplayPoint {
2721 let correct_line = start_of_relative_buffer_row(map, point, 0);
2722 right(map, correct_line, times.saturating_sub(1))
2723}
2724
2725pub(crate) fn next_line_end(
2726 map: &DisplaySnapshot,
2727 mut point: DisplayPoint,
2728 times: usize,
2729) -> DisplayPoint {
2730 if times > 1 {
2731 point = start_of_relative_buffer_row(map, point, times as isize - 1);
2732 }
2733 end_of_line(map, false, point, 1)
2734}
2735
2736fn window_top(
2737 map: &DisplaySnapshot,
2738 point: DisplayPoint,
2739 text_layout_details: &TextLayoutDetails,
2740 mut times: usize,
2741) -> (DisplayPoint, SelectionGoal) {
2742 let first_visible_line = text_layout_details
2743 .scroll_anchor
2744 .anchor
2745 .to_display_point(map);
2746
2747 if first_visible_line.row() != DisplayRow(0)
2748 && text_layout_details.vertical_scroll_margin as usize > times
2749 {
2750 times = text_layout_details.vertical_scroll_margin.ceil() as usize;
2751 }
2752
2753 if let Some(visible_rows) = text_layout_details.visible_rows {
2754 let bottom_row = first_visible_line.row().0 + visible_rows as u32;
2755 let new_row = (first_visible_line.row().0 + (times as u32))
2756 .min(bottom_row)
2757 .min(map.max_point().row().0);
2758 let new_col = point.column().min(map.line_len(first_visible_line.row()));
2759
2760 let new_point = DisplayPoint::new(DisplayRow(new_row), new_col);
2761 (map.clip_point(new_point, Bias::Left), SelectionGoal::None)
2762 } else {
2763 let new_row =
2764 DisplayRow((first_visible_line.row().0 + (times as u32)).min(map.max_point().row().0));
2765 let new_col = point.column().min(map.line_len(first_visible_line.row()));
2766
2767 let new_point = DisplayPoint::new(new_row, new_col);
2768 (map.clip_point(new_point, Bias::Left), SelectionGoal::None)
2769 }
2770}
2771
2772fn window_middle(
2773 map: &DisplaySnapshot,
2774 point: DisplayPoint,
2775 text_layout_details: &TextLayoutDetails,
2776) -> (DisplayPoint, SelectionGoal) {
2777 if let Some(visible_rows) = text_layout_details.visible_rows {
2778 let first_visible_line = text_layout_details
2779 .scroll_anchor
2780 .anchor
2781 .to_display_point(map);
2782
2783 let max_visible_rows =
2784 (visible_rows as u32).min(map.max_point().row().0 - first_visible_line.row().0);
2785
2786 let new_row =
2787 (first_visible_line.row().0 + (max_visible_rows / 2)).min(map.max_point().row().0);
2788 let new_row = DisplayRow(new_row);
2789 let new_col = point.column().min(map.line_len(new_row));
2790 let new_point = DisplayPoint::new(new_row, new_col);
2791 (map.clip_point(new_point, Bias::Left), SelectionGoal::None)
2792 } else {
2793 (point, SelectionGoal::None)
2794 }
2795}
2796
2797fn window_bottom(
2798 map: &DisplaySnapshot,
2799 point: DisplayPoint,
2800 text_layout_details: &TextLayoutDetails,
2801 mut times: usize,
2802) -> (DisplayPoint, SelectionGoal) {
2803 if let Some(visible_rows) = text_layout_details.visible_rows {
2804 let first_visible_line = text_layout_details
2805 .scroll_anchor
2806 .anchor
2807 .to_display_point(map);
2808 let bottom_row = first_visible_line.row().0
2809 + (visible_rows + text_layout_details.scroll_anchor.offset.y - 1.).floor() as u32;
2810 if bottom_row < map.max_point().row().0
2811 && text_layout_details.vertical_scroll_margin as usize > times
2812 {
2813 times = text_layout_details.vertical_scroll_margin.ceil() as usize;
2814 }
2815 let bottom_row_capped = bottom_row.min(map.max_point().row().0);
2816 let new_row = if bottom_row_capped.saturating_sub(times as u32) < first_visible_line.row().0
2817 {
2818 first_visible_line.row()
2819 } else {
2820 DisplayRow(bottom_row_capped.saturating_sub(times as u32))
2821 };
2822 let new_col = point.column().min(map.line_len(new_row));
2823 let new_point = DisplayPoint::new(new_row, new_col);
2824 (map.clip_point(new_point, Bias::Left), SelectionGoal::None)
2825 } else {
2826 (point, SelectionGoal::None)
2827 }
2828}
2829
2830fn method_motion(
2831 map: &DisplaySnapshot,
2832 mut display_point: DisplayPoint,
2833 times: usize,
2834 direction: Direction,
2835 is_start: bool,
2836) -> DisplayPoint {
2837 let Some((_, _, buffer)) = map.buffer_snapshot.as_singleton() else {
2838 return display_point;
2839 };
2840
2841 for _ in 0..times {
2842 let point = map.display_point_to_point(display_point, Bias::Left);
2843 let offset = point.to_offset(&map.buffer_snapshot);
2844 let range = if direction == Direction::Prev {
2845 0..offset
2846 } else {
2847 offset..buffer.len()
2848 };
2849
2850 let possibilities = buffer
2851 .text_object_ranges(range, language::TreeSitterOptions::max_start_depth(4))
2852 .filter_map(|(range, object)| {
2853 if !matches!(object, language::TextObject::AroundFunction) {
2854 return None;
2855 }
2856
2857 let relevant = if is_start { range.start } else { range.end };
2858 if direction == Direction::Prev && relevant < offset {
2859 Some(relevant)
2860 } else if direction == Direction::Next && relevant > offset + 1 {
2861 Some(relevant)
2862 } else {
2863 None
2864 }
2865 });
2866
2867 let dest = if direction == Direction::Prev {
2868 possibilities.max().unwrap_or(offset)
2869 } else {
2870 possibilities.min().unwrap_or(offset)
2871 };
2872 let new_point = map.clip_point(dest.to_display_point(map), Bias::Left);
2873 if new_point == display_point {
2874 break;
2875 }
2876 display_point = new_point;
2877 }
2878 display_point
2879}
2880
2881fn comment_motion(
2882 map: &DisplaySnapshot,
2883 mut display_point: DisplayPoint,
2884 times: usize,
2885 direction: Direction,
2886) -> DisplayPoint {
2887 let Some((_, _, buffer)) = map.buffer_snapshot.as_singleton() else {
2888 return display_point;
2889 };
2890
2891 for _ in 0..times {
2892 let point = map.display_point_to_point(display_point, Bias::Left);
2893 let offset = point.to_offset(&map.buffer_snapshot);
2894 let range = if direction == Direction::Prev {
2895 0..offset
2896 } else {
2897 offset..buffer.len()
2898 };
2899
2900 let possibilities = buffer
2901 .text_object_ranges(range, language::TreeSitterOptions::max_start_depth(6))
2902 .filter_map(|(range, object)| {
2903 if !matches!(object, language::TextObject::AroundComment) {
2904 return None;
2905 }
2906
2907 let relevant = if direction == Direction::Prev {
2908 range.start
2909 } else {
2910 range.end
2911 };
2912 if direction == Direction::Prev && relevant < offset {
2913 Some(relevant)
2914 } else if direction == Direction::Next && relevant > offset + 1 {
2915 Some(relevant)
2916 } else {
2917 None
2918 }
2919 });
2920
2921 let dest = if direction == Direction::Prev {
2922 possibilities.max().unwrap_or(offset)
2923 } else {
2924 possibilities.min().unwrap_or(offset)
2925 };
2926 let new_point = map.clip_point(dest.to_display_point(map), Bias::Left);
2927 if new_point == display_point {
2928 break;
2929 }
2930 display_point = new_point;
2931 }
2932
2933 display_point
2934}
2935
2936fn section_motion(
2937 map: &DisplaySnapshot,
2938 mut display_point: DisplayPoint,
2939 times: usize,
2940 direction: Direction,
2941 is_start: bool,
2942) -> DisplayPoint {
2943 if map.buffer_snapshot.as_singleton().is_some() {
2944 for _ in 0..times {
2945 let offset = map
2946 .display_point_to_point(display_point, Bias::Left)
2947 .to_offset(&map.buffer_snapshot);
2948 let range = if direction == Direction::Prev {
2949 0..offset
2950 } else {
2951 offset..map.buffer_snapshot.len()
2952 };
2953
2954 // we set a max start depth here because we want a section to only be "top level"
2955 // similar to vim's default of '{' in the first column.
2956 // (and without it, ]] at the start of editor.rs is -very- slow)
2957 let mut possibilities = map
2958 .buffer_snapshot
2959 .text_object_ranges(range, language::TreeSitterOptions::max_start_depth(3))
2960 .filter(|(_, object)| {
2961 matches!(
2962 object,
2963 language::TextObject::AroundClass | language::TextObject::AroundFunction
2964 )
2965 })
2966 .collect::<Vec<_>>();
2967 possibilities.sort_by_key(|(range_a, _)| range_a.start);
2968 let mut prev_end = None;
2969 let possibilities = possibilities.into_iter().filter_map(|(range, t)| {
2970 if t == language::TextObject::AroundFunction
2971 && prev_end.is_some_and(|prev_end| prev_end > range.start)
2972 {
2973 return None;
2974 }
2975 prev_end = Some(range.end);
2976
2977 let relevant = if is_start { range.start } else { range.end };
2978 if direction == Direction::Prev && relevant < offset {
2979 Some(relevant)
2980 } else if direction == Direction::Next && relevant > offset + 1 {
2981 Some(relevant)
2982 } else {
2983 None
2984 }
2985 });
2986
2987 let offset = if direction == Direction::Prev {
2988 possibilities.max().unwrap_or(0)
2989 } else {
2990 possibilities.min().unwrap_or(map.buffer_snapshot.len())
2991 };
2992
2993 let new_point = map.clip_point(offset.to_display_point(map), Bias::Left);
2994 if new_point == display_point {
2995 break;
2996 }
2997 display_point = new_point;
2998 }
2999 return display_point;
3000 };
3001
3002 for _ in 0..times {
3003 let next_point = if is_start {
3004 movement::start_of_excerpt(map, display_point, direction)
3005 } else {
3006 movement::end_of_excerpt(map, display_point, direction)
3007 };
3008 if next_point == display_point {
3009 break;
3010 }
3011 display_point = next_point;
3012 }
3013
3014 display_point
3015}
3016
3017fn matches_indent_type(
3018 target_indent: &text::LineIndent,
3019 current_indent: &text::LineIndent,
3020 indent_type: IndentType,
3021) -> bool {
3022 match indent_type {
3023 IndentType::Lesser => {
3024 target_indent.spaces < current_indent.spaces || target_indent.tabs < current_indent.tabs
3025 }
3026 IndentType::Greater => {
3027 target_indent.spaces > current_indent.spaces || target_indent.tabs > current_indent.tabs
3028 }
3029 IndentType::Same => {
3030 target_indent.spaces == current_indent.spaces
3031 && target_indent.tabs == current_indent.tabs
3032 }
3033 }
3034}
3035
3036fn indent_motion(
3037 map: &DisplaySnapshot,
3038 mut display_point: DisplayPoint,
3039 times: usize,
3040 direction: Direction,
3041 indent_type: IndentType,
3042) -> DisplayPoint {
3043 let buffer_point = map.display_point_to_point(display_point, Bias::Left);
3044 let current_row = MultiBufferRow(buffer_point.row);
3045 let current_indent = map.line_indent_for_buffer_row(current_row);
3046 if current_indent.is_line_empty() {
3047 return display_point;
3048 }
3049 let max_row = map.max_point().to_point(map).row;
3050
3051 for _ in 0..times {
3052 let current_buffer_row = map.display_point_to_point(display_point, Bias::Left).row;
3053
3054 let target_row = match direction {
3055 Direction::Next => (current_buffer_row + 1..=max_row).find(|&row| {
3056 let indent = map.line_indent_for_buffer_row(MultiBufferRow(row));
3057 !indent.is_line_empty()
3058 && matches_indent_type(&indent, ¤t_indent, indent_type)
3059 }),
3060 Direction::Prev => (0..current_buffer_row).rev().find(|&row| {
3061 let indent = map.line_indent_for_buffer_row(MultiBufferRow(row));
3062 !indent.is_line_empty()
3063 && matches_indent_type(&indent, ¤t_indent, indent_type)
3064 }),
3065 }
3066 .unwrap_or(current_buffer_row);
3067
3068 let new_point = map.point_to_display_point(Point::new(target_row, 0), Bias::Right);
3069 let new_point = first_non_whitespace(map, false, new_point);
3070 if new_point == display_point {
3071 break;
3072 }
3073 display_point = new_point;
3074 }
3075 display_point
3076}
3077
3078#[cfg(test)]
3079mod test {
3080
3081 use crate::{
3082 state::Mode,
3083 test::{NeovimBackedTestContext, VimTestContext},
3084 };
3085 use editor::display_map::Inlay;
3086 use indoc::indoc;
3087 use language::Point;
3088 use multi_buffer::MultiBufferRow;
3089
3090 #[gpui::test]
3091 async fn test_start_end_of_paragraph(cx: &mut gpui::TestAppContext) {
3092 let mut cx = NeovimBackedTestContext::new(cx).await;
3093
3094 let initial_state = indoc! {r"ˇabc
3095 def
3096
3097 paragraph
3098 the second
3099
3100
3101
3102 third and
3103 final"};
3104
3105 // goes down once
3106 cx.set_shared_state(initial_state).await;
3107 cx.simulate_shared_keystrokes("}").await;
3108 cx.shared_state().await.assert_eq(indoc! {r"abc
3109 def
3110 ˇ
3111 paragraph
3112 the second
3113
3114
3115
3116 third and
3117 final"});
3118
3119 // goes up once
3120 cx.simulate_shared_keystrokes("{").await;
3121 cx.shared_state().await.assert_eq(initial_state);
3122
3123 // goes down twice
3124 cx.simulate_shared_keystrokes("2 }").await;
3125 cx.shared_state().await.assert_eq(indoc! {r"abc
3126 def
3127
3128 paragraph
3129 the second
3130 ˇ
3131
3132
3133 third and
3134 final"});
3135
3136 // goes down over multiple blanks
3137 cx.simulate_shared_keystrokes("}").await;
3138 cx.shared_state().await.assert_eq(indoc! {r"abc
3139 def
3140
3141 paragraph
3142 the second
3143
3144
3145
3146 third and
3147 finaˇl"});
3148
3149 // goes up twice
3150 cx.simulate_shared_keystrokes("2 {").await;
3151 cx.shared_state().await.assert_eq(indoc! {r"abc
3152 def
3153 ˇ
3154 paragraph
3155 the second
3156
3157
3158
3159 third and
3160 final"});
3161 }
3162
3163 #[gpui::test]
3164 async fn test_matching(cx: &mut gpui::TestAppContext) {
3165 let mut cx = NeovimBackedTestContext::new(cx).await;
3166
3167 cx.set_shared_state(indoc! {r"func ˇ(a string) {
3168 do(something(with<Types>.and_arrays[0, 2]))
3169 }"})
3170 .await;
3171 cx.simulate_shared_keystrokes("%").await;
3172 cx.shared_state()
3173 .await
3174 .assert_eq(indoc! {r"func (a stringˇ) {
3175 do(something(with<Types>.and_arrays[0, 2]))
3176 }"});
3177
3178 // test it works on the last character of the line
3179 cx.set_shared_state(indoc! {r"func (a string) ˇ{
3180 do(something(with<Types>.and_arrays[0, 2]))
3181 }"})
3182 .await;
3183 cx.simulate_shared_keystrokes("%").await;
3184 cx.shared_state()
3185 .await
3186 .assert_eq(indoc! {r"func (a string) {
3187 do(something(with<Types>.and_arrays[0, 2]))
3188 ˇ}"});
3189
3190 // test it works on immediate nesting
3191 cx.set_shared_state("ˇ{()}").await;
3192 cx.simulate_shared_keystrokes("%").await;
3193 cx.shared_state().await.assert_eq("{()ˇ}");
3194 cx.simulate_shared_keystrokes("%").await;
3195 cx.shared_state().await.assert_eq("ˇ{()}");
3196
3197 // test it works on immediate nesting inside braces
3198 cx.set_shared_state("{\n ˇ{()}\n}").await;
3199 cx.simulate_shared_keystrokes("%").await;
3200 cx.shared_state().await.assert_eq("{\n {()ˇ}\n}");
3201
3202 // test it jumps to the next paren on a line
3203 cx.set_shared_state("func ˇboop() {\n}").await;
3204 cx.simulate_shared_keystrokes("%").await;
3205 cx.shared_state().await.assert_eq("func boop(ˇ) {\n}");
3206 }
3207
3208 #[gpui::test]
3209 async fn test_unmatched_forward(cx: &mut gpui::TestAppContext) {
3210 let mut cx = NeovimBackedTestContext::new(cx).await;
3211
3212 // test it works with curly braces
3213 cx.set_shared_state(indoc! {r"func (a string) {
3214 do(something(with<Types>.anˇd_arrays[0, 2]))
3215 }"})
3216 .await;
3217 cx.simulate_shared_keystrokes("] }").await;
3218 cx.shared_state()
3219 .await
3220 .assert_eq(indoc! {r"func (a string) {
3221 do(something(with<Types>.and_arrays[0, 2]))
3222 ˇ}"});
3223
3224 // test it works with brackets
3225 cx.set_shared_state(indoc! {r"func (a string) {
3226 do(somethiˇng(with<Types>.and_arrays[0, 2]))
3227 }"})
3228 .await;
3229 cx.simulate_shared_keystrokes("] )").await;
3230 cx.shared_state()
3231 .await
3232 .assert_eq(indoc! {r"func (a string) {
3233 do(something(with<Types>.and_arrays[0, 2])ˇ)
3234 }"});
3235
3236 cx.set_shared_state(indoc! {r"func (a string) { a((b, cˇ))}"})
3237 .await;
3238 cx.simulate_shared_keystrokes("] )").await;
3239 cx.shared_state()
3240 .await
3241 .assert_eq(indoc! {r"func (a string) { a((b, c)ˇ)}"});
3242
3243 // test it works on immediate nesting
3244 cx.set_shared_state("{ˇ {}{}}").await;
3245 cx.simulate_shared_keystrokes("] }").await;
3246 cx.shared_state().await.assert_eq("{ {}{}ˇ}");
3247 cx.set_shared_state("(ˇ ()())").await;
3248 cx.simulate_shared_keystrokes("] )").await;
3249 cx.shared_state().await.assert_eq("( ()()ˇ)");
3250
3251 // test it works on immediate nesting inside braces
3252 cx.set_shared_state("{\n ˇ {()}\n}").await;
3253 cx.simulate_shared_keystrokes("] }").await;
3254 cx.shared_state().await.assert_eq("{\n {()}\nˇ}");
3255 cx.set_shared_state("(\n ˇ {()}\n)").await;
3256 cx.simulate_shared_keystrokes("] )").await;
3257 cx.shared_state().await.assert_eq("(\n {()}\nˇ)");
3258 }
3259
3260 #[gpui::test]
3261 async fn test_unmatched_backward(cx: &mut gpui::TestAppContext) {
3262 let mut cx = NeovimBackedTestContext::new(cx).await;
3263
3264 // test it works with curly braces
3265 cx.set_shared_state(indoc! {r"func (a string) {
3266 do(something(with<Types>.anˇd_arrays[0, 2]))
3267 }"})
3268 .await;
3269 cx.simulate_shared_keystrokes("[ {").await;
3270 cx.shared_state()
3271 .await
3272 .assert_eq(indoc! {r"func (a string) ˇ{
3273 do(something(with<Types>.and_arrays[0, 2]))
3274 }"});
3275
3276 // test it works with brackets
3277 cx.set_shared_state(indoc! {r"func (a string) {
3278 do(somethiˇng(with<Types>.and_arrays[0, 2]))
3279 }"})
3280 .await;
3281 cx.simulate_shared_keystrokes("[ (").await;
3282 cx.shared_state()
3283 .await
3284 .assert_eq(indoc! {r"func (a string) {
3285 doˇ(something(with<Types>.and_arrays[0, 2]))
3286 }"});
3287
3288 // test it works on immediate nesting
3289 cx.set_shared_state("{{}{} ˇ }").await;
3290 cx.simulate_shared_keystrokes("[ {").await;
3291 cx.shared_state().await.assert_eq("ˇ{{}{} }");
3292 cx.set_shared_state("(()() ˇ )").await;
3293 cx.simulate_shared_keystrokes("[ (").await;
3294 cx.shared_state().await.assert_eq("ˇ(()() )");
3295
3296 // test it works on immediate nesting inside braces
3297 cx.set_shared_state("{\n {()} ˇ\n}").await;
3298 cx.simulate_shared_keystrokes("[ {").await;
3299 cx.shared_state().await.assert_eq("ˇ{\n {()} \n}");
3300 cx.set_shared_state("(\n {()} ˇ\n)").await;
3301 cx.simulate_shared_keystrokes("[ (").await;
3302 cx.shared_state().await.assert_eq("ˇ(\n {()} \n)");
3303 }
3304
3305 #[gpui::test]
3306 async fn test_matching_tags(cx: &mut gpui::TestAppContext) {
3307 let mut cx = NeovimBackedTestContext::new_html(cx).await;
3308
3309 cx.neovim.exec("set filetype=html").await;
3310
3311 cx.set_shared_state(indoc! {r"<bˇody></body>"}).await;
3312 cx.simulate_shared_keystrokes("%").await;
3313 cx.shared_state()
3314 .await
3315 .assert_eq(indoc! {r"<body><ˇ/body>"});
3316 cx.simulate_shared_keystrokes("%").await;
3317
3318 // test jumping backwards
3319 cx.shared_state()
3320 .await
3321 .assert_eq(indoc! {r"<ˇbody></body>"});
3322
3323 // test self-closing tags
3324 cx.set_shared_state(indoc! {r"<a><bˇr/></a>"}).await;
3325 cx.simulate_shared_keystrokes("%").await;
3326 cx.shared_state().await.assert_eq(indoc! {r"<a><bˇr/></a>"});
3327
3328 // test tag with attributes
3329 cx.set_shared_state(indoc! {r"<div class='test' ˇid='main'>
3330 </div>
3331 "})
3332 .await;
3333 cx.simulate_shared_keystrokes("%").await;
3334 cx.shared_state()
3335 .await
3336 .assert_eq(indoc! {r"<div class='test' id='main'>
3337 <ˇ/div>
3338 "});
3339
3340 // test multi-line self-closing tag
3341 cx.set_shared_state(indoc! {r#"<a>
3342 <br
3343 test = "test"
3344 /ˇ>
3345 </a>"#})
3346 .await;
3347 cx.simulate_shared_keystrokes("%").await;
3348 cx.shared_state().await.assert_eq(indoc! {r#"<a>
3349 ˇ<br
3350 test = "test"
3351 />
3352 </a>"#});
3353 }
3354
3355 #[gpui::test]
3356 async fn test_matching_braces_in_tag(cx: &mut gpui::TestAppContext) {
3357 let mut cx = NeovimBackedTestContext::new_typescript(cx).await;
3358
3359 // test brackets within tags
3360 cx.set_shared_state(indoc! {r"function f() {
3361 return (
3362 <div rules={ˇ[{ a: 1 }]}>
3363 <h1>test</h1>
3364 </div>
3365 );
3366 }"})
3367 .await;
3368 cx.simulate_shared_keystrokes("%").await;
3369 cx.shared_state().await.assert_eq(indoc! {r"function f() {
3370 return (
3371 <div rules={[{ a: 1 }ˇ]}>
3372 <h1>test</h1>
3373 </div>
3374 );
3375 }"});
3376 }
3377
3378 #[gpui::test]
3379 async fn test_comma_semicolon(cx: &mut gpui::TestAppContext) {
3380 let mut cx = NeovimBackedTestContext::new(cx).await;
3381
3382 // f and F
3383 cx.set_shared_state("ˇone two three four").await;
3384 cx.simulate_shared_keystrokes("f o").await;
3385 cx.shared_state().await.assert_eq("one twˇo three four");
3386 cx.simulate_shared_keystrokes(",").await;
3387 cx.shared_state().await.assert_eq("ˇone two three four");
3388 cx.simulate_shared_keystrokes("2 ;").await;
3389 cx.shared_state().await.assert_eq("one two three fˇour");
3390 cx.simulate_shared_keystrokes("shift-f e").await;
3391 cx.shared_state().await.assert_eq("one two threˇe four");
3392 cx.simulate_shared_keystrokes("2 ;").await;
3393 cx.shared_state().await.assert_eq("onˇe two three four");
3394 cx.simulate_shared_keystrokes(",").await;
3395 cx.shared_state().await.assert_eq("one two thrˇee four");
3396
3397 // t and T
3398 cx.set_shared_state("ˇone two three four").await;
3399 cx.simulate_shared_keystrokes("t o").await;
3400 cx.shared_state().await.assert_eq("one tˇwo three four");
3401 cx.simulate_shared_keystrokes(",").await;
3402 cx.shared_state().await.assert_eq("oˇne two three four");
3403 cx.simulate_shared_keystrokes("2 ;").await;
3404 cx.shared_state().await.assert_eq("one two three ˇfour");
3405 cx.simulate_shared_keystrokes("shift-t e").await;
3406 cx.shared_state().await.assert_eq("one two threeˇ four");
3407 cx.simulate_shared_keystrokes("3 ;").await;
3408 cx.shared_state().await.assert_eq("oneˇ two three four");
3409 cx.simulate_shared_keystrokes(",").await;
3410 cx.shared_state().await.assert_eq("one two thˇree four");
3411 }
3412
3413 #[gpui::test]
3414 async fn test_next_word_end_newline_last_char(cx: &mut gpui::TestAppContext) {
3415 let mut cx = NeovimBackedTestContext::new(cx).await;
3416 let initial_state = indoc! {r"something(ˇfoo)"};
3417 cx.set_shared_state(initial_state).await;
3418 cx.simulate_shared_keystrokes("}").await;
3419 cx.shared_state().await.assert_eq("something(fooˇ)");
3420 }
3421
3422 #[gpui::test]
3423 async fn test_next_line_start(cx: &mut gpui::TestAppContext) {
3424 let mut cx = NeovimBackedTestContext::new(cx).await;
3425 cx.set_shared_state("ˇone\n two\nthree").await;
3426 cx.simulate_shared_keystrokes("enter").await;
3427 cx.shared_state().await.assert_eq("one\n ˇtwo\nthree");
3428 }
3429
3430 #[gpui::test]
3431 async fn test_end_of_line_downward(cx: &mut gpui::TestAppContext) {
3432 let mut cx = NeovimBackedTestContext::new(cx).await;
3433 cx.set_shared_state("ˇ one\n two \nthree").await;
3434 cx.simulate_shared_keystrokes("g _").await;
3435 cx.shared_state().await.assert_eq(" onˇe\n two \nthree");
3436
3437 cx.set_shared_state("ˇ one \n two \nthree").await;
3438 cx.simulate_shared_keystrokes("g _").await;
3439 cx.shared_state().await.assert_eq(" onˇe \n two \nthree");
3440 cx.simulate_shared_keystrokes("2 g _").await;
3441 cx.shared_state().await.assert_eq(" one \n twˇo \nthree");
3442 }
3443
3444 #[gpui::test]
3445 async fn test_window_top(cx: &mut gpui::TestAppContext) {
3446 let mut cx = NeovimBackedTestContext::new(cx).await;
3447 let initial_state = indoc! {r"abc
3448 def
3449 paragraph
3450 the second
3451 third ˇand
3452 final"};
3453
3454 cx.set_shared_state(initial_state).await;
3455 cx.simulate_shared_keystrokes("shift-h").await;
3456 cx.shared_state().await.assert_eq(indoc! {r"abˇc
3457 def
3458 paragraph
3459 the second
3460 third and
3461 final"});
3462
3463 // clip point
3464 cx.set_shared_state(indoc! {r"
3465 1 2 3
3466 4 5 6
3467 7 8 ˇ9
3468 "})
3469 .await;
3470 cx.simulate_shared_keystrokes("shift-h").await;
3471 cx.shared_state().await.assert_eq(indoc! {"
3472 1 2 ˇ3
3473 4 5 6
3474 7 8 9
3475 "});
3476
3477 cx.set_shared_state(indoc! {r"
3478 1 2 3
3479 4 5 6
3480 ˇ7 8 9
3481 "})
3482 .await;
3483 cx.simulate_shared_keystrokes("shift-h").await;
3484 cx.shared_state().await.assert_eq(indoc! {"
3485 ˇ1 2 3
3486 4 5 6
3487 7 8 9
3488 "});
3489
3490 cx.set_shared_state(indoc! {r"
3491 1 2 3
3492 4 5 ˇ6
3493 7 8 9"})
3494 .await;
3495 cx.simulate_shared_keystrokes("9 shift-h").await;
3496 cx.shared_state().await.assert_eq(indoc! {"
3497 1 2 3
3498 4 5 6
3499 7 8 ˇ9"});
3500 }
3501
3502 #[gpui::test]
3503 async fn test_window_middle(cx: &mut gpui::TestAppContext) {
3504 let mut cx = NeovimBackedTestContext::new(cx).await;
3505 let initial_state = indoc! {r"abˇc
3506 def
3507 paragraph
3508 the second
3509 third and
3510 final"};
3511
3512 cx.set_shared_state(initial_state).await;
3513 cx.simulate_shared_keystrokes("shift-m").await;
3514 cx.shared_state().await.assert_eq(indoc! {r"abc
3515 def
3516 paˇragraph
3517 the second
3518 third and
3519 final"});
3520
3521 cx.set_shared_state(indoc! {r"
3522 1 2 3
3523 4 5 6
3524 7 8 ˇ9
3525 "})
3526 .await;
3527 cx.simulate_shared_keystrokes("shift-m").await;
3528 cx.shared_state().await.assert_eq(indoc! {"
3529 1 2 3
3530 4 5 ˇ6
3531 7 8 9
3532 "});
3533 cx.set_shared_state(indoc! {r"
3534 1 2 3
3535 4 5 6
3536 ˇ7 8 9
3537 "})
3538 .await;
3539 cx.simulate_shared_keystrokes("shift-m").await;
3540 cx.shared_state().await.assert_eq(indoc! {"
3541 1 2 3
3542 ˇ4 5 6
3543 7 8 9
3544 "});
3545 cx.set_shared_state(indoc! {r"
3546 ˇ1 2 3
3547 4 5 6
3548 7 8 9
3549 "})
3550 .await;
3551 cx.simulate_shared_keystrokes("shift-m").await;
3552 cx.shared_state().await.assert_eq(indoc! {"
3553 1 2 3
3554 ˇ4 5 6
3555 7 8 9
3556 "});
3557 cx.set_shared_state(indoc! {r"
3558 1 2 3
3559 ˇ4 5 6
3560 7 8 9
3561 "})
3562 .await;
3563 cx.simulate_shared_keystrokes("shift-m").await;
3564 cx.shared_state().await.assert_eq(indoc! {"
3565 1 2 3
3566 ˇ4 5 6
3567 7 8 9
3568 "});
3569 cx.set_shared_state(indoc! {r"
3570 1 2 3
3571 4 5 ˇ6
3572 7 8 9
3573 "})
3574 .await;
3575 cx.simulate_shared_keystrokes("shift-m").await;
3576 cx.shared_state().await.assert_eq(indoc! {"
3577 1 2 3
3578 4 5 ˇ6
3579 7 8 9
3580 "});
3581 }
3582
3583 #[gpui::test]
3584 async fn test_window_bottom(cx: &mut gpui::TestAppContext) {
3585 let mut cx = NeovimBackedTestContext::new(cx).await;
3586 let initial_state = indoc! {r"abc
3587 deˇf
3588 paragraph
3589 the second
3590 third and
3591 final"};
3592
3593 cx.set_shared_state(initial_state).await;
3594 cx.simulate_shared_keystrokes("shift-l").await;
3595 cx.shared_state().await.assert_eq(indoc! {r"abc
3596 def
3597 paragraph
3598 the second
3599 third and
3600 fiˇnal"});
3601
3602 cx.set_shared_state(indoc! {r"
3603 1 2 3
3604 4 5 ˇ6
3605 7 8 9
3606 "})
3607 .await;
3608 cx.simulate_shared_keystrokes("shift-l").await;
3609 cx.shared_state().await.assert_eq(indoc! {"
3610 1 2 3
3611 4 5 6
3612 7 8 9
3613 ˇ"});
3614
3615 cx.set_shared_state(indoc! {r"
3616 1 2 3
3617 ˇ4 5 6
3618 7 8 9
3619 "})
3620 .await;
3621 cx.simulate_shared_keystrokes("shift-l").await;
3622 cx.shared_state().await.assert_eq(indoc! {"
3623 1 2 3
3624 4 5 6
3625 7 8 9
3626 ˇ"});
3627
3628 cx.set_shared_state(indoc! {r"
3629 1 2 ˇ3
3630 4 5 6
3631 7 8 9
3632 "})
3633 .await;
3634 cx.simulate_shared_keystrokes("shift-l").await;
3635 cx.shared_state().await.assert_eq(indoc! {"
3636 1 2 3
3637 4 5 6
3638 7 8 9
3639 ˇ"});
3640
3641 cx.set_shared_state(indoc! {r"
3642 ˇ1 2 3
3643 4 5 6
3644 7 8 9
3645 "})
3646 .await;
3647 cx.simulate_shared_keystrokes("shift-l").await;
3648 cx.shared_state().await.assert_eq(indoc! {"
3649 1 2 3
3650 4 5 6
3651 7 8 9
3652 ˇ"});
3653
3654 cx.set_shared_state(indoc! {r"
3655 1 2 3
3656 4 5 ˇ6
3657 7 8 9
3658 "})
3659 .await;
3660 cx.simulate_shared_keystrokes("9 shift-l").await;
3661 cx.shared_state().await.assert_eq(indoc! {"
3662 1 2 ˇ3
3663 4 5 6
3664 7 8 9
3665 "});
3666 }
3667
3668 #[gpui::test]
3669 async fn test_previous_word_end(cx: &mut gpui::TestAppContext) {
3670 let mut cx = NeovimBackedTestContext::new(cx).await;
3671 cx.set_shared_state(indoc! {r"
3672 456 5ˇ67 678
3673 "})
3674 .await;
3675 cx.simulate_shared_keystrokes("g e").await;
3676 cx.shared_state().await.assert_eq(indoc! {"
3677 45ˇ6 567 678
3678 "});
3679
3680 // Test times
3681 cx.set_shared_state(indoc! {r"
3682 123 234 345
3683 456 5ˇ67 678
3684 "})
3685 .await;
3686 cx.simulate_shared_keystrokes("4 g e").await;
3687 cx.shared_state().await.assert_eq(indoc! {"
3688 12ˇ3 234 345
3689 456 567 678
3690 "});
3691
3692 // With punctuation
3693 cx.set_shared_state(indoc! {r"
3694 123 234 345
3695 4;5.6 5ˇ67 678
3696 789 890 901
3697 "})
3698 .await;
3699 cx.simulate_shared_keystrokes("g e").await;
3700 cx.shared_state().await.assert_eq(indoc! {"
3701 123 234 345
3702 4;5.ˇ6 567 678
3703 789 890 901
3704 "});
3705
3706 // With punctuation and count
3707 cx.set_shared_state(indoc! {r"
3708 123 234 345
3709 4;5.6 5ˇ67 678
3710 789 890 901
3711 "})
3712 .await;
3713 cx.simulate_shared_keystrokes("5 g e").await;
3714 cx.shared_state().await.assert_eq(indoc! {"
3715 123 234 345
3716 ˇ4;5.6 567 678
3717 789 890 901
3718 "});
3719
3720 // newlines
3721 cx.set_shared_state(indoc! {r"
3722 123 234 345
3723
3724 78ˇ9 890 901
3725 "})
3726 .await;
3727 cx.simulate_shared_keystrokes("g e").await;
3728 cx.shared_state().await.assert_eq(indoc! {"
3729 123 234 345
3730 ˇ
3731 789 890 901
3732 "});
3733 cx.simulate_shared_keystrokes("g e").await;
3734 cx.shared_state().await.assert_eq(indoc! {"
3735 123 234 34ˇ5
3736
3737 789 890 901
3738 "});
3739
3740 // With punctuation
3741 cx.set_shared_state(indoc! {r"
3742 123 234 345
3743 4;5.ˇ6 567 678
3744 789 890 901
3745 "})
3746 .await;
3747 cx.simulate_shared_keystrokes("g shift-e").await;
3748 cx.shared_state().await.assert_eq(indoc! {"
3749 123 234 34ˇ5
3750 4;5.6 567 678
3751 789 890 901
3752 "});
3753
3754 // With multi byte char
3755 cx.set_shared_state(indoc! {r"
3756 bar ˇó
3757 "})
3758 .await;
3759 cx.simulate_shared_keystrokes("g e").await;
3760 cx.shared_state().await.assert_eq(indoc! {"
3761 baˇr ó
3762 "});
3763 }
3764
3765 #[gpui::test]
3766 async fn test_visual_match_eol(cx: &mut gpui::TestAppContext) {
3767 let mut cx = NeovimBackedTestContext::new(cx).await;
3768
3769 cx.set_shared_state(indoc! {"
3770 fn aˇ() {
3771 return
3772 }
3773 "})
3774 .await;
3775 cx.simulate_shared_keystrokes("v $ %").await;
3776 cx.shared_state().await.assert_eq(indoc! {"
3777 fn a«() {
3778 return
3779 }ˇ»
3780 "});
3781 }
3782
3783 #[gpui::test]
3784 async fn test_clipping_with_inlay_hints(cx: &mut gpui::TestAppContext) {
3785 let mut cx = VimTestContext::new(cx, true).await;
3786
3787 cx.set_state(
3788 indoc! {"
3789 struct Foo {
3790 ˇ
3791 }
3792 "},
3793 Mode::Normal,
3794 );
3795
3796 cx.update_editor(|editor, _window, cx| {
3797 let range = editor.selections.newest_anchor().range();
3798 let inlay_text = " field: int,\n field2: string\n field3: float";
3799 let inlay = Inlay::edit_prediction(1, range.start, inlay_text);
3800 editor.splice_inlays(&[], vec![inlay], cx);
3801 });
3802
3803 cx.simulate_keystrokes("j");
3804 cx.assert_state(
3805 indoc! {"
3806 struct Foo {
3807
3808 ˇ}
3809 "},
3810 Mode::Normal,
3811 );
3812 }
3813
3814 #[gpui::test]
3815 async fn test_clipping_with_inlay_hints_end_of_line(cx: &mut gpui::TestAppContext) {
3816 let mut cx = VimTestContext::new(cx, true).await;
3817
3818 cx.set_state(
3819 indoc! {"
3820 ˇstruct Foo {
3821
3822 }
3823 "},
3824 Mode::Normal,
3825 );
3826 cx.update_editor(|editor, _window, cx| {
3827 let snapshot = editor.buffer().read(cx).snapshot(cx);
3828 let end_of_line =
3829 snapshot.anchor_after(Point::new(0, snapshot.line_len(MultiBufferRow(0))));
3830 let inlay_text = " hint";
3831 let inlay = Inlay::edit_prediction(1, end_of_line, inlay_text);
3832 editor.splice_inlays(&[], vec![inlay], cx);
3833 });
3834 cx.simulate_keystrokes("$");
3835 cx.assert_state(
3836 indoc! {"
3837 struct Foo ˇ{
3838
3839 }
3840 "},
3841 Mode::Normal,
3842 );
3843 }
3844
3845 #[gpui::test]
3846 async fn test_go_to_percentage(cx: &mut gpui::TestAppContext) {
3847 let mut cx = NeovimBackedTestContext::new(cx).await;
3848 // Normal mode
3849 cx.set_shared_state(indoc! {"
3850 The ˇquick brown
3851 fox jumps over
3852 the lazy dog
3853 The quick brown
3854 fox jumps over
3855 the lazy dog
3856 The quick brown
3857 fox jumps over
3858 the lazy dog"})
3859 .await;
3860 cx.simulate_shared_keystrokes("2 0 %").await;
3861 cx.shared_state().await.assert_eq(indoc! {"
3862 The quick brown
3863 fox ˇjumps over
3864 the lazy dog
3865 The quick brown
3866 fox jumps over
3867 the lazy dog
3868 The quick brown
3869 fox jumps over
3870 the lazy dog"});
3871
3872 cx.simulate_shared_keystrokes("2 5 %").await;
3873 cx.shared_state().await.assert_eq(indoc! {"
3874 The quick brown
3875 fox jumps over
3876 the ˇlazy dog
3877 The quick brown
3878 fox jumps over
3879 the lazy dog
3880 The quick brown
3881 fox jumps over
3882 the lazy dog"});
3883
3884 cx.simulate_shared_keystrokes("7 5 %").await;
3885 cx.shared_state().await.assert_eq(indoc! {"
3886 The quick brown
3887 fox jumps over
3888 the lazy dog
3889 The quick brown
3890 fox jumps over
3891 the lazy dog
3892 The ˇquick brown
3893 fox jumps over
3894 the lazy dog"});
3895
3896 // Visual mode
3897 cx.set_shared_state(indoc! {"
3898 The ˇquick brown
3899 fox jumps over
3900 the lazy dog
3901 The quick brown
3902 fox jumps over
3903 the lazy dog
3904 The quick brown
3905 fox jumps over
3906 the lazy dog"})
3907 .await;
3908 cx.simulate_shared_keystrokes("v 5 0 %").await;
3909 cx.shared_state().await.assert_eq(indoc! {"
3910 The «quick brown
3911 fox jumps over
3912 the lazy dog
3913 The quick brown
3914 fox jˇ»umps over
3915 the lazy dog
3916 The quick brown
3917 fox jumps over
3918 the lazy dog"});
3919
3920 cx.set_shared_state(indoc! {"
3921 The ˇquick brown
3922 fox jumps over
3923 the lazy dog
3924 The quick brown
3925 fox jumps over
3926 the lazy dog
3927 The quick brown
3928 fox jumps over
3929 the lazy dog"})
3930 .await;
3931 cx.simulate_shared_keystrokes("v 1 0 0 %").await;
3932 cx.shared_state().await.assert_eq(indoc! {"
3933 The «quick brown
3934 fox jumps over
3935 the lazy dog
3936 The quick brown
3937 fox jumps over
3938 the lazy dog
3939 The quick brown
3940 fox jumps over
3941 the lˇ»azy dog"});
3942 }
3943
3944 #[gpui::test]
3945 async fn test_space_non_ascii(cx: &mut gpui::TestAppContext) {
3946 let mut cx = NeovimBackedTestContext::new(cx).await;
3947
3948 cx.set_shared_state("ˇπππππ").await;
3949 cx.simulate_shared_keystrokes("3 space").await;
3950 cx.shared_state().await.assert_eq("πππˇππ");
3951 }
3952
3953 #[gpui::test]
3954 async fn test_space_non_ascii_eol(cx: &mut gpui::TestAppContext) {
3955 let mut cx = NeovimBackedTestContext::new(cx).await;
3956
3957 cx.set_shared_state(indoc! {"
3958 ππππˇπ
3959 πanotherline"})
3960 .await;
3961 cx.simulate_shared_keystrokes("4 space").await;
3962 cx.shared_state().await.assert_eq(indoc! {"
3963 πππππ
3964 πanˇotherline"});
3965 }
3966
3967 #[gpui::test]
3968 async fn test_backspace_non_ascii_bol(cx: &mut gpui::TestAppContext) {
3969 let mut cx = NeovimBackedTestContext::new(cx).await;
3970
3971 cx.set_shared_state(indoc! {"
3972 ππππ
3973 πanˇotherline"})
3974 .await;
3975 cx.simulate_shared_keystrokes("4 backspace").await;
3976 cx.shared_state().await.assert_eq(indoc! {"
3977 πππˇπ
3978 πanotherline"});
3979 }
3980
3981 #[gpui::test]
3982 async fn test_go_to_indent(cx: &mut gpui::TestAppContext) {
3983 let mut cx = VimTestContext::new(cx, true).await;
3984 cx.set_state(
3985 indoc! {
3986 "func empty(a string) bool {
3987 ˇif a == \"\" {
3988 return true
3989 }
3990 return false
3991 }"
3992 },
3993 Mode::Normal,
3994 );
3995 cx.simulate_keystrokes("[ -");
3996 cx.assert_state(
3997 indoc! {
3998 "ˇfunc empty(a string) bool {
3999 if a == \"\" {
4000 return true
4001 }
4002 return false
4003 }"
4004 },
4005 Mode::Normal,
4006 );
4007 cx.simulate_keystrokes("] =");
4008 cx.assert_state(
4009 indoc! {
4010 "func empty(a string) bool {
4011 if a == \"\" {
4012 return true
4013 }
4014 return false
4015 ˇ}"
4016 },
4017 Mode::Normal,
4018 );
4019 cx.simulate_keystrokes("[ +");
4020 cx.assert_state(
4021 indoc! {
4022 "func empty(a string) bool {
4023 if a == \"\" {
4024 return true
4025 }
4026 ˇreturn false
4027 }"
4028 },
4029 Mode::Normal,
4030 );
4031 cx.simulate_keystrokes("2 [ =");
4032 cx.assert_state(
4033 indoc! {
4034 "func empty(a string) bool {
4035 ˇif a == \"\" {
4036 return true
4037 }
4038 return false
4039 }"
4040 },
4041 Mode::Normal,
4042 );
4043 cx.simulate_keystrokes("] +");
4044 cx.assert_state(
4045 indoc! {
4046 "func empty(a string) bool {
4047 if a == \"\" {
4048 ˇreturn true
4049 }
4050 return false
4051 }"
4052 },
4053 Mode::Normal,
4054 );
4055 cx.simulate_keystrokes("] -");
4056 cx.assert_state(
4057 indoc! {
4058 "func empty(a string) bool {
4059 if a == \"\" {
4060 return true
4061 ˇ}
4062 return false
4063 }"
4064 },
4065 Mode::Normal,
4066 );
4067 }
4068
4069 #[gpui::test]
4070 async fn test_delete_key_can_remove_last_character(cx: &mut gpui::TestAppContext) {
4071 let mut cx = NeovimBackedTestContext::new(cx).await;
4072 cx.set_shared_state("abˇc").await;
4073 cx.simulate_shared_keystrokes("delete").await;
4074 cx.shared_state().await.assert_eq("aˇb");
4075 }
4076
4077 #[gpui::test]
4078 async fn test_forced_motion_delete_to_start_of_line(cx: &mut gpui::TestAppContext) {
4079 let mut cx = NeovimBackedTestContext::new(cx).await;
4080
4081 cx.set_shared_state(indoc! {"
4082 ˇthe quick brown fox
4083 jumped over the lazy dog"})
4084 .await;
4085 cx.simulate_shared_keystrokes("d v 0").await;
4086 cx.shared_state().await.assert_eq(indoc! {"
4087 ˇhe quick brown fox
4088 jumped over the lazy dog"});
4089 assert!(!cx.cx.forced_motion());
4090
4091 cx.set_shared_state(indoc! {"
4092 the quick bˇrown fox
4093 jumped over the lazy dog"})
4094 .await;
4095 cx.simulate_shared_keystrokes("d v 0").await;
4096 cx.shared_state().await.assert_eq(indoc! {"
4097 ˇown fox
4098 jumped over the lazy dog"});
4099 assert!(!cx.cx.forced_motion());
4100
4101 cx.set_shared_state(indoc! {"
4102 the quick brown foˇx
4103 jumped over the lazy dog"})
4104 .await;
4105 cx.simulate_shared_keystrokes("d v 0").await;
4106 cx.shared_state().await.assert_eq(indoc! {"
4107 ˇ
4108 jumped over the lazy dog"});
4109 assert!(!cx.cx.forced_motion());
4110 }
4111
4112 #[gpui::test]
4113 async fn test_forced_motion_delete_to_middle_of_line(cx: &mut gpui::TestAppContext) {
4114 let mut cx = NeovimBackedTestContext::new(cx).await;
4115
4116 cx.set_shared_state(indoc! {"
4117 ˇthe quick brown fox
4118 jumped over the lazy dog"})
4119 .await;
4120 cx.simulate_shared_keystrokes("d v g shift-m").await;
4121 cx.shared_state().await.assert_eq(indoc! {"
4122 ˇbrown fox
4123 jumped over the lazy dog"});
4124 assert!(!cx.cx.forced_motion());
4125
4126 cx.set_shared_state(indoc! {"
4127 the quick bˇrown fox
4128 jumped over the lazy dog"})
4129 .await;
4130 cx.simulate_shared_keystrokes("d v g shift-m").await;
4131 cx.shared_state().await.assert_eq(indoc! {"
4132 the quickˇown fox
4133 jumped over the lazy dog"});
4134 assert!(!cx.cx.forced_motion());
4135
4136 cx.set_shared_state(indoc! {"
4137 the quick brown foˇx
4138 jumped over the lazy dog"})
4139 .await;
4140 cx.simulate_shared_keystrokes("d v g shift-m").await;
4141 cx.shared_state().await.assert_eq(indoc! {"
4142 the quicˇk
4143 jumped over the lazy dog"});
4144 assert!(!cx.cx.forced_motion());
4145
4146 cx.set_shared_state(indoc! {"
4147 ˇthe quick brown fox
4148 jumped over the lazy dog"})
4149 .await;
4150 cx.simulate_shared_keystrokes("d v 7 5 g shift-m").await;
4151 cx.shared_state().await.assert_eq(indoc! {"
4152 ˇ fox
4153 jumped over the lazy dog"});
4154 assert!(!cx.cx.forced_motion());
4155
4156 cx.set_shared_state(indoc! {"
4157 ˇthe quick brown fox
4158 jumped over the lazy dog"})
4159 .await;
4160 cx.simulate_shared_keystrokes("d v 2 3 g shift-m").await;
4161 cx.shared_state().await.assert_eq(indoc! {"
4162 ˇuick brown fox
4163 jumped over the lazy dog"});
4164 assert!(!cx.cx.forced_motion());
4165 }
4166
4167 #[gpui::test]
4168 async fn test_forced_motion_delete_to_end_of_line(cx: &mut gpui::TestAppContext) {
4169 let mut cx = NeovimBackedTestContext::new(cx).await;
4170
4171 cx.set_shared_state(indoc! {"
4172 the quick brown foˇx
4173 jumped over the lazy dog"})
4174 .await;
4175 cx.simulate_shared_keystrokes("d v $").await;
4176 cx.shared_state().await.assert_eq(indoc! {"
4177 the quick brown foˇx
4178 jumped over the lazy dog"});
4179 assert!(!cx.cx.forced_motion());
4180
4181 cx.set_shared_state(indoc! {"
4182 ˇthe quick brown fox
4183 jumped over the lazy dog"})
4184 .await;
4185 cx.simulate_shared_keystrokes("d v $").await;
4186 cx.shared_state().await.assert_eq(indoc! {"
4187 ˇx
4188 jumped over the lazy dog"});
4189 assert!(!cx.cx.forced_motion());
4190 }
4191
4192 #[gpui::test]
4193 async fn test_forced_motion_yank(cx: &mut gpui::TestAppContext) {
4194 let mut cx = NeovimBackedTestContext::new(cx).await;
4195
4196 cx.set_shared_state(indoc! {"
4197 ˇthe quick brown fox
4198 jumped over the lazy dog"})
4199 .await;
4200 cx.simulate_shared_keystrokes("y v j p").await;
4201 cx.shared_state().await.assert_eq(indoc! {"
4202 the quick brown fox
4203 ˇthe quick brown fox
4204 jumped over the lazy dog"});
4205 assert!(!cx.cx.forced_motion());
4206
4207 cx.set_shared_state(indoc! {"
4208 the quick bˇrown fox
4209 jumped over the lazy dog"})
4210 .await;
4211 cx.simulate_shared_keystrokes("y v j p").await;
4212 cx.shared_state().await.assert_eq(indoc! {"
4213 the quick brˇrown fox
4214 jumped overown fox
4215 jumped over the lazy dog"});
4216 assert!(!cx.cx.forced_motion());
4217
4218 cx.set_shared_state(indoc! {"
4219 the quick brown foˇx
4220 jumped over the lazy dog"})
4221 .await;
4222 cx.simulate_shared_keystrokes("y v j p").await;
4223 cx.shared_state().await.assert_eq(indoc! {"
4224 the quick brown foxˇx
4225 jumped over the la
4226 jumped over the lazy dog"});
4227 assert!(!cx.cx.forced_motion());
4228
4229 cx.set_shared_state(indoc! {"
4230 the quick brown fox
4231 jˇumped over the lazy dog"})
4232 .await;
4233 cx.simulate_shared_keystrokes("y v k p").await;
4234 cx.shared_state().await.assert_eq(indoc! {"
4235 thˇhe quick brown fox
4236 je quick brown fox
4237 jumped over the lazy dog"});
4238 assert!(!cx.cx.forced_motion());
4239 }
4240
4241 #[gpui::test]
4242 async fn test_inclusive_to_exclusive_delete(cx: &mut gpui::TestAppContext) {
4243 let mut cx = NeovimBackedTestContext::new(cx).await;
4244
4245 cx.set_shared_state(indoc! {"
4246 ˇthe quick brown fox
4247 jumped over the lazy dog"})
4248 .await;
4249 cx.simulate_shared_keystrokes("d v e").await;
4250 cx.shared_state().await.assert_eq(indoc! {"
4251 ˇe quick brown fox
4252 jumped over the lazy dog"});
4253 assert!(!cx.cx.forced_motion());
4254
4255 cx.set_shared_state(indoc! {"
4256 the quick bˇrown fox
4257 jumped over the lazy dog"})
4258 .await;
4259 cx.simulate_shared_keystrokes("d v e").await;
4260 cx.shared_state().await.assert_eq(indoc! {"
4261 the quick bˇn fox
4262 jumped over the lazy dog"});
4263 assert!(!cx.cx.forced_motion());
4264
4265 cx.set_shared_state(indoc! {"
4266 the quick brown foˇx
4267 jumped over the lazy dog"})
4268 .await;
4269 cx.simulate_shared_keystrokes("d v e").await;
4270 cx.shared_state().await.assert_eq(indoc! {"
4271 the quick brown foˇd over the lazy dog"});
4272 assert!(!cx.cx.forced_motion());
4273 }
4274}