movement.rs

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