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