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::{
   6    char_kind, scroll::ScrollAnchor, CharKind, DisplayRow, EditorStyle, RowExt, ToOffset, ToPoint,
   7};
   8use gpui::{px, Pixels, WindowTextSystem};
   9use language::Point;
  10use multi_buffer::{MultiBufferRow, MultiBufferSnapshot};
  11use serde::Deserialize;
  12
  13use std::{ops::Range, sync::Arc};
  14
  15/// Defines search strategy for items in `movement` module.
  16/// `FindRange::SingeLine` only looks for a match on a single line at a time, whereas
  17/// `FindRange::MultiLine` keeps going until the end of a string.
  18#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
  19pub enum FindRange {
  20    SingleLine,
  21    MultiLine,
  22}
  23
  24/// TextLayoutDetails encompasses everything we need to move vertically
  25/// taking into account variable width characters.
  26pub struct TextLayoutDetails {
  27    pub(crate) text_system: Arc<WindowTextSystem>,
  28    pub(crate) editor_style: EditorStyle,
  29    pub(crate) rem_size: Pixels,
  30    pub scroll_anchor: ScrollAnchor,
  31    pub visible_rows: Option<f32>,
  32    pub vertical_scroll_margin: f32,
  33}
  34
  35/// Returns a column to the left of the current point, wrapping
  36/// to the previous line if that point is at the start of line.
  37pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  38    if point.column() > 0 {
  39        *point.column_mut() -= 1;
  40    } else if point.row().0 > 0 {
  41        *point.row_mut() -= 1;
  42        *point.column_mut() = map.line_len(point.row());
  43    }
  44    map.clip_point(point, Bias::Left)
  45}
  46
  47/// Returns a column to the left of the current point, doing nothing if
  48/// that point is already at the start of line.
  49pub fn saturating_left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  50    if point.column() > 0 {
  51        *point.column_mut() -= 1;
  52    } else if point.column() == 0 {
  53        // If the current sofr_wrap mode is used, the column corresponding to the display is 0,
  54        //  which does not necessarily mean that the actual beginning of a paragraph
  55        if map.display_point_to_fold_point(point, Bias::Left).column() > 0 {
  56            return left(map, point);
  57        }
  58    }
  59    map.clip_point(point, Bias::Left)
  60}
  61
  62/// Returns a column to the right of the current point, doing nothing
  63// if that point is at the end of the line.
  64pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  65    if point.column() < map.line_len(point.row()) {
  66        *point.column_mut() += 1;
  67    } else if point.row() < map.max_point().row() {
  68        *point.row_mut() += 1;
  69        *point.column_mut() = 0;
  70    }
  71    map.clip_point(point, Bias::Right)
  72}
  73
  74/// Returns a column to the right of the current point, not performing any wrapping
  75/// if that point is already at the end of line.
  76pub fn saturating_right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  77    *point.column_mut() += 1;
  78    map.clip_point(point, Bias::Right)
  79}
  80
  81/// Returns a display point for the preceding displayed line (which might be a soft-wrapped line).
  82pub fn up(
  83    map: &DisplaySnapshot,
  84    start: DisplayPoint,
  85    goal: SelectionGoal,
  86    preserve_column_at_start: bool,
  87    text_layout_details: &TextLayoutDetails,
  88) -> (DisplayPoint, SelectionGoal) {
  89    up_by_rows(
  90        map,
  91        start,
  92        1,
  93        goal,
  94        preserve_column_at_start,
  95        text_layout_details,
  96    )
  97}
  98
  99/// Returns a display point for the next displayed line (which might be a soft-wrapped line).
 100pub fn down(
 101    map: &DisplaySnapshot,
 102    start: DisplayPoint,
 103    goal: SelectionGoal,
 104    preserve_column_at_end: bool,
 105    text_layout_details: &TextLayoutDetails,
 106) -> (DisplayPoint, SelectionGoal) {
 107    down_by_rows(
 108        map,
 109        start,
 110        1,
 111        goal,
 112        preserve_column_at_end,
 113        text_layout_details,
 114    )
 115}
 116
 117pub(crate) fn up_by_rows(
 118    map: &DisplaySnapshot,
 119    start: DisplayPoint,
 120    row_count: u32,
 121    goal: SelectionGoal,
 122    preserve_column_at_start: bool,
 123    text_layout_details: &TextLayoutDetails,
 124) -> (DisplayPoint, SelectionGoal) {
 125    let mut goal_x = match goal {
 126        SelectionGoal::HorizontalPosition(x) => x.into(),
 127        SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
 128        SelectionGoal::HorizontalRange { end, .. } => end.into(),
 129        _ => map.x_for_display_point(start, text_layout_details),
 130    };
 131
 132    let prev_row = DisplayRow(start.row().0.saturating_sub(row_count));
 133    let mut point = map.clip_point(
 134        DisplayPoint::new(prev_row, map.line_len(prev_row)),
 135        Bias::Left,
 136    );
 137    if point.row() < start.row() {
 138        *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
 139    } else if preserve_column_at_start {
 140        return (start, goal);
 141    } else {
 142        point = DisplayPoint::new(DisplayRow(0), 0);
 143        goal_x = px(0.);
 144    }
 145
 146    let mut clipped_point = map.clip_point(point, Bias::Left);
 147    if clipped_point.row() < point.row() {
 148        clipped_point = map.clip_point(point, Bias::Right);
 149    }
 150    (
 151        clipped_point,
 152        SelectionGoal::HorizontalPosition(goal_x.into()),
 153    )
 154}
 155
 156pub(crate) fn down_by_rows(
 157    map: &DisplaySnapshot,
 158    start: DisplayPoint,
 159    row_count: u32,
 160    goal: SelectionGoal,
 161    preserve_column_at_end: bool,
 162    text_layout_details: &TextLayoutDetails,
 163) -> (DisplayPoint, SelectionGoal) {
 164    let mut goal_x = match goal {
 165        SelectionGoal::HorizontalPosition(x) => x.into(),
 166        SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
 167        SelectionGoal::HorizontalRange { end, .. } => end.into(),
 168        _ => map.x_for_display_point(start, text_layout_details),
 169    };
 170
 171    let new_row = DisplayRow(start.row().0 + row_count);
 172    let mut point = map.clip_point(DisplayPoint::new(new_row, 0), Bias::Right);
 173    if point.row() > start.row() {
 174        *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
 175    } else if preserve_column_at_end {
 176        return (start, goal);
 177    } else {
 178        point = map.max_point();
 179        goal_x = map.x_for_display_point(point, text_layout_details)
 180    }
 181
 182    let mut clipped_point = map.clip_point(point, Bias::Right);
 183    if clipped_point.row() > point.row() {
 184        clipped_point = map.clip_point(point, Bias::Left);
 185    }
 186    (
 187        clipped_point,
 188        SelectionGoal::HorizontalPosition(goal_x.into()),
 189    )
 190}
 191
 192/// Returns a position of the start of line.
 193/// If `stop_at_soft_boundaries` is true, the returned position is that of the
 194/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
 195/// Otherwise it's always going to be the start of a logical line.
 196pub fn line_beginning(
 197    map: &DisplaySnapshot,
 198    display_point: DisplayPoint,
 199    stop_at_soft_boundaries: bool,
 200) -> DisplayPoint {
 201    let point = display_point.to_point(map);
 202    let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
 203    let line_start = map.prev_line_boundary(point).1;
 204
 205    if stop_at_soft_boundaries && display_point != soft_line_start {
 206        soft_line_start
 207    } else {
 208        line_start
 209    }
 210}
 211
 212/// Returns the last indented position on a given line.
 213/// If `stop_at_soft_boundaries` is true, the returned [`DisplayPoint`] is that of a
 214/// displayed line (e.g. if there's soft wrap it's gonna be returned),
 215/// otherwise it's always going to be a start of a logical line.
 216pub fn indented_line_beginning(
 217    map: &DisplaySnapshot,
 218    display_point: DisplayPoint,
 219    stop_at_soft_boundaries: bool,
 220) -> DisplayPoint {
 221    let point = display_point.to_point(map);
 222    let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
 223    let indent_start = Point::new(
 224        point.row,
 225        map.buffer_snapshot
 226            .indent_size_for_line(MultiBufferRow(point.row))
 227            .len,
 228    )
 229    .to_display_point(map);
 230    let line_start = map.prev_line_boundary(point).1;
 231
 232    if stop_at_soft_boundaries && soft_line_start > indent_start && display_point != soft_line_start
 233    {
 234        soft_line_start
 235    } else if stop_at_soft_boundaries && display_point != indent_start {
 236        indent_start
 237    } else {
 238        line_start
 239    }
 240}
 241
 242/// Returns a position of the end of line.
 243
 244/// If `stop_at_soft_boundaries` is true, the returned position is that of the
 245/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
 246/// Otherwise it's always going to be the end of a logical line.
 247pub fn line_end(
 248    map: &DisplaySnapshot,
 249    display_point: DisplayPoint,
 250    stop_at_soft_boundaries: bool,
 251) -> DisplayPoint {
 252    let soft_line_end = map.clip_point(
 253        DisplayPoint::new(display_point.row(), map.line_len(display_point.row())),
 254        Bias::Left,
 255    );
 256    if stop_at_soft_boundaries && display_point != soft_line_end {
 257        soft_line_end
 258    } else {
 259        map.next_line_boundary(display_point.to_point(map)).1
 260    }
 261}
 262
 263/// Returns a position of the previous word boundary, where a word character is defined as either
 264/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
 265pub fn previous_word_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 266    let raw_point = point.to_point(map);
 267    let scope = map.buffer_snapshot.language_scope_at(raw_point);
 268
 269    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 270        (char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace())
 271            || left == '\n'
 272    })
 273}
 274
 275/// Returns a position of the previous subword boundary, where a subword is defined as a run of
 276/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 277/// lowerspace characters and uppercase characters.
 278pub fn previous_subword_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 279    let raw_point = point.to_point(map);
 280    let scope = map.buffer_snapshot.language_scope_at(raw_point);
 281
 282    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 283        let is_word_start =
 284            char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace();
 285        let is_subword_start =
 286            left == '_' && right != '_' || left.is_lowercase() && right.is_uppercase();
 287        is_word_start || is_subword_start || left == '\n'
 288    })
 289}
 290
 291/// Returns a position of the next word boundary, where a word character is defined as either
 292/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
 293pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 294    let raw_point = point.to_point(map);
 295    let scope = map.buffer_snapshot.language_scope_at(raw_point);
 296
 297    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 298        (char_kind(&scope, left) != char_kind(&scope, right) && !left.is_whitespace())
 299            || right == '\n'
 300    })
 301}
 302
 303/// Returns a position of the next subword boundary, where a subword is defined as a run of
 304/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 305/// lowerspace characters and uppercase characters.
 306pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 307    let raw_point = point.to_point(map);
 308    let scope = map.buffer_snapshot.language_scope_at(raw_point);
 309
 310    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 311        let is_word_end =
 312            (char_kind(&scope, left) != char_kind(&scope, right)) && !left.is_whitespace();
 313        let is_subword_end =
 314            left != '_' && right == '_' || 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 scope = map.buffer_snapshot.language_scope_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| char_kind(&scope, c));
 516    let prev_char_kind = text
 517        .reversed_chars_at(ix)
 518        .next()
 519        .map(|c| char_kind(&scope, 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);
 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        let display_map = cx.new_model(|cx| {
 699            DisplayMap::new(
 700                buffer,
 701                font,
 702                font_size,
 703                None,
 704                1,
 705                1,
 706                FoldPlaceholder::test(),
 707                cx,
 708            )
 709        });
 710
 711        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
 712        let mut id = 0;
 713        let inlays = (0..buffer_snapshot.len())
 714            .flat_map(|offset| {
 715                [
 716                    Inlay {
 717                        id: InlayId::Suggestion(post_inc(&mut id)),
 718                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
 719                        text: "test".into(),
 720                    },
 721                    Inlay {
 722                        id: InlayId::Suggestion(post_inc(&mut id)),
 723                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
 724                        text: "test".into(),
 725                    },
 726                    Inlay {
 727                        id: InlayId::Hint(post_inc(&mut id)),
 728                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
 729                        text: "test".into(),
 730                    },
 731                    Inlay {
 732                        id: InlayId::Hint(post_inc(&mut id)),
 733                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
 734                        text: "test".into(),
 735                    },
 736                ]
 737            })
 738            .collect();
 739        let snapshot = display_map.update(cx, |map, cx| {
 740            map.splice_inlays(Vec::new(), inlays, cx);
 741            map.snapshot(cx)
 742        });
 743
 744        assert_eq!(
 745            find_preceding_boundary_display_point(
 746                &snapshot,
 747                buffer_snapshot.len().to_display_point(&snapshot),
 748                FindRange::MultiLine,
 749                |left, _| left == 'e',
 750            ),
 751            snapshot
 752                .buffer_snapshot
 753                .offset_to_point(5)
 754                .to_display_point(&snapshot),
 755            "Should not stop at inlays when looking for boundaries"
 756        );
 757    }
 758
 759    #[gpui::test]
 760    fn test_next_word_end(cx: &mut gpui::AppContext) {
 761        init_test(cx);
 762
 763        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
 764            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 765            assert_eq!(
 766                next_word_end(&snapshot, display_points[0]),
 767                display_points[1]
 768            );
 769        }
 770
 771        assert("\nˇ   loremˇ", cx);
 772        assert("    ˇloremˇ", cx);
 773        assert("    lorˇemˇ", cx);
 774        assert("    loremˇ    ˇ\nipsum\n", cx);
 775        assert("\nˇ\nˇ\n\n", cx);
 776        assert("loremˇ    ipsumˇ   ", cx);
 777        assert("loremˇ-ˇipsum", cx);
 778        assert("loremˇ#$@-ˇipsum", cx);
 779        assert("loremˇ_ipsumˇ", cx);
 780        assert(" ˇbcΔˇ", cx);
 781        assert(" abˇ——ˇcd", cx);
 782    }
 783
 784    #[gpui::test]
 785    fn test_next_subword_end(cx: &mut gpui::AppContext) {
 786        init_test(cx);
 787
 788        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
 789            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 790            assert_eq!(
 791                next_subword_end(&snapshot, display_points[0]),
 792                display_points[1]
 793            );
 794        }
 795
 796        // Subword boundaries are respected
 797        assert("loˇremˇ_ipsum", cx);
 798        assert("ˇloremˇ_ipsum", cx);
 799        assert("loremˇ_ipsumˇ", cx);
 800        assert("loremˇ_ipsumˇ_dolor", cx);
 801        assert("loˇremˇIpsum", cx);
 802        assert("loremˇIpsumˇDolor", cx);
 803
 804        // Word boundaries are still respected
 805        assert("\nˇ   loremˇ", cx);
 806        assert("    ˇloremˇ", cx);
 807        assert("    lorˇemˇ", cx);
 808        assert("    loremˇ    ˇ\nipsum\n", cx);
 809        assert("\nˇ\nˇ\n\n", cx);
 810        assert("loremˇ    ipsumˇ   ", cx);
 811        assert("loremˇ-ˇipsum", cx);
 812        assert("loremˇ#$@-ˇipsum", cx);
 813        assert("loremˇ_ipsumˇ", cx);
 814        assert(" ˇbcˇΔ", cx);
 815        assert(" abˇ——ˇcd", cx);
 816    }
 817
 818    #[gpui::test]
 819    fn test_find_boundary(cx: &mut gpui::AppContext) {
 820        init_test(cx);
 821
 822        fn assert(
 823            marked_text: &str,
 824            cx: &mut gpui::AppContext,
 825            is_boundary: impl FnMut(char, char) -> bool,
 826        ) {
 827            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 828            assert_eq!(
 829                find_boundary(
 830                    &snapshot,
 831                    display_points[0],
 832                    FindRange::MultiLine,
 833                    is_boundary,
 834                ),
 835                display_points[1]
 836            );
 837        }
 838
 839        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
 840            left == 'j' && right == 'k'
 841        });
 842        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
 843            left == '\n' && right == 'i'
 844        });
 845        let mut line_count = 0;
 846        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
 847            if left == '\n' {
 848                line_count += 1;
 849                line_count == 2
 850            } else {
 851                false
 852            }
 853        });
 854    }
 855
 856    #[gpui::test]
 857    fn test_surrounding_word(cx: &mut gpui::AppContext) {
 858        init_test(cx);
 859
 860        fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
 861            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 862            assert_eq!(
 863                surrounding_word(&snapshot, display_points[1]),
 864                display_points[0]..display_points[2],
 865                "{}",
 866                marked_text
 867            );
 868        }
 869
 870        assert("ˇˇloremˇ  ipsum", cx);
 871        assert("ˇloˇremˇ  ipsum", cx);
 872        assert("ˇloremˇˇ  ipsum", cx);
 873        assert("loremˇ ˇ  ˇipsum", cx);
 874        assert("lorem\nˇˇˇ\nipsum", cx);
 875        assert("lorem\nˇˇipsumˇ", cx);
 876        assert("loremˇ,ˇˇ ipsum", cx);
 877        assert("ˇloremˇˇ, ipsum", cx);
 878    }
 879
 880    #[gpui::test]
 881    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
 882        cx.update(|cx| {
 883            init_test(cx);
 884        });
 885
 886        let mut cx = EditorTestContext::new(cx).await;
 887        let editor = cx.editor.clone();
 888        let window = cx.window;
 889        _ = cx.update_window(window, |_, cx| {
 890            let text_layout_details =
 891                editor.update(cx, |editor, cx| editor.text_layout_details(cx));
 892
 893            let font = font("Helvetica");
 894
 895            let buffer = cx.new_model(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
 896            let multibuffer = cx.new_model(|cx| {
 897                let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
 898                multibuffer.push_excerpts(
 899                    buffer.clone(),
 900                    [
 901                        ExcerptRange {
 902                            context: Point::new(0, 0)..Point::new(1, 4),
 903                            primary: None,
 904                        },
 905                        ExcerptRange {
 906                            context: Point::new(2, 0)..Point::new(3, 2),
 907                            primary: None,
 908                        },
 909                    ],
 910                    cx,
 911                );
 912                multibuffer
 913            });
 914            let display_map = cx.new_model(|cx| {
 915                DisplayMap::new(
 916                    multibuffer,
 917                    font,
 918                    px(14.0),
 919                    None,
 920                    2,
 921                    2,
 922                    FoldPlaceholder::test(),
 923                    cx,
 924                )
 925            });
 926            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
 927
 928            assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
 929
 930            let col_2_x = snapshot
 931                .x_for_display_point(DisplayPoint::new(DisplayRow(2), 2), &text_layout_details);
 932
 933            // Can't move up into the first excerpt's header
 934            assert_eq!(
 935                up(
 936                    &snapshot,
 937                    DisplayPoint::new(DisplayRow(2), 2),
 938                    SelectionGoal::HorizontalPosition(col_2_x.0),
 939                    false,
 940                    &text_layout_details
 941                ),
 942                (
 943                    DisplayPoint::new(DisplayRow(2), 0),
 944                    SelectionGoal::HorizontalPosition(0.0)
 945                ),
 946            );
 947            assert_eq!(
 948                up(
 949                    &snapshot,
 950                    DisplayPoint::new(DisplayRow(2), 0),
 951                    SelectionGoal::None,
 952                    false,
 953                    &text_layout_details
 954                ),
 955                (
 956                    DisplayPoint::new(DisplayRow(2), 0),
 957                    SelectionGoal::HorizontalPosition(0.0)
 958                ),
 959            );
 960
 961            let col_4_x = snapshot
 962                .x_for_display_point(DisplayPoint::new(DisplayRow(3), 4), &text_layout_details);
 963
 964            // Move up and down within first excerpt
 965            assert_eq!(
 966                up(
 967                    &snapshot,
 968                    DisplayPoint::new(DisplayRow(3), 4),
 969                    SelectionGoal::HorizontalPosition(col_4_x.0),
 970                    false,
 971                    &text_layout_details
 972                ),
 973                (
 974                    DisplayPoint::new(DisplayRow(2), 3),
 975                    SelectionGoal::HorizontalPosition(col_4_x.0)
 976                ),
 977            );
 978            assert_eq!(
 979                down(
 980                    &snapshot,
 981                    DisplayPoint::new(DisplayRow(2), 3),
 982                    SelectionGoal::HorizontalPosition(col_4_x.0),
 983                    false,
 984                    &text_layout_details
 985                ),
 986                (
 987                    DisplayPoint::new(DisplayRow(3), 4),
 988                    SelectionGoal::HorizontalPosition(col_4_x.0)
 989                ),
 990            );
 991
 992            let col_5_x = snapshot
 993                .x_for_display_point(DisplayPoint::new(DisplayRow(6), 5), &text_layout_details);
 994
 995            // Move up and down across second excerpt's header
 996            assert_eq!(
 997                up(
 998                    &snapshot,
 999                    DisplayPoint::new(DisplayRow(6), 5),
1000                    SelectionGoal::HorizontalPosition(col_5_x.0),
1001                    false,
1002                    &text_layout_details
1003                ),
1004                (
1005                    DisplayPoint::new(DisplayRow(3), 4),
1006                    SelectionGoal::HorizontalPosition(col_5_x.0)
1007                ),
1008            );
1009            assert_eq!(
1010                down(
1011                    &snapshot,
1012                    DisplayPoint::new(DisplayRow(3), 4),
1013                    SelectionGoal::HorizontalPosition(col_5_x.0),
1014                    false,
1015                    &text_layout_details
1016                ),
1017                (
1018                    DisplayPoint::new(DisplayRow(6), 5),
1019                    SelectionGoal::HorizontalPosition(col_5_x.0)
1020                ),
1021            );
1022
1023            let max_point_x = snapshot
1024                .x_for_display_point(DisplayPoint::new(DisplayRow(7), 2), &text_layout_details);
1025
1026            // Can't move down off the end
1027            assert_eq!(
1028                down(
1029                    &snapshot,
1030                    DisplayPoint::new(DisplayRow(7), 0),
1031                    SelectionGoal::HorizontalPosition(0.0),
1032                    false,
1033                    &text_layout_details
1034                ),
1035                (
1036                    DisplayPoint::new(DisplayRow(7), 2),
1037                    SelectionGoal::HorizontalPosition(max_point_x.0)
1038                ),
1039            );
1040            assert_eq!(
1041                down(
1042                    &snapshot,
1043                    DisplayPoint::new(DisplayRow(7), 2),
1044                    SelectionGoal::HorizontalPosition(max_point_x.0),
1045                    false,
1046                    &text_layout_details
1047                ),
1048                (
1049                    DisplayPoint::new(DisplayRow(7), 2),
1050                    SelectionGoal::HorizontalPosition(max_point_x.0)
1051                ),
1052            );
1053        });
1054    }
1055
1056    fn init_test(cx: &mut gpui::AppContext) {
1057        let settings_store = SettingsStore::test(cx);
1058        cx.set_global(settings_store);
1059        theme::init(theme::LoadThemes::JustBase, cx);
1060        language::init(cx);
1061        crate::init(cx);
1062        Project::init_settings(cx);
1063    }
1064}