movement.rs

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