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 DisplayPoint::zero();
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 map.max_point();
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 project::Project;
433    use settings::SettingsStore;
434    use util::post_inc;
435
436    #[gpui::test]
437    fn test_previous_word_start(cx: &mut gpui::AppContext) {
438        init_test(cx);
439
440        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
441            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
442            assert_eq!(
443                previous_word_start(&snapshot, display_points[1]),
444                display_points[0]
445            );
446        }
447
448        assert("\nˇ   ˇlorem", cx);
449        assert("ˇ\nˇ   lorem", cx);
450        assert("    ˇloremˇ", cx);
451        assert("ˇ    ˇlorem", cx);
452        assert("    ˇlorˇem", cx);
453        assert("\nlorem\nˇ   ˇipsum", cx);
454        assert("\n\nˇ\nˇ", cx);
455        assert("    ˇlorem  ˇipsum", cx);
456        assert("loremˇ-ˇipsum", cx);
457        assert("loremˇ-#$@ˇipsum", cx);
458        assert("ˇlorem_ˇipsum", cx);
459        assert(" ˇdefγˇ", cx);
460        assert(" ˇbcΔˇ", cx);
461        assert(" abˇ——ˇcd", cx);
462    }
463
464    #[gpui::test]
465    fn test_previous_subword_start(cx: &mut gpui::AppContext) {
466        init_test(cx);
467
468        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
469            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
470            assert_eq!(
471                previous_subword_start(&snapshot, display_points[1]),
472                display_points[0]
473            );
474        }
475
476        // Subword boundaries are respected
477        assert("lorem_ˇipˇsum", cx);
478        assert("lorem_ˇipsumˇ", cx);
479        assert("ˇlorem_ˇipsum", cx);
480        assert("lorem_ˇipsum_ˇdolor", cx);
481        assert("loremˇIpˇsum", cx);
482        assert("loremˇIpsumˇ", cx);
483
484        // Word boundaries are still respected
485        assert("\nˇ   ˇlorem", cx);
486        assert("    ˇloremˇ", cx);
487        assert("    ˇlorˇem", cx);
488        assert("\nlorem\nˇ   ˇipsum", cx);
489        assert("\n\nˇ\nˇ", cx);
490        assert("    ˇlorem  ˇipsum", cx);
491        assert("loremˇ-ˇipsum", cx);
492        assert("loremˇ-#$@ˇipsum", cx);
493        assert(" ˇdefγˇ", cx);
494        assert(" bcˇΔˇ", cx);
495        assert(" ˇbcδˇ", cx);
496        assert(" abˇ——ˇcd", cx);
497    }
498
499    #[gpui::test]
500    fn test_find_preceding_boundary(cx: &mut gpui::AppContext) {
501        init_test(cx);
502
503        fn assert(
504            marked_text: &str,
505            cx: &mut gpui::AppContext,
506            is_boundary: impl FnMut(char, char) -> bool,
507        ) {
508            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
509            assert_eq!(
510                find_preceding_boundary(
511                    &snapshot,
512                    display_points[1],
513                    FindRange::MultiLine,
514                    is_boundary
515                ),
516                display_points[0]
517            );
518        }
519
520        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
521            left == 'c' && right == 'd'
522        });
523        assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
524            left == '\n' && right == 'g'
525        });
526        let mut line_count = 0;
527        assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
528            if left == '\n' {
529                line_count += 1;
530                line_count == 2
531            } else {
532                false
533            }
534        });
535    }
536
537    #[gpui::test]
538    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::AppContext) {
539        init_test(cx);
540
541        let input_text = "abcdefghijklmnopqrstuvwxys";
542        let family_id = cx
543            .font_cache()
544            .load_family(&["Helvetica"], &Default::default())
545            .unwrap();
546        let font_id = cx
547            .font_cache()
548            .select_font(family_id, &Default::default())
549            .unwrap();
550        let font_size = 14.0;
551        let buffer = MultiBuffer::build_simple(input_text, cx);
552        let buffer_snapshot = buffer.read(cx).snapshot(cx);
553        let display_map =
554            cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
555
556        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
557        let mut id = 0;
558        let inlays = (0..buffer_snapshot.len())
559            .map(|offset| {
560                [
561                    Inlay {
562                        id: InlayId::Suggestion(post_inc(&mut id)),
563                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
564                        text: format!("test").into(),
565                    },
566                    Inlay {
567                        id: InlayId::Suggestion(post_inc(&mut id)),
568                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
569                        text: format!("test").into(),
570                    },
571                    Inlay {
572                        id: InlayId::Hint(post_inc(&mut id)),
573                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
574                        text: format!("test").into(),
575                    },
576                    Inlay {
577                        id: InlayId::Hint(post_inc(&mut id)),
578                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
579                        text: format!("test").into(),
580                    },
581                ]
582            })
583            .flatten()
584            .collect();
585        let snapshot = display_map.update(cx, |map, cx| {
586            map.splice_inlays(Vec::new(), inlays, cx);
587            map.snapshot(cx)
588        });
589
590        assert_eq!(
591            find_preceding_boundary(
592                &snapshot,
593                buffer_snapshot.len().to_display_point(&snapshot),
594                FindRange::MultiLine,
595                |left, _| left == 'e',
596            ),
597            snapshot
598                .buffer_snapshot
599                .offset_to_point(5)
600                .to_display_point(&snapshot),
601            "Should not stop at inlays when looking for boundaries"
602        );
603    }
604
605    #[gpui::test]
606    fn test_next_word_end(cx: &mut gpui::AppContext) {
607        init_test(cx);
608
609        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
610            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
611            assert_eq!(
612                next_word_end(&snapshot, display_points[0]),
613                display_points[1]
614            );
615        }
616
617        assert("\nˇ   loremˇ", cx);
618        assert("    ˇloremˇ", cx);
619        assert("    lorˇemˇ", cx);
620        assert("    loremˇ    ˇ\nipsum\n", cx);
621        assert("\nˇ\nˇ\n\n", cx);
622        assert("loremˇ    ipsumˇ   ", cx);
623        assert("loremˇ-ˇipsum", cx);
624        assert("loremˇ#$@-ˇipsum", cx);
625        assert("loremˇ_ipsumˇ", cx);
626        assert(" ˇbcΔˇ", cx);
627        assert(" abˇ——ˇcd", cx);
628    }
629
630    #[gpui::test]
631    fn test_next_subword_end(cx: &mut gpui::AppContext) {
632        init_test(cx);
633
634        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
635            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
636            assert_eq!(
637                next_subword_end(&snapshot, display_points[0]),
638                display_points[1]
639            );
640        }
641
642        // Subword boundaries are respected
643        assert("loˇremˇ_ipsum", cx);
644        assert("ˇloremˇ_ipsum", cx);
645        assert("loremˇ_ipsumˇ", cx);
646        assert("loremˇ_ipsumˇ_dolor", cx);
647        assert("loˇremˇIpsum", cx);
648        assert("loremˇIpsumˇDolor", cx);
649
650        // Word boundaries are still respected
651        assert("\nˇ   loremˇ", cx);
652        assert("    ˇloremˇ", cx);
653        assert("    lorˇemˇ", cx);
654        assert("    loremˇ    ˇ\nipsum\n", cx);
655        assert("\nˇ\nˇ\n\n", cx);
656        assert("loremˇ    ipsumˇ   ", cx);
657        assert("loremˇ-ˇipsum", cx);
658        assert("loremˇ#$@-ˇipsum", cx);
659        assert("loremˇ_ipsumˇ", cx);
660        assert(" ˇbcˇΔ", cx);
661        assert(" abˇ——ˇcd", cx);
662    }
663
664    #[gpui::test]
665    fn test_find_boundary(cx: &mut gpui::AppContext) {
666        init_test(cx);
667
668        fn assert(
669            marked_text: &str,
670            cx: &mut gpui::AppContext,
671            is_boundary: impl FnMut(char, char) -> bool,
672        ) {
673            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
674            assert_eq!(
675                find_boundary(
676                    &snapshot,
677                    display_points[0],
678                    FindRange::MultiLine,
679                    is_boundary
680                ),
681                display_points[1]
682            );
683        }
684
685        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
686            left == 'j' && right == 'k'
687        });
688        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
689            left == '\n' && right == 'i'
690        });
691        let mut line_count = 0;
692        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
693            if left == '\n' {
694                line_count += 1;
695                line_count == 2
696            } else {
697                false
698            }
699        });
700    }
701
702    #[gpui::test]
703    fn test_surrounding_word(cx: &mut gpui::AppContext) {
704        init_test(cx);
705
706        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
707            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
708            assert_eq!(
709                surrounding_word(&snapshot, display_points[1]),
710                display_points[0]..display_points[2]
711            );
712        }
713
714        assert("ˇˇloremˇ  ipsum", cx);
715        assert("ˇloˇremˇ  ipsum", cx);
716        assert("ˇloremˇˇ  ipsum", cx);
717        assert("loremˇ ˇ  ˇipsum", cx);
718        assert("lorem\nˇˇˇ\nipsum", cx);
719        assert("lorem\nˇˇipsumˇ", cx);
720        assert("lorem,ˇˇ ˇipsum", cx);
721        assert("ˇloremˇˇ, ipsum", cx);
722    }
723
724    #[gpui::test]
725    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
726        cx.update(|cx| {
727            init_test(cx);
728        });
729
730        let mut cx = EditorTestContext::new(cx).await;
731        let editor = cx.editor.clone();
732        let window = cx.window.clone();
733        cx.update_window(window, |cx| {
734            let text_layout_details =
735                editor.read_with(cx, |editor, cx| editor.text_layout_details(cx));
736
737            let family_id = cx
738                .font_cache()
739                .load_family(&["Helvetica"], &Default::default())
740                .unwrap();
741            let font_id = cx
742                .font_cache()
743                .select_font(family_id, &Default::default())
744                .unwrap();
745
746            let buffer =
747                cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "abc\ndefg\nhijkl\nmn"));
748            let multibuffer = cx.add_model(|cx| {
749                let mut multibuffer = MultiBuffer::new(0);
750                multibuffer.push_excerpts(
751                    buffer.clone(),
752                    [
753                        ExcerptRange {
754                            context: Point::new(0, 0)..Point::new(1, 4),
755                            primary: None,
756                        },
757                        ExcerptRange {
758                            context: Point::new(2, 0)..Point::new(3, 2),
759                            primary: None,
760                        },
761                    ],
762                    cx,
763                );
764                multibuffer
765            });
766            let display_map =
767                cx.add_model(|cx| DisplayMap::new(multibuffer, font_id, 14.0, None, 2, 2, cx));
768            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
769
770            assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
771
772            let col_2_x = snapshot.x_for_point(DisplayPoint::new(2, 2), &text_layout_details);
773
774            // Can't move up into the first excerpt's header
775            assert_eq!(
776                up(
777                    &snapshot,
778                    DisplayPoint::new(2, 2),
779                    SelectionGoal::HorizontalPosition(col_2_x),
780                    false,
781                    &text_layout_details
782                ),
783                (
784                    DisplayPoint::new(2, 0),
785                    SelectionGoal::HorizontalPosition(0.0)
786                ),
787            );
788            assert_eq!(
789                up(
790                    &snapshot,
791                    DisplayPoint::new(2, 0),
792                    SelectionGoal::None,
793                    false,
794                    &text_layout_details
795                ),
796                (
797                    DisplayPoint::new(2, 0),
798                    SelectionGoal::HorizontalPosition(0.0)
799                ),
800            );
801
802            let col_4_x = snapshot.x_for_point(DisplayPoint::new(3, 4), &text_layout_details);
803
804            // Move up and down within first excerpt
805            assert_eq!(
806                up(
807                    &snapshot,
808                    DisplayPoint::new(3, 4),
809                    SelectionGoal::HorizontalPosition(col_4_x),
810                    false,
811                    &text_layout_details
812                ),
813                (
814                    DisplayPoint::new(2, 3),
815                    SelectionGoal::HorizontalPosition(col_4_x)
816                ),
817            );
818            assert_eq!(
819                down(
820                    &snapshot,
821                    DisplayPoint::new(2, 3),
822                    SelectionGoal::HorizontalPosition(col_4_x),
823                    false,
824                    &text_layout_details
825                ),
826                (
827                    DisplayPoint::new(3, 4),
828                    SelectionGoal::HorizontalPosition(col_4_x)
829                ),
830            );
831
832            let col_5_x = snapshot.x_for_point(DisplayPoint::new(6, 5), &text_layout_details);
833
834            // Move up and down across second excerpt's header
835            assert_eq!(
836                up(
837                    &snapshot,
838                    DisplayPoint::new(6, 5),
839                    SelectionGoal::HorizontalPosition(col_5_x),
840                    false,
841                    &text_layout_details
842                ),
843                (
844                    DisplayPoint::new(3, 4),
845                    SelectionGoal::HorizontalPosition(col_5_x)
846                ),
847            );
848            assert_eq!(
849                down(
850                    &snapshot,
851                    DisplayPoint::new(3, 4),
852                    SelectionGoal::HorizontalPosition(col_5_x),
853                    false,
854                    &text_layout_details
855                ),
856                (
857                    DisplayPoint::new(6, 5),
858                    SelectionGoal::HorizontalPosition(col_5_x)
859                ),
860            );
861
862            let max_point_x = snapshot.x_for_point(DisplayPoint::new(7, 2), &text_layout_details);
863
864            // Can't move down off the end
865            assert_eq!(
866                down(
867                    &snapshot,
868                    DisplayPoint::new(7, 0),
869                    SelectionGoal::HorizontalPosition(0.0),
870                    false,
871                    &text_layout_details
872                ),
873                (
874                    DisplayPoint::new(7, 2),
875                    SelectionGoal::HorizontalPosition(max_point_x)
876                ),
877            );
878            assert_eq!(
879                down(
880                    &snapshot,
881                    DisplayPoint::new(7, 2),
882                    SelectionGoal::HorizontalPosition(max_point_x),
883                    false,
884                    &text_layout_details
885                ),
886                (
887                    DisplayPoint::new(7, 2),
888                    SelectionGoal::HorizontalPosition(max_point_x)
889                ),
890            );
891        });
892    }
893
894    fn init_test(cx: &mut gpui::AppContext) {
895        cx.set_global(SettingsStore::test(cx));
896        theme::init((), cx);
897        language::init(cx);
898        crate::init(cx);
899        Project::init_settings(cx);
900    }
901}