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