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::{DisplayRow, EditorStyle, ToOffset, ToPoint, scroll::ScrollAnchor};
   6use gpui::{Pixels, WindowTextSystem};
   7use language::Point;
   8use multi_buffer::{MultiBufferRow, MultiBufferSnapshot};
   9use serde::Deserialize;
  10use workspace::searchable::Direction;
  11
  12use std::{ops::Range, sync::Arc};
  13
  14/// Defines search strategy for items in `movement` module.
  15/// `FindRange::SingeLine` only looks for a match on a single line at a time, whereas
  16/// `FindRange::MultiLine` keeps going until the end of a string.
  17#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
  18pub enum FindRange {
  19    SingleLine,
  20    MultiLine,
  21}
  22
  23/// TextLayoutDetails encompasses everything we need to move vertically
  24/// taking into account variable width characters.
  25pub struct TextLayoutDetails {
  26    pub(crate) text_system: Arc<WindowTextSystem>,
  27    pub(crate) editor_style: EditorStyle,
  28    pub(crate) rem_size: Pixels,
  29    pub scroll_anchor: ScrollAnchor,
  30    pub visible_rows: Option<f32>,
  31    pub vertical_scroll_margin: f32,
  32}
  33
  34/// Returns a column to the left of the current point, wrapping
  35/// to the previous line if that point is at the start of line.
  36pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  37    if point.column() > 0 {
  38        *point.column_mut() -= 1;
  39    } else if point.row().0 > 0 {
  40        *point.row_mut() -= 1;
  41        *point.column_mut() = map.line_len(point.row());
  42    }
  43    map.clip_point(point, Bias::Left)
  44}
  45
  46/// Returns a column to the left of the current point, doing nothing if
  47/// that point is already at the start of line.
  48pub fn saturating_left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  49    if point.column() > 0 {
  50        *point.column_mut() -= 1;
  51    } else if point.column() == 0 {
  52        // If the current sofr_wrap mode is used, the column corresponding to the display is 0,
  53        //  which does not necessarily mean that the actual beginning of a paragraph
  54        if map.display_point_to_fold_point(point, Bias::Left).column() > 0 {
  55            return left(map, point);
  56        }
  57    }
  58    map.clip_point(point, Bias::Left)
  59}
  60
  61/// Returns a column to the right of the current point, wrapping
  62/// to the next line if that point is at the end of line.
  63pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  64    if point.column() < map.line_len(point.row()) {
  65        *point.column_mut() += 1;
  66    } else if point.row() < map.max_point().row() {
  67        *point.row_mut() += 1;
  68        *point.column_mut() = 0;
  69    }
  70    map.clip_point(point, Bias::Right)
  71}
  72
  73/// Returns a column to the right of the current point, not performing any wrapping
  74/// if that point is already at the end of line.
  75pub fn saturating_right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
  76    *point.column_mut() += 1;
  77    map.clip_point(point, Bias::Right)
  78}
  79
  80/// Returns a display point for the preceding displayed line (which might be a soft-wrapped line).
  81pub fn up(
  82    map: &DisplaySnapshot,
  83    start: DisplayPoint,
  84    goal: SelectionGoal,
  85    preserve_column_at_start: bool,
  86    text_layout_details: &TextLayoutDetails,
  87) -> (DisplayPoint, SelectionGoal) {
  88    up_by_rows(
  89        map,
  90        start,
  91        1,
  92        goal,
  93        preserve_column_at_start,
  94        text_layout_details,
  95    )
  96}
  97
  98/// Returns a display point for the next displayed line (which might be a soft-wrapped line).
  99pub fn down(
 100    map: &DisplaySnapshot,
 101    start: DisplayPoint,
 102    goal: SelectionGoal,
 103    preserve_column_at_end: bool,
 104    text_layout_details: &TextLayoutDetails,
 105) -> (DisplayPoint, SelectionGoal) {
 106    down_by_rows(
 107        map,
 108        start,
 109        1,
 110        goal,
 111        preserve_column_at_end,
 112        text_layout_details,
 113    )
 114}
 115
 116pub(crate) fn up_by_rows(
 117    map: &DisplaySnapshot,
 118    start: DisplayPoint,
 119    row_count: u32,
 120    goal: SelectionGoal,
 121    preserve_column_at_start: bool,
 122    text_layout_details: &TextLayoutDetails,
 123) -> (DisplayPoint, SelectionGoal) {
 124    let goal_x = match goal {
 125        SelectionGoal::HorizontalPosition(x) => x.into(),
 126        SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
 127        SelectionGoal::HorizontalRange { end, .. } => end.into(),
 128        _ => map.x_for_display_point(start, text_layout_details),
 129    };
 130
 131    let prev_row = DisplayRow(start.row().0.saturating_sub(row_count));
 132    let mut point = map.clip_point(
 133        DisplayPoint::new(prev_row, map.line_len(prev_row)),
 134        Bias::Left,
 135    );
 136    if point.row() < start.row() {
 137        *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
 138    } else if preserve_column_at_start {
 139        return (start, goal);
 140    } else {
 141        point = DisplayPoint::new(DisplayRow(0), 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 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    }
 178
 179    let mut clipped_point = map.clip_point(point, Bias::Right);
 180    if clipped_point.row() > point.row() {
 181        clipped_point = map.clip_point(point, Bias::Left);
 182    }
 183    (
 184        clipped_point,
 185        SelectionGoal::HorizontalPosition(goal_x.into()),
 186    )
 187}
 188
 189/// Returns a position of the start of line.
 190/// If `stop_at_soft_boundaries` is true, the returned position is that of the
 191/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
 192/// Otherwise it's always going to be the start of a logical line.
 193pub fn line_beginning(
 194    map: &DisplaySnapshot,
 195    display_point: DisplayPoint,
 196    stop_at_soft_boundaries: bool,
 197) -> DisplayPoint {
 198    let point = display_point.to_point(map);
 199    let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
 200    let line_start = map.prev_line_boundary(point).1;
 201
 202    if stop_at_soft_boundaries && display_point != soft_line_start {
 203        soft_line_start
 204    } else {
 205        line_start
 206    }
 207}
 208
 209/// Returns the last indented position on a given line.
 210/// If `stop_at_soft_boundaries` is true, the returned [`DisplayPoint`] is that of a
 211/// displayed line (e.g. if there's soft wrap it's gonna be returned),
 212/// otherwise it's always going to be a start of a logical line.
 213pub fn indented_line_beginning(
 214    map: &DisplaySnapshot,
 215    display_point: DisplayPoint,
 216    stop_at_soft_boundaries: bool,
 217    stop_at_indent: 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_indent && (display_point > indent_start || display_point == line_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    let mut is_first_iteration = true;
 268    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 269        // Make alt-left skip punctuation to respect VSCode behaviour. For example: hello.| goes to |hello.
 270        if is_first_iteration
 271            && classifier.is_punctuation(right)
 272            && !classifier.is_punctuation(left)
 273            && left != '\n'
 274        {
 275            is_first_iteration = false;
 276            return false;
 277        }
 278        is_first_iteration = false;
 279
 280        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(right))
 281            || left == '\n'
 282    })
 283}
 284
 285/// Returns a position of the previous word boundary, where a word character is defined as either
 286/// uppercase letter, lowercase letter, '_' character, language-specific word character (like '-' in CSS) or newline.
 287pub fn previous_word_start_or_newline(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 288    let raw_point = point.to_point(map);
 289    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 290
 291    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 292        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(right))
 293            || left == '\n'
 294            || right == '\n'
 295    })
 296}
 297
 298/// Text movements are too greedy, making deletions too greedy too.
 299/// Makes deletions more ergonomic by potentially reducing the deletion range based on its text contents:
 300/// * whitespace sequences with length >= 2 stop the deletion after removal (despite movement jumping over the word behind the whitespaces)
 301/// * brackets stop the deletion after removal (despite movement currently not accounting for these and jumping over)
 302pub fn adjust_greedy_deletion(
 303    map: &DisplaySnapshot,
 304    delete_from: DisplayPoint,
 305    delete_until: DisplayPoint,
 306    ignore_brackets: bool,
 307) -> DisplayPoint {
 308    if delete_from == delete_until {
 309        return delete_until;
 310    }
 311    let is_backward = delete_from > delete_until;
 312    let delete_range = if is_backward {
 313        map.display_point_to_point(delete_until, Bias::Left)
 314            .to_offset(&map.buffer_snapshot)
 315            ..map
 316                .display_point_to_point(delete_from, Bias::Right)
 317                .to_offset(&map.buffer_snapshot)
 318    } else {
 319        map.display_point_to_point(delete_from, Bias::Left)
 320            .to_offset(&map.buffer_snapshot)
 321            ..map
 322                .display_point_to_point(delete_until, Bias::Right)
 323                .to_offset(&map.buffer_snapshot)
 324    };
 325
 326    let trimmed_delete_range = if ignore_brackets {
 327        delete_range
 328    } else {
 329        let brackets_in_delete_range = map
 330            .buffer_snapshot
 331            .bracket_ranges(delete_range.clone())
 332            .into_iter()
 333            .flatten()
 334            .flat_map(|(left_bracket, right_bracket)| {
 335                [
 336                    left_bracket.start,
 337                    left_bracket.end,
 338                    right_bracket.start,
 339                    right_bracket.end,
 340                ]
 341            })
 342            .filter(|&bracket| delete_range.start < bracket && bracket < delete_range.end);
 343        let closest_bracket = if is_backward {
 344            brackets_in_delete_range.max()
 345        } else {
 346            brackets_in_delete_range.min()
 347        };
 348
 349        if is_backward {
 350            closest_bracket.unwrap_or(delete_range.start)..delete_range.end
 351        } else {
 352            delete_range.start..closest_bracket.unwrap_or(delete_range.end)
 353        }
 354    };
 355
 356    let mut whitespace_sequences = Vec::new();
 357    let mut current_offset = trimmed_delete_range.start;
 358    let mut whitespace_sequence_length = 0;
 359    let mut whitespace_sequence_start = 0;
 360    for ch in map
 361        .buffer_snapshot
 362        .text_for_range(trimmed_delete_range.clone())
 363        .flat_map(str::chars)
 364    {
 365        if ch.is_whitespace() {
 366            if whitespace_sequence_length == 0 {
 367                whitespace_sequence_start = current_offset;
 368            }
 369            whitespace_sequence_length += 1;
 370        } else {
 371            if whitespace_sequence_length >= 2 {
 372                whitespace_sequences.push((whitespace_sequence_start, current_offset));
 373            }
 374            whitespace_sequence_start = 0;
 375            whitespace_sequence_length = 0;
 376        }
 377        current_offset += ch.len_utf8();
 378    }
 379    if whitespace_sequence_length >= 2 {
 380        whitespace_sequences.push((whitespace_sequence_start, current_offset));
 381    }
 382
 383    let closest_whitespace_end = if is_backward {
 384        whitespace_sequences.last().map(|&(start, _)| start)
 385    } else {
 386        whitespace_sequences.first().map(|&(_, end)| end)
 387    };
 388
 389    closest_whitespace_end
 390        .unwrap_or_else(|| {
 391            if is_backward {
 392                trimmed_delete_range.start
 393            } else {
 394                trimmed_delete_range.end
 395            }
 396        })
 397        .to_display_point(map)
 398}
 399
 400/// Returns a position of the previous subword boundary, where a subword is defined as a run of
 401/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 402/// lowerspace characters and uppercase characters.
 403pub fn previous_subword_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 404    let raw_point = point.to_point(map);
 405    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 406
 407    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 408        let is_word_start =
 409            classifier.kind(left) != classifier.kind(right) && !right.is_whitespace();
 410        let is_subword_start = classifier.is_word('-') && left == '-' && right != '-'
 411            || left == '_' && right != '_'
 412            || left.is_lowercase() && right.is_uppercase();
 413        is_word_start || is_subword_start || left == '\n'
 414    })
 415}
 416
 417/// Returns a position of the next word boundary, where a word character is defined as either
 418/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
 419pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 420    let raw_point = point.to_point(map);
 421    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 422    let mut is_first_iteration = true;
 423    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 424        // Make alt-right skip punctuation to respect VSCode behaviour. For example: |.hello goes to .hello|
 425        if is_first_iteration
 426            && classifier.is_punctuation(left)
 427            && !classifier.is_punctuation(right)
 428            && right != '\n'
 429        {
 430            is_first_iteration = false;
 431            return false;
 432        }
 433        is_first_iteration = false;
 434
 435        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(left))
 436            || right == '\n'
 437    })
 438}
 439
 440/// Returns a position of the next word boundary, where a word character is defined as either
 441/// uppercase letter, lowercase letter, '_' character, language-specific word character (like '-' in CSS) or newline.
 442pub fn next_word_end_or_newline(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 443    let raw_point = point.to_point(map);
 444    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 445
 446    let mut on_starting_row = true;
 447    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 448        if left == '\n' {
 449            on_starting_row = false;
 450        }
 451        (classifier.kind(left) != classifier.kind(right)
 452            && ((on_starting_row && !left.is_whitespace())
 453                || (!on_starting_row && !right.is_whitespace())))
 454            || right == '\n'
 455    })
 456}
 457
 458/// Returns a position of the next subword boundary, where a subword is defined as a run of
 459/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 460/// lowerspace characters and uppercase characters.
 461pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 462    let raw_point = point.to_point(map);
 463    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 464
 465    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 466        let is_word_end =
 467            (classifier.kind(left) != classifier.kind(right)) && !classifier.is_whitespace(left);
 468        let is_subword_end = classifier.is_word('-') && left != '-' && right == '-'
 469            || left != '_' && right == '_'
 470            || left.is_lowercase() && right.is_uppercase();
 471        is_word_end || is_subword_end || right == '\n'
 472    })
 473}
 474
 475/// Returns a position of the start of the current paragraph, where a paragraph
 476/// is defined as a run of non-blank lines.
 477pub fn start_of_paragraph(
 478    map: &DisplaySnapshot,
 479    display_point: DisplayPoint,
 480    mut count: usize,
 481) -> DisplayPoint {
 482    let point = display_point.to_point(map);
 483    if point.row == 0 {
 484        return DisplayPoint::zero();
 485    }
 486
 487    let mut found_non_blank_line = false;
 488    for row in (0..point.row + 1).rev() {
 489        let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
 490        if found_non_blank_line && blank {
 491            if count <= 1 {
 492                return Point::new(row, 0).to_display_point(map);
 493            }
 494            count -= 1;
 495            found_non_blank_line = false;
 496        }
 497
 498        found_non_blank_line |= !blank;
 499    }
 500
 501    DisplayPoint::zero()
 502}
 503
 504/// Returns a position of the end of the current paragraph, where a paragraph
 505/// is defined as a run of non-blank lines.
 506pub fn end_of_paragraph(
 507    map: &DisplaySnapshot,
 508    display_point: DisplayPoint,
 509    mut count: usize,
 510) -> DisplayPoint {
 511    let point = display_point.to_point(map);
 512    if point.row == map.buffer_snapshot.max_row().0 {
 513        return map.max_point();
 514    }
 515
 516    let mut found_non_blank_line = false;
 517    for row in point.row..=map.buffer_snapshot.max_row().0 {
 518        let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
 519        if found_non_blank_line && blank {
 520            if count <= 1 {
 521                return Point::new(row, 0).to_display_point(map);
 522            }
 523            count -= 1;
 524            found_non_blank_line = false;
 525        }
 526
 527        found_non_blank_line |= !blank;
 528    }
 529
 530    map.max_point()
 531}
 532
 533pub fn start_of_excerpt(
 534    map: &DisplaySnapshot,
 535    display_point: DisplayPoint,
 536    direction: Direction,
 537) -> DisplayPoint {
 538    let point = map.display_point_to_point(display_point, Bias::Left);
 539    let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point..point) else {
 540        return display_point;
 541    };
 542    match direction {
 543        Direction::Prev => {
 544            let mut start = excerpt.start_anchor().to_display_point(map);
 545            if start >= display_point && start.row() > DisplayRow(0) {
 546                let Some(excerpt) = map.buffer_snapshot.excerpt_before(excerpt.id()) else {
 547                    return display_point;
 548                };
 549                start = excerpt.start_anchor().to_display_point(map);
 550            }
 551            start
 552        }
 553        Direction::Next => {
 554            let mut end = excerpt.end_anchor().to_display_point(map);
 555            *end.row_mut() += 1;
 556            map.clip_point(end, Bias::Right)
 557        }
 558    }
 559}
 560
 561pub fn end_of_excerpt(
 562    map: &DisplaySnapshot,
 563    display_point: DisplayPoint,
 564    direction: Direction,
 565) -> DisplayPoint {
 566    let point = map.display_point_to_point(display_point, Bias::Left);
 567    let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point..point) else {
 568        return display_point;
 569    };
 570    match direction {
 571        Direction::Prev => {
 572            let mut start = excerpt.start_anchor().to_display_point(map);
 573            if start.row() > DisplayRow(0) {
 574                *start.row_mut() -= 1;
 575            }
 576            start = map.clip_point(start, Bias::Left);
 577            *start.column_mut() = 0;
 578            start
 579        }
 580        Direction::Next => {
 581            let mut end = excerpt.end_anchor().to_display_point(map);
 582            *end.column_mut() = 0;
 583            if end <= display_point {
 584                *end.row_mut() += 1;
 585                let point_end = map.display_point_to_point(end, Bias::Right);
 586                let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point_end..point_end)
 587                else {
 588                    return display_point;
 589                };
 590                end = excerpt.end_anchor().to_display_point(map);
 591                *end.column_mut() = 0;
 592            }
 593            end
 594        }
 595    }
 596}
 597
 598/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 599/// indicated by the given predicate returning true.
 600/// The predicate is called with the character to the left and right of the candidate boundary location.
 601/// 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.
 602pub fn find_preceding_boundary_point(
 603    buffer_snapshot: &MultiBufferSnapshot,
 604    from: Point,
 605    find_range: FindRange,
 606    mut is_boundary: impl FnMut(char, char) -> bool,
 607) -> Point {
 608    let mut prev_ch = None;
 609    let mut offset = from.to_offset(buffer_snapshot);
 610
 611    for ch in buffer_snapshot.reversed_chars_at(offset) {
 612        if find_range == FindRange::SingleLine && ch == '\n' {
 613            break;
 614        }
 615        if let Some(prev_ch) = prev_ch
 616            && is_boundary(ch, prev_ch)
 617        {
 618            break;
 619        }
 620
 621        offset -= ch.len_utf8();
 622        prev_ch = Some(ch);
 623    }
 624
 625    offset.to_point(buffer_snapshot)
 626}
 627
 628/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 629/// indicated by the given predicate returning true.
 630/// The predicate is called with the character to the left and right of the candidate boundary location.
 631/// 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.
 632pub fn find_preceding_boundary_display_point(
 633    map: &DisplaySnapshot,
 634    from: DisplayPoint,
 635    find_range: FindRange,
 636    is_boundary: impl FnMut(char, char) -> bool,
 637) -> DisplayPoint {
 638    let result = find_preceding_boundary_point(
 639        &map.buffer_snapshot,
 640        from.to_point(map),
 641        find_range,
 642        is_boundary,
 643    );
 644    map.clip_point(result.to_display_point(map), Bias::Left)
 645}
 646
 647/// Scans for a boundary following the given start point until a boundary is found, indicated by the
 648/// given predicate returning true. The predicate is called with the character to the left and right
 649/// of the candidate boundary location, and will be called with `\n` characters indicating the start
 650/// or end of a line. The function supports optionally returning the point just before the boundary
 651/// is found via return_point_before_boundary.
 652pub fn find_boundary_point(
 653    map: &DisplaySnapshot,
 654    from: DisplayPoint,
 655    find_range: FindRange,
 656    mut is_boundary: impl FnMut(char, char) -> bool,
 657    return_point_before_boundary: bool,
 658) -> DisplayPoint {
 659    let mut offset = from.to_offset(map, Bias::Right);
 660    let mut prev_offset = offset;
 661    let mut prev_ch = None;
 662
 663    for ch in map.buffer_snapshot.chars_at(offset) {
 664        if find_range == FindRange::SingleLine && ch == '\n' {
 665            break;
 666        }
 667        if let Some(prev_ch) = prev_ch
 668            && is_boundary(prev_ch, ch)
 669        {
 670            if return_point_before_boundary {
 671                return map.clip_point(prev_offset.to_display_point(map), Bias::Right);
 672            } else {
 673                break;
 674            }
 675        }
 676        prev_offset = offset;
 677        offset += ch.len_utf8();
 678        prev_ch = Some(ch);
 679    }
 680    map.clip_point(offset.to_display_point(map), Bias::Right)
 681}
 682
 683pub fn find_preceding_boundary_trail(
 684    map: &DisplaySnapshot,
 685    head: DisplayPoint,
 686    mut is_boundary: impl FnMut(char, char) -> bool,
 687) -> (Option<DisplayPoint>, DisplayPoint) {
 688    let mut offset = head.to_offset(map, Bias::Left);
 689    let mut trail_offset = None;
 690
 691    let mut prev_ch = map.buffer_snapshot.chars_at(offset).next();
 692    let mut forward = map.buffer_snapshot.reversed_chars_at(offset).peekable();
 693
 694    // Skip newlines
 695    while let Some(&ch) = forward.peek() {
 696        if ch == '\n' {
 697            prev_ch = forward.next();
 698            offset -= ch.len_utf8();
 699            trail_offset = Some(offset);
 700        } else {
 701            break;
 702        }
 703    }
 704
 705    // Find the boundary
 706    let start_offset = offset;
 707    for ch in forward {
 708        if let Some(prev_ch) = prev_ch
 709            && is_boundary(prev_ch, ch)
 710        {
 711            if start_offset == offset {
 712                trail_offset = Some(offset);
 713            } else {
 714                break;
 715            }
 716        }
 717        offset -= ch.len_utf8();
 718        prev_ch = Some(ch);
 719    }
 720
 721    let trail = trail_offset
 722        .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Left));
 723
 724    (
 725        trail,
 726        map.clip_point(offset.to_display_point(map), Bias::Left),
 727    )
 728}
 729
 730/// Finds the location of a boundary
 731pub fn find_boundary_trail(
 732    map: &DisplaySnapshot,
 733    head: DisplayPoint,
 734    mut is_boundary: impl FnMut(char, char) -> bool,
 735) -> (Option<DisplayPoint>, DisplayPoint) {
 736    let mut offset = head.to_offset(map, Bias::Right);
 737    let mut trail_offset = None;
 738
 739    let mut prev_ch = map.buffer_snapshot.reversed_chars_at(offset).next();
 740    let mut forward = map.buffer_snapshot.chars_at(offset).peekable();
 741
 742    // Skip newlines
 743    while let Some(&ch) = forward.peek() {
 744        if ch == '\n' {
 745            prev_ch = forward.next();
 746            offset += ch.len_utf8();
 747            trail_offset = Some(offset);
 748        } else {
 749            break;
 750        }
 751    }
 752
 753    // Find the boundary
 754    let start_offset = offset;
 755    for ch in forward {
 756        if let Some(prev_ch) = prev_ch
 757            && is_boundary(prev_ch, ch)
 758        {
 759            if start_offset == offset {
 760                trail_offset = Some(offset);
 761            } else {
 762                break;
 763            }
 764        }
 765        offset += ch.len_utf8();
 766        prev_ch = Some(ch);
 767    }
 768
 769    let trail = trail_offset
 770        .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Right));
 771
 772    (
 773        trail,
 774        map.clip_point(offset.to_display_point(map), Bias::Right),
 775    )
 776}
 777
 778pub fn find_boundary(
 779    map: &DisplaySnapshot,
 780    from: DisplayPoint,
 781    find_range: FindRange,
 782    is_boundary: impl FnMut(char, char) -> bool,
 783) -> DisplayPoint {
 784    find_boundary_point(map, from, find_range, is_boundary, false)
 785}
 786
 787pub fn find_boundary_exclusive(
 788    map: &DisplaySnapshot,
 789    from: DisplayPoint,
 790    find_range: FindRange,
 791    is_boundary: impl FnMut(char, char) -> bool,
 792) -> DisplayPoint {
 793    find_boundary_point(map, from, find_range, is_boundary, true)
 794}
 795
 796/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
 797/// The returned value also contains a range of the start/end of a returned character in
 798/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 799pub fn chars_after(
 800    map: &DisplaySnapshot,
 801    mut offset: usize,
 802) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
 803    map.buffer_snapshot.chars_at(offset).map(move |ch| {
 804        let before = offset;
 805        offset += ch.len_utf8();
 806        (ch, before..offset)
 807    })
 808}
 809
 810/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
 811/// The returned value also contains a range of the start/end of a returned character in
 812/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 813pub fn chars_before(
 814    map: &DisplaySnapshot,
 815    mut offset: usize,
 816) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
 817    map.buffer_snapshot
 818        .reversed_chars_at(offset)
 819        .map(move |ch| {
 820            let after = offset;
 821            offset -= ch.len_utf8();
 822            (ch, offset..after)
 823        })
 824}
 825
 826/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
 827/// within a passed range.
 828///
 829/// The line ranges are **always* going to be in bounds of a requested range, which means that
 830/// the first and the last lines might not necessarily represent the
 831/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
 832pub fn split_display_range_by_lines(
 833    map: &DisplaySnapshot,
 834    range: Range<DisplayPoint>,
 835) -> Vec<Range<DisplayPoint>> {
 836    let mut result = Vec::new();
 837
 838    let mut start = range.start;
 839    // Loop over all the covered rows until the one containing the range end
 840    for row in range.start.row().0..range.end.row().0 {
 841        let row_end_column = map.line_len(DisplayRow(row));
 842        let end = map.clip_point(
 843            DisplayPoint::new(DisplayRow(row), row_end_column),
 844            Bias::Left,
 845        );
 846        if start != end {
 847            result.push(start..end);
 848        }
 849        start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
 850    }
 851
 852    // Add the final range from the start of the last end to the original range end.
 853    result.push(start..range.end);
 854
 855    result
 856}
 857
 858#[cfg(test)]
 859mod tests {
 860    use super::*;
 861    use crate::{
 862        Buffer, DisplayMap, DisplayRow, ExcerptRange, FoldPlaceholder, MultiBuffer,
 863        display_map::Inlay,
 864        test::{editor_test_context::EditorTestContext, marked_display_snapshot},
 865    };
 866    use gpui::{AppContext as _, font, px};
 867    use language::Capability;
 868    use project::{Project, project_settings::DiagnosticSeverity};
 869    use settings::SettingsStore;
 870    use util::post_inc;
 871
 872    #[gpui::test]
 873    fn test_previous_word_start(cx: &mut gpui::App) {
 874        init_test(cx);
 875
 876        fn assert(marked_text: &str, cx: &mut gpui::App) {
 877            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 878            let actual = previous_word_start(&snapshot, display_points[1]);
 879            let expected = display_points[0];
 880            if actual != expected {
 881                eprintln!(
 882                    "previous_word_start mismatch for '{}': actual={:?}, expected={:?}",
 883                    marked_text, actual, expected
 884                );
 885            }
 886            assert_eq!(actual, expected);
 887        }
 888
 889        assert("\nˇ   ˇlorem", cx);
 890        assert("ˇ\nˇ   lorem", cx);
 891        assert("    ˇloremˇ", cx);
 892        assert("ˇ    ˇlorem", cx);
 893        assert("    ˇlorˇem", cx);
 894        assert("\nlorem\nˇ   ˇipsum", cx);
 895        assert("\n\nˇ\nˇ", cx);
 896        assert("    ˇlorem  ˇipsum", cx);
 897        assert("ˇlorem-ˇipsum", cx);
 898        assert("loremˇ-#$@ˇipsum", cx);
 899        assert("ˇlorem_ˇipsum", cx);
 900        assert(" ˇdefγˇ", cx);
 901        assert(" ˇbcΔˇ", cx);
 902        // Test punctuation skipping behavior
 903        assert("ˇhello.ˇ", cx);
 904        assert("helloˇ...ˇ", cx);
 905        assert("helloˇ.---..ˇtest", cx);
 906        assert("test  ˇ.--ˇtest", cx);
 907        assert("oneˇ,;:!?ˇtwo", cx);
 908    }
 909
 910    #[gpui::test]
 911    fn test_previous_subword_start(cx: &mut gpui::App) {
 912        init_test(cx);
 913
 914        fn assert(marked_text: &str, cx: &mut gpui::App) {
 915            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 916            assert_eq!(
 917                previous_subword_start(&snapshot, display_points[1]),
 918                display_points[0]
 919            );
 920        }
 921
 922        // Subword boundaries are respected
 923        assert("lorem_ˇipˇsum", cx);
 924        assert("lorem_ˇipsumˇ", cx);
 925        assert("ˇlorem_ˇipsum", cx);
 926        assert("lorem_ˇipsum_ˇdolor", cx);
 927        assert("loremˇIpˇsum", cx);
 928        assert("loremˇIpsumˇ", cx);
 929
 930        // Word boundaries are still respected
 931        assert("\nˇ   ˇlorem", cx);
 932        assert("    ˇloremˇ", cx);
 933        assert("    ˇlorˇem", cx);
 934        assert("\nlorem\nˇ   ˇipsum", cx);
 935        assert("\n\nˇ\nˇ", cx);
 936        assert("    ˇlorem  ˇipsum", cx);
 937        assert("loremˇ-ˇipsum", cx);
 938        assert("loremˇ-#$@ˇipsum", cx);
 939        assert(" ˇdefγˇ", cx);
 940        assert(" bcˇΔˇ", cx);
 941        assert(" ˇbcδˇ", cx);
 942        assert(" abˇ——ˇcd", cx);
 943    }
 944
 945    #[gpui::test]
 946    fn test_find_preceding_boundary(cx: &mut gpui::App) {
 947        init_test(cx);
 948
 949        fn assert(
 950            marked_text: &str,
 951            cx: &mut gpui::App,
 952            is_boundary: impl FnMut(char, char) -> bool,
 953        ) {
 954            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 955            assert_eq!(
 956                find_preceding_boundary_display_point(
 957                    &snapshot,
 958                    display_points[1],
 959                    FindRange::MultiLine,
 960                    is_boundary
 961                ),
 962                display_points[0]
 963            );
 964        }
 965
 966        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
 967            left == 'c' && right == 'd'
 968        });
 969        assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
 970            left == '\n' && right == 'g'
 971        });
 972        let mut line_count = 0;
 973        assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
 974            if left == '\n' {
 975                line_count += 1;
 976                line_count == 2
 977            } else {
 978                false
 979            }
 980        });
 981    }
 982
 983    #[gpui::test]
 984    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::App) {
 985        init_test(cx);
 986
 987        let input_text = "abcdefghijklmnopqrstuvwxys";
 988        let font = font("Helvetica");
 989        let font_size = px(14.0);
 990        let buffer = MultiBuffer::build_simple(input_text, cx);
 991        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 992
 993        let display_map = cx.new(|cx| {
 994            DisplayMap::new(
 995                buffer,
 996                font,
 997                font_size,
 998                None,
 999                1,
1000                1,
1001                FoldPlaceholder::test(),
1002                DiagnosticSeverity::Warning,
1003                cx,
1004            )
1005        });
1006
1007        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
1008        let mut id = 0;
1009        let inlays = (0..buffer_snapshot.len())
1010            .flat_map(|offset| {
1011                [
1012                    Inlay::edit_prediction(
1013                        post_inc(&mut id),
1014                        buffer_snapshot.anchor_at(offset, Bias::Left),
1015                        "test",
1016                    ),
1017                    Inlay::edit_prediction(
1018                        post_inc(&mut id),
1019                        buffer_snapshot.anchor_at(offset, Bias::Right),
1020                        "test",
1021                    ),
1022                    Inlay::mock_hint(
1023                        post_inc(&mut id),
1024                        buffer_snapshot.anchor_at(offset, Bias::Left),
1025                        "test",
1026                    ),
1027                    Inlay::mock_hint(
1028                        post_inc(&mut id),
1029                        buffer_snapshot.anchor_at(offset, Bias::Right),
1030                        "test",
1031                    ),
1032                ]
1033            })
1034            .collect();
1035        let snapshot = display_map.update(cx, |map, cx| {
1036            map.splice_inlays(&[], inlays, cx);
1037            map.snapshot(cx)
1038        });
1039
1040        assert_eq!(
1041            find_preceding_boundary_display_point(
1042                &snapshot,
1043                buffer_snapshot.len().to_display_point(&snapshot),
1044                FindRange::MultiLine,
1045                |left, _| left == 'e',
1046            ),
1047            snapshot
1048                .buffer_snapshot
1049                .offset_to_point(5)
1050                .to_display_point(&snapshot),
1051            "Should not stop at inlays when looking for boundaries"
1052        );
1053    }
1054
1055    #[gpui::test]
1056    fn test_next_word_end(cx: &mut gpui::App) {
1057        init_test(cx);
1058
1059        fn assert(marked_text: &str, cx: &mut gpui::App) {
1060            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1061            let actual = next_word_end(&snapshot, display_points[0]);
1062            let expected = display_points[1];
1063            if actual != expected {
1064                eprintln!(
1065                    "next_word_end mismatch for '{}': actual={:?}, expected={:?}",
1066                    marked_text, actual, expected
1067                );
1068            }
1069            assert_eq!(actual, expected);
1070        }
1071
1072        assert("\nˇ   loremˇ", cx);
1073        assert("    ˇloremˇ", cx);
1074        assert("    lorˇemˇ", cx);
1075        assert("    loremˇ    ˇ\nipsum\n", cx);
1076        assert("\nˇ\nˇ\n\n", cx);
1077        assert("loremˇ    ipsumˇ   ", cx);
1078        assert("loremˇ-ipsumˇ", cx);
1079        assert("loremˇ#$@-ˇipsum", cx);
1080        assert("loremˇ_ipsumˇ", cx);
1081        assert(" ˇbcΔˇ", cx);
1082        assert(" abˇ——ˇcd", cx);
1083        // Test punctuation skipping behavior
1084        assert("ˇ.helloˇ", cx);
1085        assert("display_pointsˇ[0ˇ]", cx);
1086        assert("ˇ...ˇhello", cx);
1087        assert("helloˇ.---..ˇtest", cx);
1088        assert("testˇ.--ˇ test", cx);
1089        assert("oneˇ,;:!?ˇtwo", cx);
1090    }
1091
1092    #[gpui::test]
1093    fn test_next_subword_end(cx: &mut gpui::App) {
1094        init_test(cx);
1095
1096        fn assert(marked_text: &str, cx: &mut gpui::App) {
1097            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1098            assert_eq!(
1099                next_subword_end(&snapshot, display_points[0]),
1100                display_points[1]
1101            );
1102        }
1103
1104        // Subword boundaries are respected
1105        assert("loˇremˇ_ipsum", cx);
1106        assert("ˇloremˇ_ipsum", cx);
1107        assert("loremˇ_ipsumˇ", cx);
1108        assert("loremˇ_ipsumˇ_dolor", cx);
1109        assert("loˇremˇIpsum", cx);
1110        assert("loremˇIpsumˇDolor", cx);
1111
1112        // Word boundaries are still respected
1113        assert("\nˇ   loremˇ", cx);
1114        assert("    ˇloremˇ", cx);
1115        assert("    lorˇemˇ", cx);
1116        assert("    loremˇ    ˇ\nipsum\n", cx);
1117        assert("\nˇ\nˇ\n\n", cx);
1118        assert("loremˇ    ipsumˇ   ", cx);
1119        assert("loremˇ-ˇipsum", cx);
1120        assert("loremˇ#$@-ˇipsum", cx);
1121        assert("loremˇ_ipsumˇ", cx);
1122        assert(" ˇbcˇΔ", cx);
1123        assert(" abˇ——ˇcd", cx);
1124    }
1125
1126    #[gpui::test]
1127    fn test_find_boundary(cx: &mut gpui::App) {
1128        init_test(cx);
1129
1130        fn assert(
1131            marked_text: &str,
1132            cx: &mut gpui::App,
1133            is_boundary: impl FnMut(char, char) -> bool,
1134        ) {
1135            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1136            assert_eq!(
1137                find_boundary(
1138                    &snapshot,
1139                    display_points[0],
1140                    FindRange::MultiLine,
1141                    is_boundary,
1142                ),
1143                display_points[1]
1144            );
1145        }
1146
1147        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
1148            left == 'j' && right == 'k'
1149        });
1150        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
1151            left == '\n' && right == 'i'
1152        });
1153        let mut line_count = 0;
1154        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
1155            if left == '\n' {
1156                line_count += 1;
1157                line_count == 2
1158            } else {
1159                false
1160            }
1161        });
1162    }
1163
1164    #[gpui::test]
1165    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
1166        cx.update(|cx| {
1167            init_test(cx);
1168        });
1169
1170        let mut cx = EditorTestContext::new(cx).await;
1171        let editor = cx.editor.clone();
1172        let window = cx.window;
1173        _ = cx.update_window(window, |_, window, cx| {
1174            let text_layout_details = editor.read(cx).text_layout_details(window);
1175
1176            let font = font("Helvetica");
1177
1178            let buffer = cx.new(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
1179            let multibuffer = cx.new(|cx| {
1180                let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1181                multibuffer.push_excerpts(
1182                    buffer.clone(),
1183                    [
1184                        ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
1185                        ExcerptRange::new(Point::new(2, 0)..Point::new(3, 2)),
1186                    ],
1187                    cx,
1188                );
1189                multibuffer
1190            });
1191            let display_map = cx.new(|cx| {
1192                DisplayMap::new(
1193                    multibuffer,
1194                    font,
1195                    px(14.0),
1196                    None,
1197                    0,
1198                    1,
1199                    FoldPlaceholder::test(),
1200                    DiagnosticSeverity::Warning,
1201                    cx,
1202                )
1203            });
1204            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1205
1206            assert_eq!(snapshot.text(), "abc\ndefg\n\nhijkl\nmn");
1207
1208            let col_2_x = snapshot
1209                .x_for_display_point(DisplayPoint::new(DisplayRow(0), 2), &text_layout_details);
1210
1211            // Can't move up into the first excerpt's header
1212            assert_eq!(
1213                up(
1214                    &snapshot,
1215                    DisplayPoint::new(DisplayRow(0), 2),
1216                    SelectionGoal::HorizontalPosition(col_2_x.0),
1217                    false,
1218                    &text_layout_details
1219                ),
1220                (
1221                    DisplayPoint::new(DisplayRow(0), 0),
1222                    SelectionGoal::HorizontalPosition(col_2_x.0),
1223                ),
1224            );
1225            assert_eq!(
1226                up(
1227                    &snapshot,
1228                    DisplayPoint::new(DisplayRow(0), 0),
1229                    SelectionGoal::None,
1230                    false,
1231                    &text_layout_details
1232                ),
1233                (
1234                    DisplayPoint::new(DisplayRow(0), 0),
1235                    SelectionGoal::HorizontalPosition(0.0),
1236                ),
1237            );
1238
1239            let col_4_x = snapshot
1240                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 4), &text_layout_details);
1241
1242            // Move up and down within first excerpt
1243            assert_eq!(
1244                up(
1245                    &snapshot,
1246                    DisplayPoint::new(DisplayRow(1), 4),
1247                    SelectionGoal::HorizontalPosition(col_4_x.0),
1248                    false,
1249                    &text_layout_details
1250                ),
1251                (
1252                    DisplayPoint::new(DisplayRow(0), 3),
1253                    SelectionGoal::HorizontalPosition(col_4_x.0)
1254                ),
1255            );
1256            assert_eq!(
1257                down(
1258                    &snapshot,
1259                    DisplayPoint::new(DisplayRow(0), 3),
1260                    SelectionGoal::HorizontalPosition(col_4_x.0),
1261                    false,
1262                    &text_layout_details
1263                ),
1264                (
1265                    DisplayPoint::new(DisplayRow(1), 4),
1266                    SelectionGoal::HorizontalPosition(col_4_x.0)
1267                ),
1268            );
1269
1270            let col_5_x = snapshot
1271                .x_for_display_point(DisplayPoint::new(DisplayRow(3), 5), &text_layout_details);
1272
1273            // Move up and down across second excerpt's header
1274            assert_eq!(
1275                up(
1276                    &snapshot,
1277                    DisplayPoint::new(DisplayRow(3), 5),
1278                    SelectionGoal::HorizontalPosition(col_5_x.0),
1279                    false,
1280                    &text_layout_details
1281                ),
1282                (
1283                    DisplayPoint::new(DisplayRow(1), 4),
1284                    SelectionGoal::HorizontalPosition(col_5_x.0)
1285                ),
1286            );
1287            assert_eq!(
1288                down(
1289                    &snapshot,
1290                    DisplayPoint::new(DisplayRow(1), 4),
1291                    SelectionGoal::HorizontalPosition(col_5_x.0),
1292                    false,
1293                    &text_layout_details
1294                ),
1295                (
1296                    DisplayPoint::new(DisplayRow(3), 5),
1297                    SelectionGoal::HorizontalPosition(col_5_x.0)
1298                ),
1299            );
1300
1301            let max_point_x = snapshot
1302                .x_for_display_point(DisplayPoint::new(DisplayRow(4), 2), &text_layout_details);
1303
1304            // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1305            assert_eq!(
1306                down(
1307                    &snapshot,
1308                    DisplayPoint::new(DisplayRow(4), 0),
1309                    SelectionGoal::HorizontalPosition(0.0),
1310                    false,
1311                    &text_layout_details
1312                ),
1313                (
1314                    DisplayPoint::new(DisplayRow(4), 2),
1315                    SelectionGoal::HorizontalPosition(0.0)
1316                ),
1317            );
1318            assert_eq!(
1319                down(
1320                    &snapshot,
1321                    DisplayPoint::new(DisplayRow(4), 2),
1322                    SelectionGoal::HorizontalPosition(max_point_x.0),
1323                    false,
1324                    &text_layout_details
1325                ),
1326                (
1327                    DisplayPoint::new(DisplayRow(4), 2),
1328                    SelectionGoal::HorizontalPosition(max_point_x.0)
1329                ),
1330            );
1331        });
1332    }
1333
1334    fn init_test(cx: &mut gpui::App) {
1335        let settings_store = SettingsStore::test(cx);
1336        cx.set_global(settings_store);
1337        workspace::init_settings(cx);
1338        theme::init(theme::LoadThemes::JustBase, cx);
1339        language::init(cx);
1340        crate::init(cx);
1341        Project::init_settings(cx);
1342    }
1343}