movement.rs

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