movement.rs

  1use super::{Bias, DisplayPoint, DisplaySnapshot, SelectionGoal, ToDisplayPoint};
  2use crate::ToPoint;
  3use anyhow::Result;
  4use std::{cmp, ops::Range};
  5
  6pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> Result<DisplayPoint> {
  7    if point.column() > 0 {
  8        *point.column_mut() -= 1;
  9    } else if point.row() > 0 {
 10        *point.row_mut() -= 1;
 11        *point.column_mut() = map.line_len(point.row());
 12    }
 13    Ok(map.clip_point(point, Bias::Left))
 14}
 15
 16pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> Result<DisplayPoint> {
 17    let max_column = map.line_len(point.row());
 18    if point.column() < max_column {
 19        *point.column_mut() += 1;
 20    } else if point.row() < map.max_point().row() {
 21        *point.row_mut() += 1;
 22        *point.column_mut() = 0;
 23    }
 24    Ok(map.clip_point(point, Bias::Right))
 25}
 26
 27pub fn up(
 28    map: &DisplaySnapshot,
 29    start: DisplayPoint,
 30    goal: SelectionGoal,
 31) -> Result<(DisplayPoint, SelectionGoal)> {
 32    let mut goal_column = if let SelectionGoal::Column(column) = goal {
 33        column
 34    } else {
 35        map.column_to_chars(start.row(), start.column())
 36    };
 37
 38    let prev_row = start.row().saturating_sub(1);
 39    let mut point = map.clip_point(
 40        DisplayPoint::new(prev_row, map.line_len(prev_row)),
 41        Bias::Left,
 42    );
 43    if point.row() < start.row() {
 44        *point.column_mut() = map.column_from_chars(point.row(), goal_column);
 45    } else {
 46        point = DisplayPoint::new(0, 0);
 47        goal_column = 0;
 48    }
 49
 50    let clip_bias = if point.column() == map.line_len(point.row()) {
 51        Bias::Left
 52    } else {
 53        Bias::Right
 54    };
 55
 56    Ok((
 57        map.clip_point(point, clip_bias),
 58        SelectionGoal::Column(goal_column),
 59    ))
 60}
 61
 62pub fn down(
 63    map: &DisplaySnapshot,
 64    start: DisplayPoint,
 65    goal: SelectionGoal,
 66) -> Result<(DisplayPoint, SelectionGoal)> {
 67    let mut goal_column = if let SelectionGoal::Column(column) = goal {
 68        column
 69    } else {
 70        map.column_to_chars(start.row(), start.column())
 71    };
 72
 73    let next_row = start.row() + 1;
 74    let mut point = map.clip_point(DisplayPoint::new(next_row, 0), Bias::Right);
 75    if point.row() > start.row() {
 76        *point.column_mut() = map.column_from_chars(point.row(), goal_column);
 77    } else {
 78        point = map.max_point();
 79        goal_column = map.column_to_chars(point.row(), point.column())
 80    }
 81
 82    let clip_bias = if point.column() == map.line_len(point.row()) {
 83        Bias::Left
 84    } else {
 85        Bias::Right
 86    };
 87
 88    Ok((
 89        map.clip_point(point, clip_bias),
 90        SelectionGoal::Column(goal_column),
 91    ))
 92}
 93
 94pub fn line_beginning(
 95    map: &DisplaySnapshot,
 96    point: DisplayPoint,
 97    toggle_indent: bool,
 98) -> DisplayPoint {
 99    let (indent, is_blank) = map.line_indent(point.row());
100    if toggle_indent && !is_blank && point.column() != indent {
101        DisplayPoint::new(point.row(), indent)
102    } else {
103        DisplayPoint::new(point.row(), 0)
104    }
105}
106
107pub fn line_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
108    let line_end = DisplayPoint::new(point.row(), map.line_len(point.row()));
109    map.clip_point(line_end, Bias::Left)
110}
111
112pub fn prev_word_boundary(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
113    let mut line_start = 0;
114    if point.row() > 0 {
115        if let Some(indent) = map.soft_wrap_indent(point.row() - 1) {
116            line_start = indent;
117        }
118    }
119
120    if point.column() == line_start {
121        if point.row() == 0 {
122            return DisplayPoint::new(0, 0);
123        } else {
124            let row = point.row() - 1;
125            point = map.clip_point(DisplayPoint::new(row, map.line_len(row)), Bias::Left);
126        }
127    }
128
129    let mut boundary = DisplayPoint::new(point.row(), 0);
130    let mut column = 0;
131    let mut prev_char_kind = CharKind::Newline;
132    for c in map.chars_at(DisplayPoint::new(point.row(), 0)) {
133        if column >= point.column() {
134            break;
135        }
136
137        let char_kind = char_kind(c);
138        if char_kind != prev_char_kind
139            && char_kind != CharKind::Whitespace
140            && char_kind != CharKind::Newline
141        {
142            *boundary.column_mut() = column;
143        }
144
145        prev_char_kind = char_kind;
146        column += c.len_utf8() as u32;
147    }
148    boundary
149}
150
151pub fn next_word_boundary(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
152    let mut prev_char_kind = None;
153    for c in map.chars_at(point) {
154        let char_kind = char_kind(c);
155        if let Some(prev_char_kind) = prev_char_kind {
156            if c == '\n' {
157                break;
158            }
159            if prev_char_kind != char_kind
160                && prev_char_kind != CharKind::Whitespace
161                && prev_char_kind != CharKind::Newline
162            {
163                break;
164            }
165        }
166
167        if c == '\n' {
168            *point.row_mut() += 1;
169            *point.column_mut() = 0;
170        } else {
171            *point.column_mut() += c.len_utf8() as u32;
172        }
173        prev_char_kind = Some(char_kind);
174    }
175    point
176}
177
178pub fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
179    let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
180    let text = &map.buffer_snapshot;
181    let next_char_kind = text.chars_at(ix).next().map(char_kind);
182    let prev_char_kind = text.reversed_chars_at(ix).next().map(char_kind);
183    prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
184}
185
186pub fn surrounding_word(map: &DisplaySnapshot, point: DisplayPoint) -> Range<DisplayPoint> {
187    let mut start = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
188    let mut end = start;
189
190    let text = &map.buffer_snapshot;
191    let mut next_chars = text.chars_at(start).peekable();
192    let mut prev_chars = text.reversed_chars_at(start).peekable();
193    let word_kind = cmp::max(
194        prev_chars.peek().copied().map(char_kind),
195        next_chars.peek().copied().map(char_kind),
196    );
197
198    for ch in prev_chars {
199        if Some(char_kind(ch)) == word_kind {
200            start -= ch.len_utf8();
201        } else {
202            break;
203        }
204    }
205
206    for ch in next_chars {
207        if Some(char_kind(ch)) == word_kind {
208            end += ch.len_utf8();
209        } else {
210            break;
211        }
212    }
213
214    start.to_point(&map.buffer_snapshot).to_display_point(map)
215        ..end.to_point(&map.buffer_snapshot).to_display_point(map)
216}
217
218#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
219enum CharKind {
220    Newline,
221    Punctuation,
222    Whitespace,
223    Word,
224}
225
226fn char_kind(c: char) -> CharKind {
227    if c == '\n' {
228        CharKind::Newline
229    } else if c.is_whitespace() {
230        CharKind::Whitespace
231    } else if c.is_alphanumeric() || c == '_' {
232        CharKind::Word
233    } else {
234        CharKind::Punctuation
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use crate::{Buffer, DisplayMap, ExcerptProperties, MultiBuffer};
242    use language::Point;
243
244    #[gpui::test]
245    fn test_move_up_and_down_with_excerpts(cx: &mut gpui::MutableAppContext) {
246        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
247        let font_id = cx
248            .font_cache()
249            .select_font(family_id, &Default::default())
250            .unwrap();
251
252        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefg\nhijkl\nmn", cx));
253        let multibuffer = cx.add_model(|cx| {
254            let mut multibuffer = MultiBuffer::new(0);
255            multibuffer.push_excerpt(
256                ExcerptProperties {
257                    buffer: &buffer,
258                    range: Point::new(0, 0)..Point::new(1, 4),
259                    header_height: 2,
260                    render_header: None,
261                },
262                cx,
263            );
264            multibuffer.push_excerpt(
265                ExcerptProperties {
266                    buffer: &buffer,
267                    range: Point::new(2, 0)..Point::new(3, 2),
268                    header_height: 3,
269                    render_header: None,
270                },
271                cx,
272            );
273            multibuffer
274        });
275
276        let display_map =
277            cx.add_model(|cx| DisplayMap::new(multibuffer, 2, font_id, 14.0, None, cx));
278
279        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
280        assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\n\nhijkl\nmn");
281
282        // Can't move up into the first excerpt's header
283        assert_eq!(
284            up(&snapshot, DisplayPoint::new(2, 2), SelectionGoal::Column(2)).unwrap(),
285            (DisplayPoint::new(2, 0), SelectionGoal::Column(0)),
286        );
287        assert_eq!(
288            up(&snapshot, DisplayPoint::new(2, 0), SelectionGoal::None).unwrap(),
289            (DisplayPoint::new(2, 0), SelectionGoal::Column(0)),
290        );
291
292        // Move up and down within first excerpt
293        assert_eq!(
294            up(&snapshot, DisplayPoint::new(3, 4), SelectionGoal::Column(4)).unwrap(),
295            (DisplayPoint::new(2, 3), SelectionGoal::Column(4)),
296        );
297        assert_eq!(
298            down(&snapshot, DisplayPoint::new(2, 3), SelectionGoal::Column(4)).unwrap(),
299            (DisplayPoint::new(3, 4), SelectionGoal::Column(4)),
300        );
301
302        // Move up and down across second excerpt's header
303        assert_eq!(
304            up(&snapshot, DisplayPoint::new(7, 5), SelectionGoal::Column(5)).unwrap(),
305            (DisplayPoint::new(3, 4), SelectionGoal::Column(5)),
306        );
307        assert_eq!(
308            down(&snapshot, DisplayPoint::new(3, 4), SelectionGoal::Column(5)).unwrap(),
309            (DisplayPoint::new(7, 5), SelectionGoal::Column(5)),
310        );
311
312        // Can't move down off the end
313        assert_eq!(
314            down(&snapshot, DisplayPoint::new(8, 0), SelectionGoal::Column(0)).unwrap(),
315            (DisplayPoint::new(8, 2), SelectionGoal::Column(2)),
316        );
317        assert_eq!(
318            down(&snapshot, DisplayPoint::new(8, 2), SelectionGoal::Column(2)).unwrap(),
319            (DisplayPoint::new(8, 2), SelectionGoal::Column(2)),
320        );
321    }
322
323    #[gpui::test]
324    fn test_prev_next_word_boundary_multibyte(cx: &mut gpui::MutableAppContext) {
325        let tab_size = 4;
326        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
327        let font_id = cx
328            .font_cache()
329            .select_font(family_id, &Default::default())
330            .unwrap();
331        let font_size = 14.0;
332
333        let buffer = MultiBuffer::build_simple("a bcΔ defγ hi—jk", cx);
334        let display_map =
335            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
336        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
337        assert_eq!(
338            prev_word_boundary(&snapshot, DisplayPoint::new(0, 12)),
339            DisplayPoint::new(0, 7)
340        );
341        assert_eq!(
342            prev_word_boundary(&snapshot, DisplayPoint::new(0, 7)),
343            DisplayPoint::new(0, 2)
344        );
345        assert_eq!(
346            prev_word_boundary(&snapshot, DisplayPoint::new(0, 6)),
347            DisplayPoint::new(0, 2)
348        );
349        assert_eq!(
350            prev_word_boundary(&snapshot, DisplayPoint::new(0, 2)),
351            DisplayPoint::new(0, 0)
352        );
353        assert_eq!(
354            prev_word_boundary(&snapshot, DisplayPoint::new(0, 1)),
355            DisplayPoint::new(0, 0)
356        );
357
358        assert_eq!(
359            next_word_boundary(&snapshot, DisplayPoint::new(0, 0)),
360            DisplayPoint::new(0, 1)
361        );
362        assert_eq!(
363            next_word_boundary(&snapshot, DisplayPoint::new(0, 1)),
364            DisplayPoint::new(0, 6)
365        );
366        assert_eq!(
367            next_word_boundary(&snapshot, DisplayPoint::new(0, 2)),
368            DisplayPoint::new(0, 6)
369        );
370        assert_eq!(
371            next_word_boundary(&snapshot, DisplayPoint::new(0, 6)),
372            DisplayPoint::new(0, 12)
373        );
374        assert_eq!(
375            next_word_boundary(&snapshot, DisplayPoint::new(0, 7)),
376            DisplayPoint::new(0, 12)
377        );
378    }
379
380    #[gpui::test]
381    fn test_surrounding_word(cx: &mut gpui::MutableAppContext) {
382        let tab_size = 4;
383        let family_id = cx.font_cache().load_family(&["Helvetica"]).unwrap();
384        let font_id = cx
385            .font_cache()
386            .select_font(family_id, &Default::default())
387            .unwrap();
388        let font_size = 14.0;
389        let buffer = MultiBuffer::build_simple("lorem ipsum   dolor\n    sit", cx);
390        let display_map =
391            cx.add_model(|cx| DisplayMap::new(buffer, tab_size, font_id, font_size, None, cx));
392        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
393
394        assert_eq!(
395            surrounding_word(&snapshot, DisplayPoint::new(0, 0)),
396            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5)
397        );
398        assert_eq!(
399            surrounding_word(&snapshot, DisplayPoint::new(0, 2)),
400            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5)
401        );
402        assert_eq!(
403            surrounding_word(&snapshot, DisplayPoint::new(0, 5)),
404            DisplayPoint::new(0, 0)..DisplayPoint::new(0, 5)
405        );
406        assert_eq!(
407            surrounding_word(&snapshot, DisplayPoint::new(0, 6)),
408            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11)
409        );
410        assert_eq!(
411            surrounding_word(&snapshot, DisplayPoint::new(0, 7)),
412            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11)
413        );
414        assert_eq!(
415            surrounding_word(&snapshot, DisplayPoint::new(0, 11)),
416            DisplayPoint::new(0, 6)..DisplayPoint::new(0, 11)
417        );
418        assert_eq!(
419            surrounding_word(&snapshot, DisplayPoint::new(0, 13)),
420            DisplayPoint::new(0, 11)..DisplayPoint::new(0, 14)
421        );
422        assert_eq!(
423            surrounding_word(&snapshot, DisplayPoint::new(0, 14)),
424            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19)
425        );
426        assert_eq!(
427            surrounding_word(&snapshot, DisplayPoint::new(0, 17)),
428            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19)
429        );
430        assert_eq!(
431            surrounding_word(&snapshot, DisplayPoint::new(0, 19)),
432            DisplayPoint::new(0, 14)..DisplayPoint::new(0, 19)
433        );
434        assert_eq!(
435            surrounding_word(&snapshot, DisplayPoint::new(1, 0)),
436            DisplayPoint::new(1, 0)..DisplayPoint::new(1, 4)
437        );
438        assert_eq!(
439            surrounding_word(&snapshot, DisplayPoint::new(1, 1)),
440            DisplayPoint::new(1, 0)..DisplayPoint::new(1, 4)
441        );
442        assert_eq!(
443            surrounding_word(&snapshot, DisplayPoint::new(1, 6)),
444            DisplayPoint::new(1, 4)..DisplayPoint::new(1, 7)
445        );
446        assert_eq!(
447            surrounding_word(&snapshot, DisplayPoint::new(1, 7)),
448            DisplayPoint::new(1, 4)..DisplayPoint::new(1, 7)
449        );
450    }
451}