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 text::BufferId;
526    use util::post_inc;
527
528    #[gpui::test]
529    fn test_previous_word_start(cx: &mut gpui::AppContext) {
530        init_test(cx);
531
532        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
533            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
534            assert_eq!(
535                previous_word_start(&snapshot, display_points[1]),
536                display_points[0]
537            );
538        }
539
540        assert("\nˇ   ˇlorem", cx);
541        assert("ˇ\nˇ   lorem", cx);
542        assert("    ˇloremˇ", cx);
543        assert("ˇ    ˇlorem", cx);
544        assert("    ˇlorˇem", cx);
545        assert("\nlorem\nˇ   ˇipsum", cx);
546        assert("\n\nˇ\nˇ", cx);
547        assert("    ˇlorem  ˇipsum", cx);
548        assert("loremˇ-ˇipsum", cx);
549        assert("loremˇ-#$@ˇipsum", cx);
550        assert("ˇlorem_ˇipsum", cx);
551        assert(" ˇdefγˇ", cx);
552        assert(" ˇbcΔˇ", cx);
553        assert(" abˇ——ˇcd", cx);
554    }
555
556    #[gpui::test]
557    fn test_previous_subword_start(cx: &mut gpui::AppContext) {
558        init_test(cx);
559
560        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
561            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
562            assert_eq!(
563                previous_subword_start(&snapshot, display_points[1]),
564                display_points[0]
565            );
566        }
567
568        // Subword boundaries are respected
569        assert("lorem_ˇipˇsum", cx);
570        assert("lorem_ˇipsumˇ", cx);
571        assert("ˇlorem_ˇipsum", cx);
572        assert("lorem_ˇipsum_ˇdolor", cx);
573        assert("loremˇIpˇsum", cx);
574        assert("loremˇIpsumˇ", cx);
575
576        // Word boundaries are still respected
577        assert("\nˇ   ˇlorem", cx);
578        assert("    ˇloremˇ", cx);
579        assert("    ˇlorˇem", cx);
580        assert("\nlorem\nˇ   ˇipsum", cx);
581        assert("\n\nˇ\nˇ", cx);
582        assert("    ˇlorem  ˇipsum", cx);
583        assert("loremˇ-ˇipsum", cx);
584        assert("loremˇ-#$@ˇipsum", cx);
585        assert(" ˇdefγˇ", cx);
586        assert(" bcˇΔˇ", cx);
587        assert(" ˇbcδˇ", cx);
588        assert(" abˇ——ˇcd", cx);
589    }
590
591    #[gpui::test]
592    fn test_find_preceding_boundary(cx: &mut gpui::AppContext) {
593        init_test(cx);
594
595        fn assert(
596            marked_text: &str,
597            cx: &mut gpui::AppContext,
598            is_boundary: impl FnMut(char, char) -> bool,
599        ) {
600            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
601            assert_eq!(
602                find_preceding_boundary(
603                    &snapshot,
604                    display_points[1],
605                    FindRange::MultiLine,
606                    is_boundary
607                ),
608                display_points[0]
609            );
610        }
611
612        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
613            left == 'c' && right == 'd'
614        });
615        assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
616            left == '\n' && right == 'g'
617        });
618        let mut line_count = 0;
619        assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
620            if left == '\n' {
621                line_count += 1;
622                line_count == 2
623            } else {
624                false
625            }
626        });
627    }
628
629    #[gpui::test]
630    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::AppContext) {
631        init_test(cx);
632
633        let input_text = "abcdefghijklmnopqrstuvwxys";
634        let font = font("Helvetica");
635        let font_size = px(14.0);
636        let buffer = MultiBuffer::build_simple(input_text, cx);
637        let buffer_snapshot = buffer.read(cx).snapshot(cx);
638        let display_map =
639            cx.new_model(|cx| DisplayMap::new(buffer, font, font_size, None, 1, 1, cx));
640
641        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
642        let mut id = 0;
643        let inlays = (0..buffer_snapshot.len())
644            .map(|offset| {
645                [
646                    Inlay {
647                        id: InlayId::Suggestion(post_inc(&mut id)),
648                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
649                        text: format!("test").into(),
650                    },
651                    Inlay {
652                        id: InlayId::Suggestion(post_inc(&mut id)),
653                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
654                        text: format!("test").into(),
655                    },
656                    Inlay {
657                        id: InlayId::Hint(post_inc(&mut id)),
658                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
659                        text: format!("test").into(),
660                    },
661                    Inlay {
662                        id: InlayId::Hint(post_inc(&mut id)),
663                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
664                        text: format!("test").into(),
665                    },
666                ]
667            })
668            .flatten()
669            .collect();
670        let snapshot = display_map.update(cx, |map, cx| {
671            map.splice_inlays(Vec::new(), inlays, cx);
672            map.snapshot(cx)
673        });
674
675        assert_eq!(
676            find_preceding_boundary(
677                &snapshot,
678                buffer_snapshot.len().to_display_point(&snapshot),
679                FindRange::MultiLine,
680                |left, _| left == 'e',
681            ),
682            snapshot
683                .buffer_snapshot
684                .offset_to_point(5)
685                .to_display_point(&snapshot),
686            "Should not stop at inlays when looking for boundaries"
687        );
688    }
689
690    #[gpui::test]
691    fn test_next_word_end(cx: &mut gpui::AppContext) {
692        init_test(cx);
693
694        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
695            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
696            assert_eq!(
697                next_word_end(&snapshot, display_points[0]),
698                display_points[1]
699            );
700        }
701
702        assert("\nˇ   loremˇ", cx);
703        assert("    ˇloremˇ", cx);
704        assert("    lorˇemˇ", cx);
705        assert("    loremˇ    ˇ\nipsum\n", cx);
706        assert("\nˇ\nˇ\n\n", cx);
707        assert("loremˇ    ipsumˇ   ", cx);
708        assert("loremˇ-ˇipsum", cx);
709        assert("loremˇ#$@-ˇipsum", cx);
710        assert("loremˇ_ipsumˇ", cx);
711        assert(" ˇbcΔˇ", cx);
712        assert(" abˇ——ˇcd", cx);
713    }
714
715    #[gpui::test]
716    fn test_next_subword_end(cx: &mut gpui::AppContext) {
717        init_test(cx);
718
719        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
720            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
721            assert_eq!(
722                next_subword_end(&snapshot, display_points[0]),
723                display_points[1]
724            );
725        }
726
727        // Subword boundaries are respected
728        assert("loˇremˇ_ipsum", cx);
729        assert("ˇloremˇ_ipsum", cx);
730        assert("loremˇ_ipsumˇ", cx);
731        assert("loremˇ_ipsumˇ_dolor", cx);
732        assert("loˇremˇIpsum", cx);
733        assert("loremˇIpsumˇDolor", cx);
734
735        // Word boundaries are still respected
736        assert("\nˇ   loremˇ", cx);
737        assert("    ˇloremˇ", cx);
738        assert("    lorˇemˇ", cx);
739        assert("    loremˇ    ˇ\nipsum\n", cx);
740        assert("\nˇ\nˇ\n\n", cx);
741        assert("loremˇ    ipsumˇ   ", cx);
742        assert("loremˇ-ˇipsum", cx);
743        assert("loremˇ#$@-ˇipsum", cx);
744        assert("loremˇ_ipsumˇ", cx);
745        assert(" ˇbcˇΔ", cx);
746        assert(" abˇ——ˇcd", cx);
747    }
748
749    #[gpui::test]
750    fn test_find_boundary(cx: &mut gpui::AppContext) {
751        init_test(cx);
752
753        fn assert(
754            marked_text: &str,
755            cx: &mut gpui::AppContext,
756            is_boundary: impl FnMut(char, char) -> bool,
757        ) {
758            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
759            assert_eq!(
760                find_boundary(
761                    &snapshot,
762                    display_points[0],
763                    FindRange::MultiLine,
764                    is_boundary
765                ),
766                display_points[1]
767            );
768        }
769
770        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
771            left == 'j' && right == 'k'
772        });
773        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
774            left == '\n' && right == 'i'
775        });
776        let mut line_count = 0;
777        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
778            if left == '\n' {
779                line_count += 1;
780                line_count == 2
781            } else {
782                false
783            }
784        });
785    }
786
787    #[gpui::test]
788    fn test_surrounding_word(cx: &mut gpui::AppContext) {
789        init_test(cx);
790
791        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
792            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
793            assert_eq!(
794                surrounding_word(&snapshot, display_points[1]),
795                display_points[0]..display_points[2],
796                "{}",
797                marked_text.to_string()
798            );
799        }
800
801        assert("ˇˇloremˇ  ipsum", cx);
802        assert("ˇloˇremˇ  ipsum", cx);
803        assert("ˇloremˇˇ  ipsum", cx);
804        assert("loremˇ ˇ  ˇipsum", cx);
805        assert("lorem\nˇˇˇ\nipsum", cx);
806        assert("lorem\nˇˇipsumˇ", cx);
807        assert("loremˇ,ˇˇ ipsum", cx);
808        assert("ˇloremˇˇ, ipsum", cx);
809    }
810
811    #[gpui::test]
812    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
813        cx.update(|cx| {
814            init_test(cx);
815        });
816
817        let mut cx = EditorTestContext::new(cx).await;
818        let editor = cx.editor.clone();
819        let window = cx.window.clone();
820        _ = cx.update_window(window, |_, cx| {
821            let text_layout_details =
822                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
823
824            let font = font("Helvetica");
825
826            let buffer = cx.new_model(|cx| {
827                Buffer::new(
828                    0,
829                    BufferId::new(cx.entity_id().as_u64()).unwrap(),
830                    "abc\ndefg\nhijkl\nmn",
831                )
832            });
833            let multibuffer = cx.new_model(|cx| {
834                let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
835                multibuffer.push_excerpts(
836                    buffer.clone(),
837                    [
838                        ExcerptRange {
839                            context: Point::new(0, 0)..Point::new(1, 4),
840                            primary: None,
841                        },
842                        ExcerptRange {
843                            context: Point::new(2, 0)..Point::new(3, 2),
844                            primary: None,
845                        },
846                    ],
847                    cx,
848                );
849                multibuffer
850            });
851            let display_map =
852                cx.new_model(|cx| DisplayMap::new(multibuffer, font, px(14.0), None, 2, 2, cx));
853            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
854
855            assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
856
857            let col_2_x =
858                snapshot.x_for_display_point(DisplayPoint::new(2, 2), &text_layout_details);
859
860            // Can't move up into the first excerpt's header
861            assert_eq!(
862                up(
863                    &snapshot,
864                    DisplayPoint::new(2, 2),
865                    SelectionGoal::HorizontalPosition(col_2_x.0),
866                    false,
867                    &text_layout_details
868                ),
869                (
870                    DisplayPoint::new(2, 0),
871                    SelectionGoal::HorizontalPosition(0.0)
872                ),
873            );
874            assert_eq!(
875                up(
876                    &snapshot,
877                    DisplayPoint::new(2, 0),
878                    SelectionGoal::None,
879                    false,
880                    &text_layout_details
881                ),
882                (
883                    DisplayPoint::new(2, 0),
884                    SelectionGoal::HorizontalPosition(0.0)
885                ),
886            );
887
888            let col_4_x =
889                snapshot.x_for_display_point(DisplayPoint::new(3, 4), &text_layout_details);
890
891            // Move up and down within first excerpt
892            assert_eq!(
893                up(
894                    &snapshot,
895                    DisplayPoint::new(3, 4),
896                    SelectionGoal::HorizontalPosition(col_4_x.0),
897                    false,
898                    &text_layout_details
899                ),
900                (
901                    DisplayPoint::new(2, 3),
902                    SelectionGoal::HorizontalPosition(col_4_x.0)
903                ),
904            );
905            assert_eq!(
906                down(
907                    &snapshot,
908                    DisplayPoint::new(2, 3),
909                    SelectionGoal::HorizontalPosition(col_4_x.0),
910                    false,
911                    &text_layout_details
912                ),
913                (
914                    DisplayPoint::new(3, 4),
915                    SelectionGoal::HorizontalPosition(col_4_x.0)
916                ),
917            );
918
919            let col_5_x =
920                snapshot.x_for_display_point(DisplayPoint::new(6, 5), &text_layout_details);
921
922            // Move up and down across second excerpt's header
923            assert_eq!(
924                up(
925                    &snapshot,
926                    DisplayPoint::new(6, 5),
927                    SelectionGoal::HorizontalPosition(col_5_x.0),
928                    false,
929                    &text_layout_details
930                ),
931                (
932                    DisplayPoint::new(3, 4),
933                    SelectionGoal::HorizontalPosition(col_5_x.0)
934                ),
935            );
936            assert_eq!(
937                down(
938                    &snapshot,
939                    DisplayPoint::new(3, 4),
940                    SelectionGoal::HorizontalPosition(col_5_x.0),
941                    false,
942                    &text_layout_details
943                ),
944                (
945                    DisplayPoint::new(6, 5),
946                    SelectionGoal::HorizontalPosition(col_5_x.0)
947                ),
948            );
949
950            let max_point_x =
951                snapshot.x_for_display_point(DisplayPoint::new(7, 2), &text_layout_details);
952
953            // Can't move down off the end
954            assert_eq!(
955                down(
956                    &snapshot,
957                    DisplayPoint::new(7, 0),
958                    SelectionGoal::HorizontalPosition(0.0),
959                    false,
960                    &text_layout_details
961                ),
962                (
963                    DisplayPoint::new(7, 2),
964                    SelectionGoal::HorizontalPosition(max_point_x.0)
965                ),
966            );
967            assert_eq!(
968                down(
969                    &snapshot,
970                    DisplayPoint::new(7, 2),
971                    SelectionGoal::HorizontalPosition(max_point_x.0),
972                    false,
973                    &text_layout_details
974                ),
975                (
976                    DisplayPoint::new(7, 2),
977                    SelectionGoal::HorizontalPosition(max_point_x.0)
978                ),
979            );
980        });
981    }
982
983    fn init_test(cx: &mut gpui::AppContext) {
984        let settings_store = SettingsStore::test(cx);
985        cx.set_global(settings_store);
986        theme::init(theme::LoadThemes::JustBase, cx);
987        language::init(cx);
988        crate::init(cx);
989        Project::init_settings(cx);
990    }
991}