movement.rs

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