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