motion.rs

  1use editor::{
  2    char_kind,
  3    display_map::{DisplaySnapshot, ToDisplayPoint},
  4    movement, Bias, CharKind, DisplayPoint,
  5};
  6use gpui::{actions, impl_actions, MutableAppContext};
  7use language::{Point, Selection, SelectionGoal};
  8use serde::Deserialize;
  9use workspace::Workspace;
 10
 11use crate::{
 12    normal::normal_motion,
 13    state::{Mode, Operator},
 14    visual::visual_motion,
 15    Vim,
 16};
 17
 18#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 19pub enum Motion {
 20    Left,
 21    Backspace,
 22    Down,
 23    Up,
 24    Right,
 25    NextWordStart { ignore_punctuation: bool },
 26    NextWordEnd { ignore_punctuation: bool },
 27    PreviousWordStart { ignore_punctuation: bool },
 28    FirstNonWhitespace,
 29    CurrentLine,
 30    StartOfLine,
 31    EndOfLine,
 32    StartOfDocument,
 33    EndOfDocument,
 34    Matching,
 35}
 36
 37#[derive(Clone, Deserialize, PartialEq)]
 38#[serde(rename_all = "camelCase")]
 39struct NextWordStart {
 40    #[serde(default)]
 41    ignore_punctuation: bool,
 42}
 43
 44#[derive(Clone, Deserialize, PartialEq)]
 45#[serde(rename_all = "camelCase")]
 46struct NextWordEnd {
 47    #[serde(default)]
 48    ignore_punctuation: bool,
 49}
 50
 51#[derive(Clone, Deserialize, PartialEq)]
 52#[serde(rename_all = "camelCase")]
 53struct PreviousWordStart {
 54    #[serde(default)]
 55    ignore_punctuation: bool,
 56}
 57
 58actions!(
 59    vim,
 60    [
 61        Left,
 62        Backspace,
 63        Down,
 64        Up,
 65        Right,
 66        FirstNonWhitespace,
 67        StartOfLine,
 68        EndOfLine,
 69        CurrentLine,
 70        StartOfDocument,
 71        EndOfDocument,
 72        Matching,
 73    ]
 74);
 75impl_actions!(vim, [NextWordStart, NextWordEnd, PreviousWordStart]);
 76
 77pub fn init(cx: &mut MutableAppContext) {
 78    cx.add_action(|_: &mut Workspace, _: &Left, cx: _| motion(Motion::Left, cx));
 79    cx.add_action(|_: &mut Workspace, _: &Backspace, cx: _| motion(Motion::Backspace, cx));
 80    cx.add_action(|_: &mut Workspace, _: &Down, cx: _| motion(Motion::Down, cx));
 81    cx.add_action(|_: &mut Workspace, _: &Up, cx: _| motion(Motion::Up, cx));
 82    cx.add_action(|_: &mut Workspace, _: &Right, cx: _| motion(Motion::Right, cx));
 83    cx.add_action(|_: &mut Workspace, _: &FirstNonWhitespace, cx: _| {
 84        motion(Motion::FirstNonWhitespace, cx)
 85    });
 86    cx.add_action(|_: &mut Workspace, _: &StartOfLine, cx: _| motion(Motion::StartOfLine, cx));
 87    cx.add_action(|_: &mut Workspace, _: &EndOfLine, cx: _| motion(Motion::EndOfLine, cx));
 88    cx.add_action(|_: &mut Workspace, _: &CurrentLine, cx: _| motion(Motion::CurrentLine, cx));
 89    cx.add_action(|_: &mut Workspace, _: &StartOfDocument, cx: _| {
 90        motion(Motion::StartOfDocument, cx)
 91    });
 92    cx.add_action(|_: &mut Workspace, _: &EndOfDocument, cx: _| motion(Motion::EndOfDocument, cx));
 93    cx.add_action(|_: &mut Workspace, _: &Matching, cx: _| motion(Motion::Matching, cx));
 94
 95    cx.add_action(
 96        |_: &mut Workspace, &NextWordStart { ignore_punctuation }: &NextWordStart, cx: _| {
 97            motion(Motion::NextWordStart { ignore_punctuation }, cx)
 98        },
 99    );
100    cx.add_action(
101        |_: &mut Workspace, &NextWordEnd { ignore_punctuation }: &NextWordEnd, cx: _| {
102            motion(Motion::NextWordEnd { ignore_punctuation }, cx)
103        },
104    );
105    cx.add_action(
106        |_: &mut Workspace,
107         &PreviousWordStart { ignore_punctuation }: &PreviousWordStart,
108         cx: _| { motion(Motion::PreviousWordStart { ignore_punctuation }, cx) },
109    );
110}
111
112pub(crate) fn motion(motion: Motion, cx: &mut MutableAppContext) {
113    if let Some(Operator::Namespace(_)) = Vim::read(cx).active_operator() {
114        Vim::update(cx, |vim, cx| vim.pop_operator(cx));
115    }
116
117    let times = Vim::update(cx, |vim, cx| vim.pop_number_operator(cx));
118    let operator = Vim::read(cx).active_operator();
119    match Vim::read(cx).state.mode {
120        Mode::Normal => normal_motion(motion, operator, times, cx),
121        Mode::Visual { .. } => visual_motion(motion, times, cx),
122        Mode::Insert => {
123            // Shouldn't execute a motion in insert mode. Ignoring
124        }
125    }
126    Vim::update(cx, |vim, cx| vim.clear_operator(cx));
127}
128
129// Motion handling is specified here:
130// https://github.com/vim/vim/blob/master/runtime/doc/motion.txt
131impl Motion {
132    pub fn linewise(self) -> bool {
133        use Motion::*;
134        matches!(
135            self,
136            Down | Up | StartOfDocument | EndOfDocument | CurrentLine
137        )
138    }
139
140    pub fn inclusive(self) -> bool {
141        use Motion::*;
142        match self {
143            Down
144            | Up
145            | StartOfDocument
146            | EndOfDocument
147            | CurrentLine
148            | EndOfLine
149            | NextWordEnd { .. }
150            | Matching => true,
151            Left
152            | Backspace
153            | Right
154            | StartOfLine
155            | NextWordStart { .. }
156            | PreviousWordStart { .. }
157            | FirstNonWhitespace => false,
158        }
159    }
160
161    pub fn move_point(
162        self,
163        map: &DisplaySnapshot,
164        point: DisplayPoint,
165        goal: SelectionGoal,
166        times: usize,
167    ) -> (DisplayPoint, SelectionGoal) {
168        use Motion::*;
169        match self {
170            Left => (left(map, point, times), SelectionGoal::None),
171            Backspace => (backspace(map, point, times), SelectionGoal::None),
172            Down => down(map, point, goal, times),
173            Up => up(map, point, goal, times),
174            Right => (right(map, point, times), SelectionGoal::None),
175            NextWordStart { ignore_punctuation } => (
176                next_word_start(map, point, ignore_punctuation, times),
177                SelectionGoal::None,
178            ),
179            NextWordEnd { ignore_punctuation } => (
180                next_word_end(map, point, ignore_punctuation, times),
181                SelectionGoal::None,
182            ),
183            PreviousWordStart { ignore_punctuation } => (
184                previous_word_start(map, point, ignore_punctuation, times),
185                SelectionGoal::None,
186            ),
187            FirstNonWhitespace => (first_non_whitespace(map, point), SelectionGoal::None),
188            StartOfLine => (start_of_line(map, point), SelectionGoal::None),
189            EndOfLine => (end_of_line(map, point), SelectionGoal::None),
190            CurrentLine => (end_of_line(map, point), SelectionGoal::None),
191            StartOfDocument => (start_of_document(map, point, times), SelectionGoal::None),
192            EndOfDocument => (end_of_document(map, point, times), SelectionGoal::None),
193            Matching => (matching(map, point), SelectionGoal::None),
194        }
195    }
196
197    // Expands a selection using self motion for an operator
198    pub fn expand_selection(
199        self,
200        map: &DisplaySnapshot,
201        selection: &mut Selection<DisplayPoint>,
202        times: usize,
203        expand_to_surrounding_newline: bool,
204    ) {
205        let (new_head, goal) = self.move_point(map, selection.head(), selection.goal, times);
206        selection.set_head(new_head, goal);
207
208        if self.linewise() {
209            if selection.start != selection.end {
210                selection.start = map.prev_line_boundary(selection.start.to_point(map)).1;
211
212                if expand_to_surrounding_newline {
213                    if selection.end.row() < map.max_point().row() {
214                        *selection.end.row_mut() += 1;
215                        *selection.end.column_mut() = 0;
216                        selection.end = map.clip_point(selection.end, Bias::Right);
217                        // Don't reset the end here
218                        return;
219                    } else if selection.start.row() > 0 {
220                        *selection.start.row_mut() -= 1;
221                        *selection.start.column_mut() = map.line_len(selection.start.row());
222                        selection.start = map.clip_point(selection.start, Bias::Left);
223                    }
224                }
225
226                (_, selection.end) = map.next_line_boundary(selection.end.to_point(map));
227            }
228        } else {
229            // If the motion is exclusive and the end of the motion is in column 1, the
230            // end of the motion is moved to the end of the previous line and the motion
231            // becomes inclusive. Example: "}" moves to the first line after a paragraph,
232            // but "d}" will not include that line.
233            let mut inclusive = self.inclusive();
234            if !inclusive
235                && self != Motion::Backspace
236                && selection.end.row() > selection.start.row()
237                && selection.end.column() == 0
238                && selection.end.row() > 0
239            {
240                inclusive = true;
241                *selection.end.row_mut() -= 1;
242                *selection.end.column_mut() = 0;
243                selection.end = map.clip_point(
244                    map.next_line_boundary(selection.end.to_point(map)).1,
245                    Bias::Left,
246                );
247            }
248
249            if inclusive && selection.end.column() < map.line_len(selection.end.row()) {
250                *selection.end.column_mut() += 1;
251            }
252        }
253    }
254}
255
256fn left(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
257    for _ in 0..times {
258        *point.column_mut() = point.column().saturating_sub(1);
259        point = map.clip_point(point, Bias::Right);
260        if point.column() == 0 {
261            break;
262        }
263    }
264    point
265}
266
267fn backspace(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
268    for _ in 0..times {
269        point = movement::left(map, point);
270    }
271    point
272}
273
274fn down(
275    map: &DisplaySnapshot,
276    mut point: DisplayPoint,
277    mut goal: SelectionGoal,
278    times: usize,
279) -> (DisplayPoint, SelectionGoal) {
280    for _ in 0..times {
281        (point, goal) = movement::down(map, point, goal, true);
282    }
283    (point, goal)
284}
285
286fn up(
287    map: &DisplaySnapshot,
288    mut point: DisplayPoint,
289    mut goal: SelectionGoal,
290    times: usize,
291) -> (DisplayPoint, SelectionGoal) {
292    for _ in 0..times {
293        (point, goal) = movement::up(map, point, goal, true);
294    }
295    (point, goal)
296}
297
298pub(crate) fn right(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
299    for _ in 0..times {
300        let mut new_point = point;
301        *new_point.column_mut() += 1;
302        let new_point = map.clip_point(new_point, Bias::Right);
303        if point == new_point {
304            break;
305        }
306        point = new_point;
307    }
308    point
309}
310
311pub(crate) fn next_word_start(
312    map: &DisplaySnapshot,
313    mut point: DisplayPoint,
314    ignore_punctuation: bool,
315    times: usize,
316) -> DisplayPoint {
317    for _ in 0..times {
318        let mut crossed_newline = false;
319        point = movement::find_boundary(map, point, |left, right| {
320            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
321            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
322            let at_newline = right == '\n';
323
324            let found = (left_kind != right_kind && right_kind != CharKind::Whitespace)
325                || at_newline && crossed_newline
326                || at_newline && left == '\n'; // Prevents skipping repeated empty lines
327
328            if at_newline {
329                crossed_newline = true;
330            }
331            found
332        })
333    }
334    point
335}
336
337fn next_word_end(
338    map: &DisplaySnapshot,
339    mut point: DisplayPoint,
340    ignore_punctuation: bool,
341    times: usize,
342) -> DisplayPoint {
343    for _ in 0..times {
344        *point.column_mut() += 1;
345        point = movement::find_boundary(map, point, |left, right| {
346            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
347            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
348
349            left_kind != right_kind && left_kind != CharKind::Whitespace
350        });
351
352        // find_boundary clips, so if the character after the next character is a newline or at the end of the document, we know
353        // we have backtraced already
354        if !map
355            .chars_at(point)
356            .nth(1)
357            .map(|(c, _)| c == '\n')
358            .unwrap_or(true)
359        {
360            *point.column_mut() = point.column().saturating_sub(1);
361        }
362        point = map.clip_point(point, Bias::Left);
363    }
364    point
365}
366
367fn previous_word_start(
368    map: &DisplaySnapshot,
369    mut point: DisplayPoint,
370    ignore_punctuation: bool,
371    times: usize,
372) -> DisplayPoint {
373    for _ in 0..times {
374        // This works even though find_preceding_boundary is called for every character in the line containing
375        // cursor because the newline is checked only once.
376        point = movement::find_preceding_boundary(map, point, |left, right| {
377            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
378            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
379
380            (left_kind != right_kind && !right.is_whitespace()) || left == '\n'
381        });
382    }
383    point
384}
385
386fn first_non_whitespace(map: &DisplaySnapshot, from: DisplayPoint) -> DisplayPoint {
387    let mut last_point = DisplayPoint::new(from.row(), 0);
388    for (ch, point) in map.chars_at(last_point) {
389        if ch == '\n' {
390            return from;
391        }
392
393        last_point = point;
394
395        if char_kind(ch) != CharKind::Whitespace {
396            break;
397        }
398    }
399
400    map.clip_point(last_point, Bias::Left)
401}
402
403fn start_of_line(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
404    map.prev_line_boundary(point.to_point(map)).1
405}
406
407fn end_of_line(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
408    map.clip_point(map.next_line_boundary(point.to_point(map)).1, Bias::Left)
409}
410
411fn start_of_document(map: &DisplaySnapshot, point: DisplayPoint, line: usize) -> DisplayPoint {
412    let mut new_point = Point::new((line - 1) as u32, 0).to_display_point(map);
413    *new_point.column_mut() = point.column();
414    map.clip_point(new_point, Bias::Left)
415}
416
417fn end_of_document(map: &DisplaySnapshot, point: DisplayPoint, line: usize) -> DisplayPoint {
418    let mut new_point = if line == 1 {
419        map.max_point()
420    } else {
421        Point::new((line - 1) as u32, 0).to_display_point(map)
422    };
423    *new_point.column_mut() = point.column();
424    map.clip_point(new_point, Bias::Left)
425}
426
427fn matching(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
428    let offset = point.to_offset(map, Bias::Left);
429    if let Some((open_range, close_range)) =
430        map.buffer_snapshot.enclosing_bracket_ranges(offset..offset)
431    {
432        if open_range.contains(&offset) {
433            close_range.start.to_display_point(map)
434        } else {
435            open_range.start.to_display_point(map)
436        }
437    } else {
438        point
439    }
440}