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::{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)]
 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        if self.linewise() {
143            return true;
144        }
145
146        match self {
147            EndOfLine | NextWordEnd { .. } | Matching => true,
148            Left | Right | StartOfLine | NextWordStart { .. } | PreviousWordStart { .. } => false,
149            _ => panic!("Exclusivity not defined for {self:?}"),
150        }
151    }
152
153    pub fn move_point(
154        self,
155        map: &DisplaySnapshot,
156        point: DisplayPoint,
157        goal: SelectionGoal,
158        times: usize,
159    ) -> (DisplayPoint, SelectionGoal) {
160        use Motion::*;
161        match self {
162            Left => (left(map, point, times), SelectionGoal::None),
163            Backspace => (backspace(map, point, times), SelectionGoal::None),
164            Down => down(map, point, goal, times),
165            Up => up(map, point, goal, times),
166            Right => (right(map, point, times), SelectionGoal::None),
167            NextWordStart { ignore_punctuation } => (
168                next_word_start(map, point, ignore_punctuation, times),
169                SelectionGoal::None,
170            ),
171            NextWordEnd { ignore_punctuation } => (
172                next_word_end(map, point, ignore_punctuation, times),
173                SelectionGoal::None,
174            ),
175            PreviousWordStart { ignore_punctuation } => (
176                previous_word_start(map, point, ignore_punctuation, times),
177                SelectionGoal::None,
178            ),
179            FirstNonWhitespace => (first_non_whitespace(map, point), SelectionGoal::None),
180            StartOfLine => (start_of_line(map, point), SelectionGoal::None),
181            EndOfLine => (end_of_line(map, point), SelectionGoal::None),
182            CurrentLine => (end_of_line(map, point), SelectionGoal::None),
183            StartOfDocument => (start_of_document(map, point, times), SelectionGoal::None),
184            EndOfDocument => (end_of_document(map, point), SelectionGoal::None),
185            Matching => (matching(map, point), SelectionGoal::None),
186        }
187    }
188
189    // Expands a selection using self motion for an operator
190    pub fn expand_selection(
191        self,
192        map: &DisplaySnapshot,
193        selection: &mut Selection<DisplayPoint>,
194        times: usize,
195        expand_to_surrounding_newline: bool,
196    ) {
197        let (head, goal) = self.move_point(map, selection.head(), selection.goal, times);
198        selection.set_head(head, goal);
199
200        if self.linewise() {
201            selection.start = map.prev_line_boundary(selection.start.to_point(map)).1;
202
203            if expand_to_surrounding_newline {
204                if selection.end.row() < map.max_point().row() {
205                    *selection.end.row_mut() += 1;
206                    *selection.end.column_mut() = 0;
207                    selection.end = map.clip_point(selection.end, Bias::Right);
208                    // Don't reset the end here
209                    return;
210                } else if selection.start.row() > 0 {
211                    *selection.start.row_mut() -= 1;
212                    *selection.start.column_mut() = map.line_len(selection.start.row());
213                    selection.start = map.clip_point(selection.start, Bias::Left);
214                }
215            }
216
217            (_, selection.end) = map.next_line_boundary(selection.end.to_point(map));
218        } else {
219            // If the motion is exclusive and the end of the motion is in column 1, the
220            // end of the motion is moved to the end of the previous line and the motion
221            // becomes inclusive. Example: "}" moves to the first line after a paragraph,
222            // but "d}" will not include that line.
223            let mut inclusive = self.inclusive();
224            if !inclusive
225                && selection.end.row() > selection.start.row()
226                && selection.end.column() == 0
227                && selection.end.row() > 0
228            {
229                inclusive = true;
230                *selection.end.row_mut() -= 1;
231                *selection.end.column_mut() = 0;
232                selection.end = map.clip_point(
233                    map.next_line_boundary(selection.end.to_point(map)).1,
234                    Bias::Left,
235                );
236            }
237
238            if inclusive && selection.end.column() < map.line_len(selection.end.row()) {
239                *selection.end.column_mut() += 1;
240            }
241        }
242    }
243}
244
245fn left(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
246    for _ in 0..times {
247        *point.column_mut() = point.column().saturating_sub(1);
248        point = map.clip_point(point, Bias::Right);
249        if point.column() == 0 {
250            break;
251        }
252    }
253    point
254}
255
256fn backspace(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
257    for _ in 0..times {
258        point = movement::left(map, point);
259    }
260    point
261}
262
263fn down(
264    map: &DisplaySnapshot,
265    mut point: DisplayPoint,
266    mut goal: SelectionGoal,
267    times: usize,
268) -> (DisplayPoint, SelectionGoal) {
269    for _ in 0..times {
270        (point, goal) = movement::down(map, point, goal, true);
271    }
272    (point, goal)
273}
274
275fn up(
276    map: &DisplaySnapshot,
277    mut point: DisplayPoint,
278    mut goal: SelectionGoal,
279    times: usize,
280) -> (DisplayPoint, SelectionGoal) {
281    for _ in 0..times {
282        (point, goal) = movement::up(map, point, goal, true);
283    }
284    (point, goal)
285}
286
287pub(crate) fn right(map: &DisplaySnapshot, mut point: DisplayPoint, times: usize) -> DisplayPoint {
288    for _ in 0..times {
289        let mut new_point = point;
290        *new_point.column_mut() += 1;
291        let new_point = map.clip_point(new_point, Bias::Right);
292        if point == new_point {
293            break;
294        }
295        point = new_point;
296    }
297    point
298}
299
300pub(crate) fn next_word_start(
301    map: &DisplaySnapshot,
302    mut point: DisplayPoint,
303    ignore_punctuation: bool,
304    times: usize,
305) -> DisplayPoint {
306    for _ in 0..times {
307        let mut crossed_newline = false;
308        point = movement::find_boundary(map, point, |left, right| {
309            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
310            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
311            let at_newline = right == '\n';
312
313            let found = (left_kind != right_kind && right_kind != CharKind::Whitespace)
314                || at_newline && crossed_newline
315                || at_newline && left == '\n'; // Prevents skipping repeated empty lines
316
317            if at_newline {
318                crossed_newline = true;
319            }
320            found
321        })
322    }
323    point
324}
325
326fn next_word_end(
327    map: &DisplaySnapshot,
328    mut point: DisplayPoint,
329    ignore_punctuation: bool,
330    times: usize,
331) -> DisplayPoint {
332    for _ in 0..times {
333        *point.column_mut() += 1;
334        point = movement::find_boundary(map, point, |left, right| {
335            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
336            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
337
338            left_kind != right_kind && left_kind != CharKind::Whitespace
339        });
340
341        // find_boundary clips, so if the character after the next character is a newline or at the end of the document, we know
342        // we have backtraced already
343        if !map
344            .chars_at(point)
345            .nth(1)
346            .map(|(c, _)| c == '\n')
347            .unwrap_or(true)
348        {
349            *point.column_mut() = point.column().saturating_sub(1);
350        }
351        point = map.clip_point(point, Bias::Left);
352    }
353    point
354}
355
356fn previous_word_start(
357    map: &DisplaySnapshot,
358    mut point: DisplayPoint,
359    ignore_punctuation: bool,
360    times: usize,
361) -> DisplayPoint {
362    for _ in 0..times {
363        // This works even though find_preceding_boundary is called for every character in the line containing
364        // cursor because the newline is checked only once.
365        point = movement::find_preceding_boundary(map, point, |left, right| {
366            let left_kind = char_kind(left).coerce_punctuation(ignore_punctuation);
367            let right_kind = char_kind(right).coerce_punctuation(ignore_punctuation);
368
369            (left_kind != right_kind && !right.is_whitespace()) || left == '\n'
370        });
371    }
372    point
373}
374
375fn first_non_whitespace(map: &DisplaySnapshot, from: DisplayPoint) -> DisplayPoint {
376    let mut last_point = DisplayPoint::new(from.row(), 0);
377    for (ch, point) in map.chars_at(last_point) {
378        if ch == '\n' {
379            return from;
380        }
381
382        last_point = point;
383
384        if char_kind(ch) != CharKind::Whitespace {
385            break;
386        }
387    }
388
389    map.clip_point(last_point, Bias::Left)
390}
391
392fn start_of_line(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
393    map.prev_line_boundary(point.to_point(map)).1
394}
395
396fn end_of_line(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
397    map.clip_point(map.next_line_boundary(point.to_point(map)).1, Bias::Left)
398}
399
400fn start_of_document(map: &DisplaySnapshot, point: DisplayPoint, line: usize) -> DisplayPoint {
401    let mut new_point = (line - 1).to_display_point(map);
402    *new_point.column_mut() = point.column();
403    map.clip_point(new_point, Bias::Left)
404}
405
406fn end_of_document(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
407    let mut new_point = map.max_point();
408    *new_point.column_mut() = point.column();
409    map.clip_point(new_point, Bias::Left)
410}
411
412fn matching(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
413    let offset = point.to_offset(map, Bias::Left);
414    if let Some((open_range, close_range)) =
415        map.buffer_snapshot.enclosing_bracket_ranges(offset..offset)
416    {
417        if open_range.contains(&offset) {
418            close_range.start.to_display_point(map)
419        } else {
420            open_range.start.to_display_point(map)
421        }
422    } else {
423        point
424    }
425}