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