movement.rs

  1//! Movement module contains helper functions for calculating intended position
  2//! in editor given a given motion (e.g. it handles converting a "move left" command into coordinates in editor). It is exposed mostly for use by vim crate.
  3
  4use super::{Bias, DisplayPoint, DisplaySnapshot, SelectionGoal, ToDisplayPoint};
  5use crate::{char_kind, CharKind, EditorStyle, ToOffset, ToPoint};
  6use gpui::{px, Pixels, TextSystem};
  7use language::Point;
  8
  9use std::{ops::Range, sync::Arc};
 10
 11/// Defines search strategy for items in `movement` module.
 12/// `FindRange::SingeLine` only looks for a match on a single line at a time, whereas
 13/// `FindRange::MultiLine` keeps going until the end of a string.
 14#[derive(Debug, PartialEq)]
 15pub enum FindRange {
 16    SingleLine,
 17    MultiLine,
 18}
 19
 20/// TextLayoutDetails encompasses everything we need to move vertically
 21/// taking into account variable width characters.
 22pub struct TextLayoutDetails {
 23    pub(crate) text_system: Arc<TextSystem>,
 24    pub(crate) editor_style: EditorStyle,
 25    pub(crate) rem_size: Pixels,
 26}
 27
 28/// Returns a column to the left of the current point, wrapping
 29/// to the previous line if that point is at the start of line.
 30pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
 31    if point.column() > 0 {
 32        *point.column_mut() -= 1;
 33    } else if point.row() > 0 {
 34        *point.row_mut() -= 1;
 35        *point.column_mut() = map.line_len(point.row());
 36    }
 37    map.clip_point(point, Bias::Left)
 38}
 39
 40/// Returns a column to the left of the current point, doing nothing if
 41/// that point is already at the start of line.
 42pub fn saturating_left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
 43    if point.column() > 0 {
 44        *point.column_mut() -= 1;
 45    }
 46    map.clip_point(point, Bias::Left)
 47}
 48
 49/// Returns a column to the right of the current point, wrapping
 50/// to the next line if that point is at the end of line.
 51pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
 52    let max_column = map.line_len(point.row());
 53    if point.column() < max_column {
 54        *point.column_mut() += 1;
 55    } else if point.row() < map.max_point().row() {
 56        *point.row_mut() += 1;
 57        *point.column_mut() = 0;
 58    }
 59    map.clip_point(point, Bias::Right)
 60}
 61
 62/// Returns a column to the right of the current point, not performing any wrapping
 63/// if that point is already at the end of line.
 64pub fn saturating_right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
 65    *point.column_mut() += 1;
 66    map.clip_point(point, Bias::Right)
 67}
 68
 69/// Returns a display point for the preceding displayed line (which might be a soft-wrapped line).
 70pub fn up(
 71    map: &DisplaySnapshot,
 72    start: DisplayPoint,
 73    goal: SelectionGoal,
 74    preserve_column_at_start: bool,
 75    text_layout_details: &TextLayoutDetails,
 76) -> (DisplayPoint, SelectionGoal) {
 77    up_by_rows(
 78        map,
 79        start,
 80        1,
 81        goal,
 82        preserve_column_at_start,
 83        text_layout_details,
 84    )
 85}
 86
 87/// Returns a display point for the next displayed line (which might be a soft-wrapped line).
 88pub fn down(
 89    map: &DisplaySnapshot,
 90    start: DisplayPoint,
 91    goal: SelectionGoal,
 92    preserve_column_at_end: bool,
 93    text_layout_details: &TextLayoutDetails,
 94) -> (DisplayPoint, SelectionGoal) {
 95    down_by_rows(
 96        map,
 97        start,
 98        1,
 99        goal,
100        preserve_column_at_end,
101        text_layout_details,
102    )
103}
104
105pub(crate) fn up_by_rows(
106    map: &DisplaySnapshot,
107    start: DisplayPoint,
108    row_count: u32,
109    goal: SelectionGoal,
110    preserve_column_at_start: bool,
111    text_layout_details: &TextLayoutDetails,
112) -> (DisplayPoint, SelectionGoal) {
113    let mut goal_x = match goal {
114        SelectionGoal::HorizontalPosition(x) => x.into(),
115        SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
116        SelectionGoal::HorizontalRange { end, .. } => end.into(),
117        _ => map.x_for_display_point(start, text_layout_details),
118    };
119
120    let prev_row = start.row().saturating_sub(row_count);
121    let mut point = map.clip_point(
122        DisplayPoint::new(prev_row, map.line_len(prev_row)),
123        Bias::Left,
124    );
125    if point.row() < start.row() {
126        *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
127    } else if preserve_column_at_start {
128        return (start, goal);
129    } else {
130        point = DisplayPoint::new(0, 0);
131        goal_x = px(0.);
132    }
133
134    let mut clipped_point = map.clip_point(point, Bias::Left);
135    if clipped_point.row() < point.row() {
136        clipped_point = map.clip_point(point, Bias::Right);
137    }
138    (
139        clipped_point,
140        SelectionGoal::HorizontalPosition(goal_x.into()),
141    )
142}
143
144pub(crate) fn down_by_rows(
145    map: &DisplaySnapshot,
146    start: DisplayPoint,
147    row_count: u32,
148    goal: SelectionGoal,
149    preserve_column_at_end: bool,
150    text_layout_details: &TextLayoutDetails,
151) -> (DisplayPoint, SelectionGoal) {
152    let mut goal_x = match goal {
153        SelectionGoal::HorizontalPosition(x) => x.into(),
154        SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
155        SelectionGoal::HorizontalRange { end, .. } => end.into(),
156        _ => map.x_for_display_point(start, text_layout_details),
157    };
158
159    let new_row = start.row() + row_count;
160    let mut point = map.clip_point(DisplayPoint::new(new_row, 0), Bias::Right);
161    if point.row() > start.row() {
162        *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
163    } else if preserve_column_at_end {
164        return (start, goal);
165    } else {
166        point = map.max_point();
167        goal_x = map.x_for_display_point(point, text_layout_details)
168    }
169
170    let mut clipped_point = map.clip_point(point, Bias::Right);
171    if clipped_point.row() > point.row() {
172        clipped_point = map.clip_point(point, Bias::Left);
173    }
174    (
175        clipped_point,
176        SelectionGoal::HorizontalPosition(goal_x.into()),
177    )
178}
179
180/// Returns a position of the start of line.
181/// If `stop_at_soft_boundaries` is true, the returned position is that of the
182/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
183/// Otherwise it's always going to be the start of a logical line.
184pub fn line_beginning(
185    map: &DisplaySnapshot,
186    display_point: DisplayPoint,
187    stop_at_soft_boundaries: bool,
188) -> DisplayPoint {
189    let point = display_point.to_point(map);
190    let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
191    let line_start = map.prev_line_boundary(point).1;
192
193    if stop_at_soft_boundaries && display_point != soft_line_start {
194        soft_line_start
195    } else {
196        line_start
197    }
198}
199
200/// Returns the last indented position on a given line.
201/// If `stop_at_soft_boundaries` is true, the returned [`DisplayPoint`] is that of a
202/// displayed line (e.g. if there's soft wrap it's gonna be returned),
203/// otherwise it's always going to be a start of a logical line.
204pub fn indented_line_beginning(
205    map: &DisplaySnapshot,
206    display_point: DisplayPoint,
207    stop_at_soft_boundaries: bool,
208) -> DisplayPoint {
209    let point = display_point.to_point(map);
210    let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
211    let indent_start = Point::new(
212        point.row,
213        map.buffer_snapshot.indent_size_for_line(point.row).len,
214    )
215    .to_display_point(map);
216    let line_start = map.prev_line_boundary(point).1;
217
218    if stop_at_soft_boundaries && soft_line_start > indent_start && display_point != soft_line_start
219    {
220        soft_line_start
221    } else if stop_at_soft_boundaries && display_point != indent_start {
222        indent_start
223    } else {
224        line_start
225    }
226}
227
228/// Returns a position of the end of line.
229
230/// If `stop_at_soft_boundaries` is true, the returned position is that of the
231/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
232/// Otherwise it's always going to be the end of a logical line.
233pub fn line_end(
234    map: &DisplaySnapshot,
235    display_point: DisplayPoint,
236    stop_at_soft_boundaries: bool,
237) -> DisplayPoint {
238    let soft_line_end = map.clip_point(
239        DisplayPoint::new(display_point.row(), map.line_len(display_point.row())),
240        Bias::Left,
241    );
242    if stop_at_soft_boundaries && display_point != soft_line_end {
243        soft_line_end
244    } else {
245        map.next_line_boundary(display_point.to_point(map)).1
246    }
247}
248
249/// Returns a position of the previous word boundary, where a word character is defined as either
250/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
251pub fn previous_word_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
252    let raw_point = point.to_point(map);
253    let scope = map.buffer_snapshot.language_scope_at(raw_point);
254
255    find_preceding_boundary(map, point, FindRange::MultiLine, |left, right| {
256        (char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace())
257            || left == '\n'
258    })
259}
260
261/// Returns a position of the previous subword boundary, where a subword is defined as a run of
262/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
263/// lowerspace characters and uppercase characters.
264pub fn previous_subword_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
265    let raw_point = point.to_point(map);
266    let scope = map.buffer_snapshot.language_scope_at(raw_point);
267
268    find_preceding_boundary(map, point, FindRange::MultiLine, |left, right| {
269        let is_word_start =
270            char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace();
271        let is_subword_start =
272            left == '_' && right != '_' || left.is_lowercase() && right.is_uppercase();
273        is_word_start || is_subword_start || left == '\n'
274    })
275}
276
277/// Returns a position of the next word boundary, where a word character is defined as either
278/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
279pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
280    let raw_point = point.to_point(map);
281    let scope = map.buffer_snapshot.language_scope_at(raw_point);
282
283    find_boundary(map, point, FindRange::MultiLine, |left, right| {
284        (char_kind(&scope, left) != char_kind(&scope, right) && !left.is_whitespace())
285            || right == '\n'
286    })
287}
288
289/// Returns a position of the next subword boundary, where a subword is defined as a run of
290/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
291/// lowerspace characters and uppercase characters.
292pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
293    let raw_point = point.to_point(map);
294    let scope = map.buffer_snapshot.language_scope_at(raw_point);
295
296    find_boundary(map, point, FindRange::MultiLine, |left, right| {
297        let is_word_end =
298            (char_kind(&scope, left) != char_kind(&scope, right)) && !left.is_whitespace();
299        let is_subword_end =
300            left != '_' && right == '_' || left.is_lowercase() && right.is_uppercase();
301        is_word_end || is_subword_end || right == '\n'
302    })
303}
304
305/// Returns a position of the start of the current paragraph, where a paragraph
306/// is defined as a run of non-blank lines.
307pub fn start_of_paragraph(
308    map: &DisplaySnapshot,
309    display_point: DisplayPoint,
310    mut count: usize,
311) -> DisplayPoint {
312    let point = display_point.to_point(map);
313    if point.row == 0 {
314        return DisplayPoint::zero();
315    }
316
317    let mut found_non_blank_line = false;
318    for row in (0..point.row + 1).rev() {
319        let blank = map.buffer_snapshot.is_line_blank(row);
320        if found_non_blank_line && blank {
321            if count <= 1 {
322                return Point::new(row, 0).to_display_point(map);
323            }
324            count -= 1;
325            found_non_blank_line = false;
326        }
327
328        found_non_blank_line |= !blank;
329    }
330
331    DisplayPoint::zero()
332}
333
334/// Returns a position of the end of the current paragraph, where a paragraph
335/// is defined as a run of non-blank lines.
336pub fn end_of_paragraph(
337    map: &DisplaySnapshot,
338    display_point: DisplayPoint,
339    mut count: usize,
340) -> DisplayPoint {
341    let point = display_point.to_point(map);
342    if point.row == map.max_buffer_row() {
343        return map.max_point();
344    }
345
346    let mut found_non_blank_line = false;
347    for row in point.row..map.max_buffer_row() + 1 {
348        let blank = map.buffer_snapshot.is_line_blank(row);
349        if found_non_blank_line && blank {
350            if count <= 1 {
351                return Point::new(row, 0).to_display_point(map);
352            }
353            count -= 1;
354            found_non_blank_line = false;
355        }
356
357        found_non_blank_line |= !blank;
358    }
359
360    map.max_point()
361}
362
363/// Scans for a boundary preceding the given start point `from` until a boundary is found,
364/// indicated by the given predicate returning true.
365/// The predicate is called with the character to the left and right of the candidate boundary location.
366/// If FindRange::SingleLine is specified and no boundary is found before the start of the current line, the start of the current line will be returned.
367pub fn find_preceding_boundary(
368    map: &DisplaySnapshot,
369    from: DisplayPoint,
370    find_range: FindRange,
371    mut is_boundary: impl FnMut(char, char) -> bool,
372) -> DisplayPoint {
373    let mut prev_ch = None;
374    let mut offset = from.to_point(map).to_offset(&map.buffer_snapshot);
375
376    for ch in map.buffer_snapshot.reversed_chars_at(offset) {
377        if find_range == FindRange::SingleLine && ch == '\n' {
378            break;
379        }
380        if let Some(prev_ch) = prev_ch {
381            if is_boundary(ch, prev_ch) {
382                break;
383            }
384        }
385
386        offset -= ch.len_utf8();
387        prev_ch = Some(ch);
388    }
389
390    map.clip_point(offset.to_display_point(map), Bias::Left)
391}
392
393/// Scans for a boundary following the given start point until a boundary is found, indicated by the
394/// given predicate returning true. The predicate is called with the character to the left and right
395/// of the candidate boundary location, and will be called with `\n` characters indicating the start
396/// or end of a line.
397pub fn find_boundary(
398    map: &DisplaySnapshot,
399    from: DisplayPoint,
400    find_range: FindRange,
401    mut is_boundary: impl FnMut(char, char) -> bool,
402) -> DisplayPoint {
403    let mut offset = from.to_offset(&map, Bias::Right);
404    let mut prev_ch = None;
405
406    for ch in map.buffer_snapshot.chars_at(offset) {
407        if find_range == FindRange::SingleLine && ch == '\n' {
408            break;
409        }
410        if let Some(prev_ch) = prev_ch {
411            if is_boundary(prev_ch, ch) {
412                break;
413            }
414        }
415
416        offset += ch.len_utf8();
417        prev_ch = Some(ch);
418    }
419    map.clip_point(offset.to_display_point(map), Bias::Right)
420}
421
422/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
423/// The returned value also contains a range of the start/end of a returned character in
424/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
425pub fn chars_after(
426    map: &DisplaySnapshot,
427    mut offset: usize,
428) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
429    map.buffer_snapshot.chars_at(offset).map(move |ch| {
430        let before = offset;
431        offset = offset + ch.len_utf8();
432        (ch, before..offset)
433    })
434}
435
436/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
437/// The returned value also contains a range of the start/end of a returned character in
438/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
439pub fn chars_before(
440    map: &DisplaySnapshot,
441    mut offset: usize,
442) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
443    map.buffer_snapshot
444        .reversed_chars_at(offset)
445        .map(move |ch| {
446            let after = offset;
447            offset = offset - ch.len_utf8();
448            (ch, offset..after)
449        })
450}
451
452pub(crate) fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
453    let raw_point = point.to_point(map);
454    let scope = map.buffer_snapshot.language_scope_at(raw_point);
455    let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
456    let text = &map.buffer_snapshot;
457    let next_char_kind = text.chars_at(ix).next().map(|c| char_kind(&scope, c));
458    let prev_char_kind = text
459        .reversed_chars_at(ix)
460        .next()
461        .map(|c| char_kind(&scope, c));
462    prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
463}
464
465pub(crate) fn surrounding_word(
466    map: &DisplaySnapshot,
467    position: DisplayPoint,
468) -> Range<DisplayPoint> {
469    let position = map
470        .clip_point(position, Bias::Left)
471        .to_offset(map, Bias::Left);
472    let (range, _) = map.buffer_snapshot.surrounding_word(position);
473    let start = range
474        .start
475        .to_point(&map.buffer_snapshot)
476        .to_display_point(map);
477    let end = range
478        .end
479        .to_point(&map.buffer_snapshot)
480        .to_display_point(map);
481    start..end
482}
483
484/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
485/// within a passed range.
486///
487/// The line ranges are **always* going to be in bounds of a requested range, which means that
488/// the first and the last lines might not necessarily represent the
489/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
490pub fn split_display_range_by_lines(
491    map: &DisplaySnapshot,
492    range: Range<DisplayPoint>,
493) -> Vec<Range<DisplayPoint>> {
494    let mut result = Vec::new();
495
496    let mut start = range.start;
497    // Loop over all the covered rows until the one containing the range end
498    for row in range.start.row()..range.end.row() {
499        let row_end_column = map.line_len(row);
500        let end = map.clip_point(DisplayPoint::new(row, row_end_column), Bias::Left);
501        if start != end {
502            result.push(start..end);
503        }
504        start = map.clip_point(DisplayPoint::new(row + 1, 0), Bias::Left);
505    }
506
507    // Add the final range from the start of the last end to the original range end.
508    result.push(start..range.end);
509
510    result
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516    use crate::{
517        display_map::Inlay,
518        test::{editor_test_context::EditorTestContext, marked_display_snapshot},
519        Buffer, DisplayMap, ExcerptRange, InlayId, MultiBuffer,
520    };
521    use gpui::{font, Context as _};
522    use language::Capability;
523    use project::Project;
524    use settings::SettingsStore;
525    use util::post_inc;
526
527    #[gpui::test]
528    fn test_previous_word_start(cx: &mut gpui::AppContext) {
529        init_test(cx);
530
531        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
532            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
533            assert_eq!(
534                previous_word_start(&snapshot, display_points[1]),
535                display_points[0]
536            );
537        }
538
539        assert("\nˇ   ˇlorem", cx);
540        assert("ˇ\nˇ   lorem", cx);
541        assert("    ˇloremˇ", cx);
542        assert("ˇ    ˇlorem", cx);
543        assert("    ˇlorˇem", cx);
544        assert("\nlorem\nˇ   ˇipsum", cx);
545        assert("\n\nˇ\nˇ", cx);
546        assert("    ˇlorem  ˇipsum", cx);
547        assert("loremˇ-ˇipsum", cx);
548        assert("loremˇ-#$@ˇipsum", cx);
549        assert("ˇlorem_ˇipsum", cx);
550        assert(" ˇdefγˇ", cx);
551        assert(" ˇbcΔˇ", cx);
552        assert(" abˇ——ˇcd", cx);
553    }
554
555    #[gpui::test]
556    fn test_previous_subword_start(cx: &mut gpui::AppContext) {
557        init_test(cx);
558
559        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
560            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
561            assert_eq!(
562                previous_subword_start(&snapshot, display_points[1]),
563                display_points[0]
564            );
565        }
566
567        // Subword boundaries are respected
568        assert("lorem_ˇipˇsum", cx);
569        assert("lorem_ˇipsumˇ", cx);
570        assert("ˇlorem_ˇipsum", cx);
571        assert("lorem_ˇipsum_ˇdolor", cx);
572        assert("loremˇIpˇsum", cx);
573        assert("loremˇIpsumˇ", cx);
574
575        // Word boundaries are still respected
576        assert("\nˇ   ˇlorem", cx);
577        assert("    ˇloremˇ", cx);
578        assert("    ˇlorˇem", cx);
579        assert("\nlorem\nˇ   ˇipsum", cx);
580        assert("\n\nˇ\nˇ", cx);
581        assert("    ˇlorem  ˇipsum", cx);
582        assert("loremˇ-ˇipsum", cx);
583        assert("loremˇ-#$@ˇipsum", cx);
584        assert(" ˇdefγˇ", cx);
585        assert(" bcˇΔˇ", cx);
586        assert(" ˇbcδˇ", cx);
587        assert(" abˇ——ˇcd", cx);
588    }
589
590    #[gpui::test]
591    fn test_find_preceding_boundary(cx: &mut gpui::AppContext) {
592        init_test(cx);
593
594        fn assert(
595            marked_text: &str,
596            cx: &mut gpui::AppContext,
597            is_boundary: impl FnMut(char, char) -> bool,
598        ) {
599            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
600            assert_eq!(
601                find_preceding_boundary(
602                    &snapshot,
603                    display_points[1],
604                    FindRange::MultiLine,
605                    is_boundary
606                ),
607                display_points[0]
608            );
609        }
610
611        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
612            left == 'c' && right == 'd'
613        });
614        assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
615            left == '\n' && right == 'g'
616        });
617        let mut line_count = 0;
618        assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
619            if left == '\n' {
620                line_count += 1;
621                line_count == 2
622            } else {
623                false
624            }
625        });
626    }
627
628    #[gpui::test]
629    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::AppContext) {
630        init_test(cx);
631
632        let input_text = "abcdefghijklmnopqrstuvwxys";
633        let font = font("Helvetica");
634        let font_size = px(14.0);
635        let buffer = MultiBuffer::build_simple(input_text, cx);
636        let buffer_snapshot = buffer.read(cx).snapshot(cx);
637        let display_map =
638            cx.new_model(|cx| DisplayMap::new(buffer, font, font_size, None, 1, 1, cx));
639
640        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
641        let mut id = 0;
642        let inlays = (0..buffer_snapshot.len())
643            .map(|offset| {
644                [
645                    Inlay {
646                        id: InlayId::Suggestion(post_inc(&mut id)),
647                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
648                        text: format!("test").into(),
649                    },
650                    Inlay {
651                        id: InlayId::Suggestion(post_inc(&mut id)),
652                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
653                        text: format!("test").into(),
654                    },
655                    Inlay {
656                        id: InlayId::Hint(post_inc(&mut id)),
657                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
658                        text: format!("test").into(),
659                    },
660                    Inlay {
661                        id: InlayId::Hint(post_inc(&mut id)),
662                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
663                        text: format!("test").into(),
664                    },
665                ]
666            })
667            .flatten()
668            .collect();
669        let snapshot = display_map.update(cx, |map, cx| {
670            map.splice_inlays(Vec::new(), inlays, cx);
671            map.snapshot(cx)
672        });
673
674        assert_eq!(
675            find_preceding_boundary(
676                &snapshot,
677                buffer_snapshot.len().to_display_point(&snapshot),
678                FindRange::MultiLine,
679                |left, _| left == 'e',
680            ),
681            snapshot
682                .buffer_snapshot
683                .offset_to_point(5)
684                .to_display_point(&snapshot),
685            "Should not stop at inlays when looking for boundaries"
686        );
687    }
688
689    #[gpui::test]
690    fn test_next_word_end(cx: &mut gpui::AppContext) {
691        init_test(cx);
692
693        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
694            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
695            assert_eq!(
696                next_word_end(&snapshot, display_points[0]),
697                display_points[1]
698            );
699        }
700
701        assert("\nˇ   loremˇ", cx);
702        assert("    ˇloremˇ", cx);
703        assert("    lorˇemˇ", cx);
704        assert("    loremˇ    ˇ\nipsum\n", cx);
705        assert("\nˇ\nˇ\n\n", cx);
706        assert("loremˇ    ipsumˇ   ", cx);
707        assert("loremˇ-ˇipsum", cx);
708        assert("loremˇ#$@-ˇipsum", cx);
709        assert("loremˇ_ipsumˇ", cx);
710        assert(" ˇbcΔˇ", cx);
711        assert(" abˇ——ˇcd", cx);
712    }
713
714    #[gpui::test]
715    fn test_next_subword_end(cx: &mut gpui::AppContext) {
716        init_test(cx);
717
718        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
719            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
720            assert_eq!(
721                next_subword_end(&snapshot, display_points[0]),
722                display_points[1]
723            );
724        }
725
726        // Subword boundaries are respected
727        assert("loˇremˇ_ipsum", cx);
728        assert("ˇloremˇ_ipsum", cx);
729        assert("loremˇ_ipsumˇ", cx);
730        assert("loremˇ_ipsumˇ_dolor", cx);
731        assert("loˇremˇIpsum", cx);
732        assert("loremˇIpsumˇDolor", cx);
733
734        // Word boundaries are still respected
735        assert("\nˇ   loremˇ", cx);
736        assert("    ˇloremˇ", cx);
737        assert("    lorˇemˇ", cx);
738        assert("    loremˇ    ˇ\nipsum\n", cx);
739        assert("\nˇ\nˇ\n\n", cx);
740        assert("loremˇ    ipsumˇ   ", cx);
741        assert("loremˇ-ˇipsum", cx);
742        assert("loremˇ#$@-ˇipsum", cx);
743        assert("loremˇ_ipsumˇ", cx);
744        assert(" ˇbcˇΔ", cx);
745        assert(" abˇ——ˇcd", cx);
746    }
747
748    #[gpui::test]
749    fn test_find_boundary(cx: &mut gpui::AppContext) {
750        init_test(cx);
751
752        fn assert(
753            marked_text: &str,
754            cx: &mut gpui::AppContext,
755            is_boundary: impl FnMut(char, char) -> bool,
756        ) {
757            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
758            assert_eq!(
759                find_boundary(
760                    &snapshot,
761                    display_points[0],
762                    FindRange::MultiLine,
763                    is_boundary
764                ),
765                display_points[1]
766            );
767        }
768
769        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
770            left == 'j' && right == 'k'
771        });
772        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
773            left == '\n' && right == 'i'
774        });
775        let mut line_count = 0;
776        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
777            if left == '\n' {
778                line_count += 1;
779                line_count == 2
780            } else {
781                false
782            }
783        });
784    }
785
786    #[gpui::test]
787    fn test_surrounding_word(cx: &mut gpui::AppContext) {
788        init_test(cx);
789
790        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
791            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
792            assert_eq!(
793                surrounding_word(&snapshot, display_points[1]),
794                display_points[0]..display_points[2],
795                "{}",
796                marked_text.to_string()
797            );
798        }
799
800        assert("ˇˇloremˇ  ipsum", cx);
801        assert("ˇloˇremˇ  ipsum", cx);
802        assert("ˇloremˇˇ  ipsum", cx);
803        assert("loremˇ ˇ  ˇipsum", cx);
804        assert("lorem\nˇˇˇ\nipsum", cx);
805        assert("lorem\nˇˇipsumˇ", cx);
806        assert("loremˇ,ˇˇ ipsum", cx);
807        assert("ˇloremˇˇ, ipsum", cx);
808    }
809
810    #[gpui::test]
811    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
812        cx.update(|cx| {
813            init_test(cx);
814        });
815
816        let mut cx = EditorTestContext::new(cx).await;
817        let editor = cx.editor.clone();
818        let window = cx.window.clone();
819        _ = cx.update_window(window, |_, cx| {
820            let text_layout_details =
821                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
822
823            let font = font("Helvetica");
824
825            let buffer =
826                cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "abc\ndefg\nhijkl\nmn"));
827            let multibuffer = cx.new_model(|cx| {
828                let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
829                multibuffer.push_excerpts(
830                    buffer.clone(),
831                    [
832                        ExcerptRange {
833                            context: Point::new(0, 0)..Point::new(1, 4),
834                            primary: None,
835                        },
836                        ExcerptRange {
837                            context: Point::new(2, 0)..Point::new(3, 2),
838                            primary: None,
839                        },
840                    ],
841                    cx,
842                );
843                multibuffer
844            });
845            let display_map =
846                cx.new_model(|cx| DisplayMap::new(multibuffer, font, px(14.0), None, 2, 2, cx));
847            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
848
849            assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
850
851            let col_2_x =
852                snapshot.x_for_display_point(DisplayPoint::new(2, 2), &text_layout_details);
853
854            // Can't move up into the first excerpt's header
855            assert_eq!(
856                up(
857                    &snapshot,
858                    DisplayPoint::new(2, 2),
859                    SelectionGoal::HorizontalPosition(col_2_x.0),
860                    false,
861                    &text_layout_details
862                ),
863                (
864                    DisplayPoint::new(2, 0),
865                    SelectionGoal::HorizontalPosition(0.0)
866                ),
867            );
868            assert_eq!(
869                up(
870                    &snapshot,
871                    DisplayPoint::new(2, 0),
872                    SelectionGoal::None,
873                    false,
874                    &text_layout_details
875                ),
876                (
877                    DisplayPoint::new(2, 0),
878                    SelectionGoal::HorizontalPosition(0.0)
879                ),
880            );
881
882            let col_4_x =
883                snapshot.x_for_display_point(DisplayPoint::new(3, 4), &text_layout_details);
884
885            // Move up and down within first excerpt
886            assert_eq!(
887                up(
888                    &snapshot,
889                    DisplayPoint::new(3, 4),
890                    SelectionGoal::HorizontalPosition(col_4_x.0),
891                    false,
892                    &text_layout_details
893                ),
894                (
895                    DisplayPoint::new(2, 3),
896                    SelectionGoal::HorizontalPosition(col_4_x.0)
897                ),
898            );
899            assert_eq!(
900                down(
901                    &snapshot,
902                    DisplayPoint::new(2, 3),
903                    SelectionGoal::HorizontalPosition(col_4_x.0),
904                    false,
905                    &text_layout_details
906                ),
907                (
908                    DisplayPoint::new(3, 4),
909                    SelectionGoal::HorizontalPosition(col_4_x.0)
910                ),
911            );
912
913            let col_5_x =
914                snapshot.x_for_display_point(DisplayPoint::new(6, 5), &text_layout_details);
915
916            // Move up and down across second excerpt's header
917            assert_eq!(
918                up(
919                    &snapshot,
920                    DisplayPoint::new(6, 5),
921                    SelectionGoal::HorizontalPosition(col_5_x.0),
922                    false,
923                    &text_layout_details
924                ),
925                (
926                    DisplayPoint::new(3, 4),
927                    SelectionGoal::HorizontalPosition(col_5_x.0)
928                ),
929            );
930            assert_eq!(
931                down(
932                    &snapshot,
933                    DisplayPoint::new(3, 4),
934                    SelectionGoal::HorizontalPosition(col_5_x.0),
935                    false,
936                    &text_layout_details
937                ),
938                (
939                    DisplayPoint::new(6, 5),
940                    SelectionGoal::HorizontalPosition(col_5_x.0)
941                ),
942            );
943
944            let max_point_x =
945                snapshot.x_for_display_point(DisplayPoint::new(7, 2), &text_layout_details);
946
947            // Can't move down off the end
948            assert_eq!(
949                down(
950                    &snapshot,
951                    DisplayPoint::new(7, 0),
952                    SelectionGoal::HorizontalPosition(0.0),
953                    false,
954                    &text_layout_details
955                ),
956                (
957                    DisplayPoint::new(7, 2),
958                    SelectionGoal::HorizontalPosition(max_point_x.0)
959                ),
960            );
961            assert_eq!(
962                down(
963                    &snapshot,
964                    DisplayPoint::new(7, 2),
965                    SelectionGoal::HorizontalPosition(max_point_x.0),
966                    false,
967                    &text_layout_details
968                ),
969                (
970                    DisplayPoint::new(7, 2),
971                    SelectionGoal::HorizontalPosition(max_point_x.0)
972                ),
973            );
974        });
975    }
976
977    fn init_test(cx: &mut gpui::AppContext) {
978        let settings_store = SettingsStore::test(cx);
979        cx.set_global(settings_store);
980        theme::init(theme::LoadThemes::JustBase, cx);
981        language::init(cx);
982        crate::init(cx);
983        Project::init_settings(cx);
984    }
985}