movement.rs

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