movement.rs

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