movement.rs

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