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::{ScrollOffset, SharedScrollAnchor},
   8};
   9use gpui::{Pixels, WindowTextSystem};
  10use language::{CharClassifier, Point};
  11use multi_buffer::{MultiBufferOffset, 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: SharedScrollAnchor,
  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, &mut |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, &mut |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 = MultiBufferOffset(0);
 362    let mut whitespace_sequence_start = MultiBufferOffset(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 == MultiBufferOffset(0) {
 370                whitespace_sequence_start = current_offset;
 371            }
 372            whitespace_sequence_length += 1;
 373        } else {
 374            if whitespace_sequence_length >= MultiBufferOffset(2) {
 375                whitespace_sequences.push((whitespace_sequence_start, current_offset));
 376            }
 377            whitespace_sequence_start = MultiBufferOffset(0);
 378            whitespace_sequence_length = MultiBufferOffset(0);
 379        }
 380        current_offset += ch.len_utf8();
 381    }
 382    if whitespace_sequence_length >= MultiBufferOffset(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, &mut |left, right| {
 411        is_subword_start(left, right, &classifier) || left == '\n' || right == '\n'
 412    })
 413}
 414
 415/// Returns a position of the previous subword boundary, where a subword is defined as a run of
 416/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 417/// lowerspace characters and uppercase characters or newline.
 418pub fn previous_subword_start_or_newline(
 419    map: &DisplaySnapshot,
 420    point: DisplayPoint,
 421) -> DisplayPoint {
 422    let raw_point = point.to_point(map);
 423    let classifier = map.buffer_snapshot().char_classifier_at(raw_point);
 424
 425    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, &mut |left, right| {
 426        (is_subword_start(left, right, &classifier)) || left == '\n' || right == '\n'
 427    })
 428}
 429
 430pub fn is_subword_start(left: char, right: char, classifier: &CharClassifier) -> bool {
 431    let is_word_start = classifier.kind(left) != classifier.kind(right) && !right.is_whitespace();
 432    let is_subword_start = classifier.is_word('-') && left == '-' && right != '-'
 433        || left == '_' && right != '_'
 434        || left != '_' && right == '_'
 435        || left.is_lowercase() && right.is_uppercase();
 436    is_word_start || is_subword_start
 437}
 438
 439/// Returns a position of the next word boundary, where a word character is defined as either
 440/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
 441pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 442    let raw_point = point.to_point(map);
 443    let classifier = map.buffer_snapshot().char_classifier_at(raw_point);
 444    let mut is_first_iteration = true;
 445    find_boundary(map, point, FindRange::MultiLine, &mut |left, right| {
 446        // Make alt-right skip punctuation to respect VSCode behaviour. For example: |.hello goes to .hello|
 447        if is_first_iteration
 448            && classifier.is_punctuation(left)
 449            && !classifier.is_punctuation(right)
 450            && right != '\n'
 451        {
 452            is_first_iteration = false;
 453            return false;
 454        }
 455        is_first_iteration = false;
 456
 457        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(left))
 458            || right == '\n'
 459    })
 460}
 461
 462/// Returns a position of the next word boundary, where a word character is defined as either
 463/// uppercase letter, lowercase letter, '_' character, language-specific word character (like '-' in CSS) or newline.
 464pub fn next_word_end_or_newline(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 465    let raw_point = point.to_point(map);
 466    let classifier = map.buffer_snapshot().char_classifier_at(raw_point);
 467
 468    let mut on_starting_row = true;
 469    find_boundary(map, point, FindRange::MultiLine, &mut |left, right| {
 470        if left == '\n' {
 471            on_starting_row = false;
 472        }
 473        (classifier.kind(left) != classifier.kind(right)
 474            && ((on_starting_row && !left.is_whitespace())
 475                || (!on_starting_row && !right.is_whitespace())))
 476            || right == '\n'
 477    })
 478}
 479
 480/// Returns a position of the next subword boundary, where a subword is defined as a run of
 481/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 482/// lowerspace characters and uppercase characters.
 483pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 484    let raw_point = point.to_point(map);
 485    let classifier = map.buffer_snapshot().char_classifier_at(raw_point);
 486
 487    find_boundary(map, point, FindRange::MultiLine, &mut |left, right| {
 488        is_subword_end(left, right, &classifier) || left == '\n' || right == '\n'
 489    })
 490}
 491
 492/// Returns a position of the next subword boundary, where a subword is defined as a run of
 493/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 494/// lowerspace characters and uppercase characters or newline.
 495pub fn next_subword_end_or_newline(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 496    let raw_point = point.to_point(map);
 497    let classifier = map.buffer_snapshot().char_classifier_at(raw_point);
 498
 499    let mut on_starting_row = true;
 500    find_boundary(map, point, FindRange::MultiLine, &mut |left, right| {
 501        if left == '\n' {
 502            on_starting_row = false;
 503        }
 504        ((classifier.kind(left) != classifier.kind(right)
 505            || is_subword_boundary_end(left, right, &classifier))
 506            && ((on_starting_row && !left.is_whitespace())
 507                || (!on_starting_row && !right.is_whitespace())))
 508            || right == '\n'
 509    })
 510}
 511
 512pub fn is_subword_end(left: char, right: char, classifier: &CharClassifier) -> bool {
 513    let is_word_end =
 514        (classifier.kind(left) != classifier.kind(right)) && !classifier.is_whitespace(left);
 515    is_word_end || is_subword_boundary_end(left, right, classifier)
 516}
 517
 518/// Returns true if the transition from `left` to `right` is a subword boundary,
 519/// such as case changes, underscores, or dashes. Does not include word boundaries like whitespace.
 520fn is_subword_boundary_end(left: char, right: char, classifier: &CharClassifier) -> bool {
 521    classifier.is_word('-') && left != '-' && right == '-'
 522        || left != '_' && right == '_'
 523        || left == '_' && right != '_'
 524        || left.is_lowercase() && right.is_uppercase()
 525}
 526
 527/// Returns a position of the start of the current paragraph, where a paragraph
 528/// is defined as a run of non-blank lines.
 529pub fn start_of_paragraph(
 530    map: &DisplaySnapshot,
 531    display_point: DisplayPoint,
 532    mut count: usize,
 533) -> DisplayPoint {
 534    let point = display_point.to_point(map);
 535    if point.row == 0 {
 536        return DisplayPoint::zero();
 537    }
 538
 539    let mut found_non_blank_line = false;
 540    for row in (0..point.row + 1).rev() {
 541        let blank = map.buffer_snapshot().is_line_blank(MultiBufferRow(row));
 542        if found_non_blank_line && blank {
 543            if count <= 1 {
 544                return Point::new(row, 0).to_display_point(map);
 545            }
 546            count -= 1;
 547            found_non_blank_line = false;
 548        }
 549
 550        found_non_blank_line |= !blank;
 551    }
 552
 553    DisplayPoint::zero()
 554}
 555
 556/// Returns a position of the end of the current paragraph, where a paragraph
 557/// is defined as a run of non-blank lines.
 558pub fn end_of_paragraph(
 559    map: &DisplaySnapshot,
 560    display_point: DisplayPoint,
 561    mut count: usize,
 562) -> DisplayPoint {
 563    let point = display_point.to_point(map);
 564    if point.row == map.buffer_snapshot().max_row().0 {
 565        return map.max_point();
 566    }
 567
 568    let mut found_non_blank_line = false;
 569    for row in point.row..=map.buffer_snapshot().max_row().0 {
 570        let blank = map.buffer_snapshot().is_line_blank(MultiBufferRow(row));
 571        if found_non_blank_line && blank {
 572            if count <= 1 {
 573                return Point::new(row, 0).to_display_point(map);
 574            }
 575            count -= 1;
 576            found_non_blank_line = false;
 577        }
 578
 579        found_non_blank_line |= !blank;
 580    }
 581
 582    map.max_point()
 583}
 584
 585pub fn start_of_excerpt(
 586    map: &DisplaySnapshot,
 587    display_point: DisplayPoint,
 588    direction: Direction,
 589) -> DisplayPoint {
 590    let point = map.display_point_to_point(display_point, Bias::Left);
 591    let Some((_, excerpt_range)) = map.buffer_snapshot().excerpt_containing(point..point) else {
 592        return display_point;
 593    };
 594    match direction {
 595        Direction::Prev => {
 596            let Some(start_anchor) = map.anchor_in_excerpt(excerpt_range.context.start) else {
 597                return display_point;
 598            };
 599            let mut start = start_anchor.to_display_point(map);
 600            if start >= display_point && start.row() > DisplayRow(0) {
 601                let Some(excerpt) = map.buffer_snapshot().excerpt_before(start_anchor) else {
 602                    return display_point;
 603                };
 604                if let Some(start_anchor) = map.anchor_in_excerpt(excerpt.context.start) {
 605                    start = start_anchor.to_display_point(map);
 606                }
 607            }
 608            start
 609        }
 610        Direction::Next => {
 611            let Some(end_anchor) = map.anchor_in_excerpt(excerpt_range.context.end) else {
 612                return display_point;
 613            };
 614            let mut end = end_anchor.to_display_point(map);
 615            *end.row_mut() += 1;
 616            map.clip_point(end, Bias::Right)
 617        }
 618    }
 619}
 620
 621pub fn end_of_excerpt(
 622    map: &DisplaySnapshot,
 623    display_point: DisplayPoint,
 624    direction: Direction,
 625) -> DisplayPoint {
 626    let point = map.display_point_to_point(display_point, Bias::Left);
 627    let Some((_, excerpt_range)) = map.buffer_snapshot().excerpt_containing(point..point) else {
 628        return display_point;
 629    };
 630    match direction {
 631        Direction::Prev => {
 632            let Some(start_anchor) = map.anchor_in_excerpt(excerpt_range.context.start) else {
 633                return display_point;
 634            };
 635            let mut start = start_anchor.to_display_point(map);
 636            if start.row() > DisplayRow(0) {
 637                *start.row_mut() -= 1;
 638            }
 639            start = map.clip_point(start, Bias::Left);
 640            *start.column_mut() = 0;
 641            start
 642        }
 643        Direction::Next => {
 644            let Some(end_anchor) = map.anchor_in_excerpt(excerpt_range.context.end) else {
 645                return display_point;
 646            };
 647            let mut end = end_anchor.to_display_point(map);
 648            *end.column_mut() = 0;
 649            if end <= display_point {
 650                *end.row_mut() += 1;
 651                let point_end = map.display_point_to_point(end, Bias::Right);
 652                let Some((_, excerpt_range)) = map
 653                    .buffer_snapshot()
 654                    .excerpt_containing(point_end..point_end)
 655                else {
 656                    return display_point;
 657                };
 658                if let Some(end_anchor) = map.anchor_in_excerpt(excerpt_range.context.end) {
 659                    end = end_anchor.to_display_point(map);
 660                }
 661                *end.column_mut() = 0;
 662            }
 663            end
 664        }
 665    }
 666}
 667
 668/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 669/// indicated by the given predicate returning true.
 670/// The predicate is called with the character to the left and right of the candidate boundary location.
 671/// 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.
 672pub fn find_preceding_boundary_point(
 673    buffer_snapshot: &MultiBufferSnapshot,
 674    from: Point,
 675    find_range: FindRange,
 676    is_boundary: &mut dyn FnMut(char, char) -> bool,
 677) -> Point {
 678    let mut prev_ch = None;
 679    let mut offset = from.to_offset(buffer_snapshot);
 680
 681    for ch in buffer_snapshot.reversed_chars_at(offset) {
 682        if find_range == FindRange::SingleLine && ch == '\n' {
 683            break;
 684        }
 685        if let Some(prev_ch) = prev_ch
 686            && is_boundary(ch, prev_ch)
 687        {
 688            break;
 689        }
 690
 691        offset -= ch.len_utf8();
 692        prev_ch = Some(ch);
 693    }
 694
 695    offset.to_point(buffer_snapshot)
 696}
 697
 698/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 699/// indicated by the given predicate returning true.
 700/// The predicate is called with the character to the left and right of the candidate boundary location.
 701/// 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.
 702pub fn find_preceding_boundary_display_point(
 703    map: &DisplaySnapshot,
 704    from: DisplayPoint,
 705    find_range: FindRange,
 706    is_boundary: &mut dyn FnMut(char, char) -> bool,
 707) -> DisplayPoint {
 708    let result = find_preceding_boundary_point(
 709        map.buffer_snapshot(),
 710        from.to_point(map),
 711        find_range,
 712        is_boundary,
 713    );
 714    map.clip_point(result.to_display_point(map), Bias::Left)
 715}
 716
 717/// Scans for a boundary following the given start point until a boundary is found, indicated by the
 718/// given predicate returning true. The predicate is called with the character to the left and right
 719/// of the candidate boundary location, and will be called with `\n` characters indicating the start
 720/// or end of a line. The function supports optionally returning the point just before the boundary
 721/// is found via return_point_before_boundary.
 722pub fn find_boundary_point(
 723    map: &DisplaySnapshot,
 724    from: DisplayPoint,
 725    find_range: FindRange,
 726    is_boundary: &mut dyn FnMut(char, char) -> bool,
 727    return_point_before_boundary: bool,
 728) -> DisplayPoint {
 729    let mut offset = from.to_offset(map, Bias::Right);
 730    let mut prev_offset = offset;
 731    let mut prev_ch = None;
 732
 733    for ch in map.buffer_snapshot().chars_at(offset) {
 734        if find_range == FindRange::SingleLine && ch == '\n' {
 735            break;
 736        }
 737        if let Some(prev_ch) = prev_ch
 738            && is_boundary(prev_ch, ch)
 739        {
 740            if return_point_before_boundary {
 741                let point = prev_offset.to_point(map.buffer_snapshot());
 742                return map.clip_point(map.point_to_display_point(point, Bias::Right), Bias::Right);
 743            } else {
 744                break;
 745            }
 746        }
 747        prev_offset = offset;
 748        offset += ch.len_utf8();
 749        prev_ch = Some(ch);
 750    }
 751    let point = offset.to_point(map.buffer_snapshot());
 752    map.clip_point(map.point_to_display_point(point, Bias::Right), Bias::Right)
 753}
 754
 755pub fn find_preceding_boundary_trail(
 756    map: &DisplaySnapshot,
 757    head: DisplayPoint,
 758    is_boundary: &mut dyn FnMut(char, char) -> bool,
 759) -> (Option<DisplayPoint>, DisplayPoint) {
 760    let mut offset = head.to_offset(map, Bias::Left);
 761    let mut trail_offset = None;
 762
 763    let mut prev_ch = map.buffer_snapshot().chars_at(offset).next();
 764    let mut forward = map.buffer_snapshot().reversed_chars_at(offset).peekable();
 765
 766    // Skip newlines
 767    while let Some(&ch) = forward.peek() {
 768        if ch == '\n' {
 769            prev_ch = forward.next();
 770            offset -= ch.len_utf8();
 771            trail_offset = Some(offset);
 772        } else {
 773            break;
 774        }
 775    }
 776
 777    // Find the boundary
 778    let start_offset = offset;
 779    for ch in forward {
 780        if let Some(prev_ch) = prev_ch
 781            && is_boundary(prev_ch, ch)
 782        {
 783            if start_offset == offset {
 784                trail_offset = Some(offset);
 785            } else {
 786                break;
 787            }
 788        }
 789        offset -= ch.len_utf8();
 790        prev_ch = Some(ch);
 791    }
 792
 793    let trail = trail_offset
 794        .map(|trail_offset| map.clip_point(trail_offset.to_display_point(map), Bias::Left));
 795
 796    (
 797        trail,
 798        map.clip_point(offset.to_display_point(map), Bias::Left),
 799    )
 800}
 801
 802/// Finds the location of a boundary
 803pub fn find_boundary_trail(
 804    map: &DisplaySnapshot,
 805    head: DisplayPoint,
 806    is_boundary: &mut dyn FnMut(char, char) -> bool,
 807) -> (Option<DisplayPoint>, DisplayPoint) {
 808    let mut offset = head.to_offset(map, Bias::Right);
 809    let mut trail_offset = None;
 810
 811    let mut prev_ch = map.buffer_snapshot().reversed_chars_at(offset).next();
 812    let mut forward = map.buffer_snapshot().chars_at(offset).peekable();
 813
 814    // Skip newlines
 815    while let Some(&ch) = forward.peek() {
 816        if ch == '\n' {
 817            prev_ch = forward.next();
 818            offset += ch.len_utf8();
 819            trail_offset = Some(offset);
 820        } else {
 821            break;
 822        }
 823    }
 824
 825    // Find the boundary
 826    let start_offset = offset;
 827    for ch in forward {
 828        if let Some(prev_ch) = prev_ch
 829            && is_boundary(prev_ch, ch)
 830        {
 831            if start_offset == offset {
 832                trail_offset = Some(offset);
 833            } else {
 834                break;
 835            }
 836        }
 837        offset += ch.len_utf8();
 838        prev_ch = Some(ch);
 839    }
 840
 841    let trail = trail_offset.map(|trail_offset| {
 842        let point = trail_offset.to_point(map.buffer_snapshot());
 843        map.clip_point(map.point_to_display_point(point, Bias::Right), Bias::Right)
 844    });
 845
 846    (trail, {
 847        let point = offset.to_point(map.buffer_snapshot());
 848        map.clip_point(map.point_to_display_point(point, Bias::Right), Bias::Right)
 849    })
 850}
 851
 852pub fn find_boundary(
 853    map: &DisplaySnapshot,
 854    from: DisplayPoint,
 855    find_range: FindRange,
 856    is_boundary: &mut dyn FnMut(char, char) -> bool,
 857) -> DisplayPoint {
 858    find_boundary_point(map, from, find_range, is_boundary, false)
 859}
 860
 861pub fn find_boundary_exclusive(
 862    map: &DisplaySnapshot,
 863    from: DisplayPoint,
 864    find_range: FindRange,
 865    is_boundary: &mut dyn FnMut(char, char) -> bool,
 866) -> DisplayPoint {
 867    find_boundary_point(map, from, find_range, is_boundary, true)
 868}
 869
 870/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
 871/// The returned value also contains a range of the start/end of a returned character in
 872/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 873pub fn chars_after(
 874    map: &DisplaySnapshot,
 875    mut offset: MultiBufferOffset,
 876) -> impl Iterator<Item = (char, Range<MultiBufferOffset>)> + '_ {
 877    map.buffer_snapshot().chars_at(offset).map(move |ch| {
 878        let before = offset;
 879        offset += ch.len_utf8();
 880        (ch, before..offset)
 881    })
 882}
 883
 884/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
 885/// The returned value also contains a range of the start/end of a returned character in
 886/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 887pub fn chars_before(
 888    map: &DisplaySnapshot,
 889    mut offset: MultiBufferOffset,
 890) -> impl Iterator<Item = (char, Range<MultiBufferOffset>)> + '_ {
 891    map.buffer_snapshot()
 892        .reversed_chars_at(offset)
 893        .map(move |ch| {
 894            let after = offset;
 895            offset -= ch.len_utf8();
 896            (ch, offset..after)
 897        })
 898}
 899
 900/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
 901/// within a passed range.
 902///
 903/// The line ranges are **always* going to be in bounds of a requested range, which means that
 904/// the first and the last lines might not necessarily represent the
 905/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
 906pub fn split_display_range_by_lines(
 907    map: &DisplaySnapshot,
 908    range: Range<DisplayPoint>,
 909) -> Vec<Range<DisplayPoint>> {
 910    let mut result = Vec::new();
 911
 912    let mut start = range.start;
 913    // Loop over all the covered rows until the one containing the range end
 914    for row in range.start.row().0..range.end.row().0 {
 915        let row_end_column = map.line_len(DisplayRow(row));
 916        let end = map.clip_point(
 917            DisplayPoint::new(DisplayRow(row), row_end_column),
 918            Bias::Left,
 919        );
 920        if start != end {
 921            result.push(start..end);
 922        }
 923        start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
 924    }
 925
 926    // Add the final range from the start of the last end to the original range end.
 927    result.push(start..range.end);
 928
 929    result
 930}
 931
 932#[cfg(test)]
 933mod tests {
 934    use super::*;
 935    use crate::{
 936        Buffer, DisplayMap, DisplayRow, FoldPlaceholder, MultiBuffer,
 937        inlays::Inlay,
 938        test::{editor_test_context::EditorTestContext, marked_display_snapshot},
 939    };
 940    use gpui::{AppContext as _, font, px};
 941    use language::Capability;
 942    use multi_buffer::PathKey;
 943    use project::project_settings::DiagnosticSeverity;
 944    use settings::SettingsStore;
 945    use util::post_inc;
 946
 947    #[gpui::test]
 948    fn test_previous_word_start(cx: &mut gpui::App) {
 949        init_test(cx);
 950
 951        fn assert(marked_text: &str, cx: &mut gpui::App) {
 952            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 953            let actual = previous_word_start(&snapshot, display_points[1]);
 954            let expected = display_points[0];
 955            if actual != expected {
 956                eprintln!(
 957                    "previous_word_start mismatch for '{}': actual={:?}, expected={:?}",
 958                    marked_text, actual, expected
 959                );
 960            }
 961            assert_eq!(actual, expected);
 962        }
 963
 964        assert("\nˇ   ˇlorem", cx);
 965        assert("ˇ\nˇ   lorem", cx);
 966        assert("    ˇloremˇ", cx);
 967        assert("ˇ    ˇlorem", cx);
 968        assert("    ˇlorˇem", cx);
 969        assert("\nlorem\nˇ   ˇipsum", cx);
 970        assert("\n\nˇ\nˇ", cx);
 971        assert("    ˇlorem  ˇipsum", cx);
 972        assert("ˇlorem-ˇipsum", cx);
 973        assert("loremˇ-#$@ˇipsum", cx);
 974        assert("ˇlorem_ˇipsum", cx);
 975        assert(" ˇdefγˇ", cx);
 976        assert(" ˇbcΔˇ", cx);
 977        // Test punctuation skipping behavior
 978        assert("ˇhello.ˇ", cx);
 979        assert("helloˇ...ˇ", cx);
 980        assert("helloˇ.---..ˇtest", cx);
 981        assert("test  ˇ.--ˇtest", cx);
 982        assert("oneˇ,;:!?ˇtwo", cx);
 983    }
 984
 985    #[gpui::test]
 986    fn test_previous_subword_start(cx: &mut gpui::App) {
 987        init_test(cx);
 988
 989        fn assert(marked_text: &str, cx: &mut gpui::App) {
 990            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 991            assert_eq!(
 992                previous_subword_start(&snapshot, display_points[1]),
 993                display_points[0]
 994            );
 995        }
 996
 997        // Subword boundaries are respected
 998        assert("loremˇ_ˇipsum", cx);
 999        assert("lorem_ˇipsumˇ", cx);
1000        assert("ˇloremˇ_ipsum", cx);
1001        assert("lorem_ˇipsumˇ_dolor", cx);
1002        assert("loremˇIpˇsum", cx);
1003        assert("loremˇIpsumˇ", cx);
1004
1005        // Word boundaries are still respected
1006        assert("\nˇ   ˇlorem", cx);
1007        assert("    ˇloremˇ", cx);
1008        assert("    ˇlorˇem", cx);
1009        assert("\nlorem\nˇ   ˇipsum", cx);
1010        assert("\n\nˇ\nˇ", cx);
1011        assert("    ˇlorem  ˇipsum", cx);
1012        assert("loremˇ-ˇipsum", cx);
1013        assert("loremˇ-#$@ˇipsum", cx);
1014        assert(" ˇdefγˇ", cx);
1015        assert(" bcˇΔˇ", cx);
1016        assert(" ˇbcδˇ", cx);
1017        assert(" abˇ——ˇcd", cx);
1018    }
1019
1020    #[gpui::test]
1021    fn test_find_preceding_boundary(cx: &mut gpui::App) {
1022        init_test(cx);
1023
1024        fn assert(
1025            marked_text: &str,
1026            cx: &mut gpui::App,
1027            is_boundary: &mut dyn FnMut(char, char) -> bool,
1028        ) {
1029            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1030            assert_eq!(
1031                find_preceding_boundary_display_point(
1032                    &snapshot,
1033                    display_points[1],
1034                    FindRange::MultiLine,
1035                    is_boundary
1036                ),
1037                display_points[0]
1038            );
1039        }
1040
1041        assert("abcˇdef\ngh\nijˇk", cx, &mut |left, right| {
1042            left == 'c' && right == 'd'
1043        });
1044        assert("abcdef\nˇgh\nijˇk", cx, &mut |left, right| {
1045            left == '\n' && right == 'g'
1046        });
1047        let mut line_count = 0;
1048        assert("abcdef\nˇgh\nijˇk", cx, &mut |left, _| {
1049            if left == '\n' {
1050                line_count += 1;
1051                line_count == 2
1052            } else {
1053                false
1054            }
1055        });
1056    }
1057
1058    #[gpui::test]
1059    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::App) {
1060        init_test(cx);
1061
1062        let input_text = "abcdefghijklmnopqrstuvwxys";
1063        let font = font("Helvetica");
1064        let font_size = px(14.0);
1065        let buffer = MultiBuffer::build_simple(input_text, cx);
1066        let buffer_snapshot = buffer.read(cx).snapshot(cx);
1067
1068        let display_map = cx.new(|cx| {
1069            DisplayMap::new(
1070                buffer,
1071                font,
1072                font_size,
1073                None,
1074                1,
1075                1,
1076                FoldPlaceholder::test(),
1077                DiagnosticSeverity::Warning,
1078                cx,
1079            )
1080        });
1081
1082        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
1083        let mut id = 0;
1084        let inlays = (0..buffer_snapshot.len().0)
1085            .flat_map(|offset| {
1086                let offset = MultiBufferOffset(offset);
1087                [
1088                    Inlay::edit_prediction(
1089                        post_inc(&mut id),
1090                        buffer_snapshot.anchor_before(offset),
1091                        "test",
1092                    ),
1093                    Inlay::edit_prediction(
1094                        post_inc(&mut id),
1095                        buffer_snapshot.anchor_after(offset),
1096                        "test",
1097                    ),
1098                    Inlay::mock_hint(
1099                        post_inc(&mut id),
1100                        buffer_snapshot.anchor_before(offset),
1101                        "test",
1102                    ),
1103                    Inlay::mock_hint(
1104                        post_inc(&mut id),
1105                        buffer_snapshot.anchor_after(offset),
1106                        "test",
1107                    ),
1108                ]
1109            })
1110            .collect();
1111        let snapshot = display_map.update(cx, |map, cx| {
1112            map.splice_inlays(&[], inlays, cx);
1113            map.snapshot(cx)
1114        });
1115
1116        assert_eq!(
1117            find_preceding_boundary_display_point(
1118                &snapshot,
1119                buffer_snapshot.len().to_display_point(&snapshot),
1120                FindRange::MultiLine,
1121                &mut |left, _| left == 'e',
1122            ),
1123            snapshot
1124                .buffer_snapshot()
1125                .offset_to_point(MultiBufferOffset(5))
1126                .to_display_point(&snapshot),
1127            "Should not stop at inlays when looking for boundaries"
1128        );
1129    }
1130
1131    #[gpui::test]
1132    fn test_next_word_end(cx: &mut gpui::App) {
1133        init_test(cx);
1134
1135        fn assert(marked_text: &str, cx: &mut gpui::App) {
1136            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1137            let actual = next_word_end(&snapshot, display_points[0]);
1138            let expected = display_points[1];
1139            if actual != expected {
1140                eprintln!(
1141                    "next_word_end mismatch for '{}': actual={:?}, expected={:?}",
1142                    marked_text, actual, expected
1143                );
1144            }
1145            assert_eq!(actual, expected);
1146        }
1147
1148        assert("\nˇ   loremˇ", cx);
1149        assert("    ˇloremˇ", cx);
1150        assert("    lorˇemˇ", cx);
1151        assert("    loremˇ    ˇ\nipsum\n", cx);
1152        assert("\nˇ\nˇ\n\n", cx);
1153        assert("loremˇ    ipsumˇ   ", cx);
1154        assert("loremˇ-ipsumˇ", cx);
1155        assert("loremˇ#$@-ˇipsum", cx);
1156        assert("loremˇ_ipsumˇ", cx);
1157        assert(" ˇbcΔˇ", cx);
1158        assert(" abˇ——ˇcd", cx);
1159        // Test punctuation skipping behavior
1160        assert("ˇ.helloˇ", cx);
1161        assert("display_pointsˇ[0ˇ]", cx);
1162        assert("ˇ...ˇhello", cx);
1163        assert("helloˇ.---..ˇtest", cx);
1164        assert("testˇ.--ˇ test", cx);
1165        assert("oneˇ,;:!?ˇtwo", cx);
1166    }
1167
1168    #[gpui::test]
1169    fn test_next_subword_end(cx: &mut gpui::App) {
1170        init_test(cx);
1171
1172        fn assert(marked_text: &str, cx: &mut gpui::App) {
1173            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1174            assert_eq!(
1175                next_subword_end(&snapshot, display_points[0]),
1176                display_points[1]
1177            );
1178        }
1179
1180        // Subword boundaries are respected
1181        assert("loremˇ_ˇipsum", cx);
1182        assert("ˇloremˇ_ipsum", cx);
1183        assert("loremˇ_ˇipsum", cx);
1184        assert("lorem_ˇipsumˇ_dolor", cx);
1185        assert("loˇremˇIpsum", cx);
1186        assert("loremˇIpsumˇDolor", cx);
1187
1188        // Word boundaries are still respected
1189        assert("\nˇ   loremˇ", cx);
1190        assert("    ˇloremˇ", cx);
1191        assert("    lorˇemˇ", cx);
1192        assert("    loremˇ    ˇ\nipsum\n", cx);
1193        assert("\nˇ\nˇ\n\n", cx);
1194        assert("loremˇ    ipsumˇ   ", cx);
1195        assert("loremˇ-ˇipsum", cx);
1196        assert("loremˇ#$@-ˇipsum", cx);
1197        assert("loremˇ_ˇipsum", cx);
1198        assert(" ˇbcˇΔ", cx);
1199        assert(" abˇ——ˇcd", cx);
1200    }
1201
1202    #[gpui::test]
1203    fn test_find_boundary(cx: &mut gpui::App) {
1204        init_test(cx);
1205
1206        fn assert(
1207            marked_text: &str,
1208            cx: &mut gpui::App,
1209            is_boundary: &mut dyn FnMut(char, char) -> bool,
1210        ) {
1211            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1212            assert_eq!(
1213                find_boundary(
1214                    &snapshot,
1215                    display_points[0],
1216                    FindRange::MultiLine,
1217                    is_boundary,
1218                ),
1219                display_points[1]
1220            );
1221        }
1222
1223        assert("abcˇdef\ngh\nijˇk", cx, &mut |left, right| {
1224            left == 'j' && right == 'k'
1225        });
1226        assert("abˇcdef\ngh\nˇijk", cx, &mut |left, right| {
1227            left == '\n' && right == 'i'
1228        });
1229        let mut line_count = 0;
1230        assert("abcˇdef\ngh\nˇijk", cx, &mut |left, _| {
1231            if left == '\n' {
1232                line_count += 1;
1233                line_count == 2
1234            } else {
1235                false
1236            }
1237        });
1238    }
1239
1240    #[gpui::test]
1241    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
1242        cx.update(|cx| {
1243            init_test(cx);
1244        });
1245
1246        let mut cx = EditorTestContext::new(cx).await;
1247        let editor = cx.editor.clone();
1248        let window = cx.window;
1249        _ = cx.update_window(window, |_, window, cx| {
1250            let text_layout_details =
1251                editor.update(cx, |editor, cx| editor.text_layout_details(window, cx));
1252
1253            let font = font("Helvetica");
1254
1255            let buffer = cx.new(|cx| Buffer::local("abc\ndefg\na\na\na\nhijkl\nmn", cx));
1256            let multibuffer = cx.new(|cx| {
1257                let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1258                multibuffer.set_excerpts_for_path(
1259                    PathKey::sorted(0),
1260                    buffer.clone(),
1261                    [
1262                        Point::new(0, 0)..Point::new(1, 4),
1263                        Point::new(5, 0)..Point::new(6, 2),
1264                    ],
1265                    0,
1266                    cx,
1267                );
1268                multibuffer
1269            });
1270            let display_map = cx.new(|cx| {
1271                DisplayMap::new(
1272                    multibuffer,
1273                    font,
1274                    px(14.0),
1275                    None,
1276                    0,
1277                    1,
1278                    FoldPlaceholder::test(),
1279                    DiagnosticSeverity::Warning,
1280                    cx,
1281                )
1282            });
1283            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1284
1285            assert_eq!(snapshot.text(), "abc\ndefg\n\nhijkl\nmn");
1286
1287            let col_2_x = snapshot
1288                .x_for_display_point(DisplayPoint::new(DisplayRow(0), 2), &text_layout_details);
1289
1290            // Can't move up into the first excerpt's header
1291            assert_eq!(
1292                up(
1293                    &snapshot,
1294                    DisplayPoint::new(DisplayRow(0), 2),
1295                    SelectionGoal::HorizontalPosition(f64::from(col_2_x)),
1296                    false,
1297                    &text_layout_details
1298                ),
1299                (
1300                    DisplayPoint::new(DisplayRow(0), 0),
1301                    SelectionGoal::HorizontalPosition(f64::from(col_2_x)),
1302                ),
1303            );
1304            assert_eq!(
1305                up(
1306                    &snapshot,
1307                    DisplayPoint::new(DisplayRow(0), 0),
1308                    SelectionGoal::None,
1309                    false,
1310                    &text_layout_details
1311                ),
1312                (
1313                    DisplayPoint::new(DisplayRow(0), 0),
1314                    SelectionGoal::HorizontalPosition(0.0),
1315                ),
1316            );
1317
1318            let col_4_x = snapshot
1319                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 4), &text_layout_details);
1320
1321            // Move up and down within first excerpt
1322            assert_eq!(
1323                up(
1324                    &snapshot,
1325                    DisplayPoint::new(DisplayRow(1), 4),
1326                    SelectionGoal::HorizontalPosition(col_4_x.into()),
1327                    false,
1328                    &text_layout_details
1329                ),
1330                (
1331                    DisplayPoint::new(DisplayRow(0), 3),
1332                    SelectionGoal::HorizontalPosition(col_4_x.into())
1333                ),
1334            );
1335            assert_eq!(
1336                down(
1337                    &snapshot,
1338                    DisplayPoint::new(DisplayRow(0), 3),
1339                    SelectionGoal::HorizontalPosition(col_4_x.into()),
1340                    false,
1341                    &text_layout_details
1342                ),
1343                (
1344                    DisplayPoint::new(DisplayRow(1), 4),
1345                    SelectionGoal::HorizontalPosition(col_4_x.into())
1346                ),
1347            );
1348
1349            let col_5_x = snapshot
1350                .x_for_display_point(DisplayPoint::new(DisplayRow(3), 5), &text_layout_details);
1351
1352            // Move up and down across second excerpt's header
1353            assert_eq!(
1354                up(
1355                    &snapshot,
1356                    DisplayPoint::new(DisplayRow(3), 5),
1357                    SelectionGoal::HorizontalPosition(col_5_x.into()),
1358                    false,
1359                    &text_layout_details
1360                ),
1361                (
1362                    DisplayPoint::new(DisplayRow(1), 4),
1363                    SelectionGoal::HorizontalPosition(col_5_x.into())
1364                ),
1365            );
1366            assert_eq!(
1367                down(
1368                    &snapshot,
1369                    DisplayPoint::new(DisplayRow(1), 4),
1370                    SelectionGoal::HorizontalPosition(col_5_x.into()),
1371                    false,
1372                    &text_layout_details
1373                ),
1374                (
1375                    DisplayPoint::new(DisplayRow(3), 5),
1376                    SelectionGoal::HorizontalPosition(col_5_x.into())
1377                ),
1378            );
1379
1380            let max_point_x = snapshot
1381                .x_for_display_point(DisplayPoint::new(DisplayRow(4), 2), &text_layout_details);
1382
1383            // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1384            assert_eq!(
1385                down(
1386                    &snapshot,
1387                    DisplayPoint::new(DisplayRow(4), 0),
1388                    SelectionGoal::HorizontalPosition(0.0),
1389                    false,
1390                    &text_layout_details
1391                ),
1392                (
1393                    DisplayPoint::new(DisplayRow(4), 2),
1394                    SelectionGoal::HorizontalPosition(0.0)
1395                ),
1396            );
1397            assert_eq!(
1398                down(
1399                    &snapshot,
1400                    DisplayPoint::new(DisplayRow(4), 2),
1401                    SelectionGoal::HorizontalPosition(max_point_x.into()),
1402                    false,
1403                    &text_layout_details
1404                ),
1405                (
1406                    DisplayPoint::new(DisplayRow(4), 2),
1407                    SelectionGoal::HorizontalPosition(max_point_x.into())
1408                ),
1409            );
1410        });
1411    }
1412
1413    #[gpui::test]
1414    fn test_word_movement_over_folds(cx: &mut gpui::App) {
1415        use crate::display_map::Crease;
1416
1417        init_test(cx);
1418
1419        // Simulate a mention: `hello [@file.txt](file:///path) world`
1420        // The fold covers `[@file.txt](file:///path)` and is replaced by "⋯".
1421        // Display text: `hello ⋯ world`
1422        let buffer_text = "hello [@file.txt](file:///path) world";
1423        let buffer = MultiBuffer::build_simple(buffer_text, cx);
1424        let font = font("Helvetica");
1425        let display_map = cx.new(|cx| {
1426            DisplayMap::new(
1427                buffer,
1428                font,
1429                px(14.0),
1430                None,
1431                0,
1432                1,
1433                FoldPlaceholder::test(),
1434                DiagnosticSeverity::Warning,
1435                cx,
1436            )
1437        });
1438        display_map.update(cx, |map, cx| {
1439            // Fold the `[@file.txt](file:///path)` range (bytes 6..31)
1440            map.fold(
1441                vec![Crease::simple(
1442                    Point::new(0, 6)..Point::new(0, 31),
1443                    FoldPlaceholder::test(),
1444                )],
1445                cx,
1446            );
1447        });
1448        let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1449
1450        // "hello " (6 bytes) + "⋯" (3 bytes) + " world" (6 bytes) = "hello ⋯ world"
1451        assert_eq!(snapshot.text(), "hello ⋯ world");
1452
1453        // Ctrl+Right from before fold ("hello |⋯ world") should skip past the fold.
1454        // Cursor at column 6 = start of fold.
1455        let before_fold = DisplayPoint::new(DisplayRow(0), 6);
1456        let after_fold = next_word_end(&snapshot, before_fold);
1457        // Should land past the fold, not get stuck at fold start.
1458        assert!(
1459            after_fold > before_fold,
1460            "next_word_end should move past the fold: got {:?}, started at {:?}",
1461            after_fold,
1462            before_fold
1463        );
1464
1465        // Ctrl+Right from "hello" should jump past "hello" to the fold or past it.
1466        let at_start = DisplayPoint::new(DisplayRow(0), 0);
1467        let after_hello = next_word_end(&snapshot, at_start);
1468        assert_eq!(
1469            after_hello,
1470            DisplayPoint::new(DisplayRow(0), 5),
1471            "next_word_end from start should land at end of 'hello'"
1472        );
1473
1474        // Ctrl+Left from after fold should move to before the fold.
1475        // "⋯" ends at column 9. " world" starts at 9. Column 15 = end of "world".
1476        let after_world = DisplayPoint::new(DisplayRow(0), 15);
1477        let before_world = previous_word_start(&snapshot, after_world);
1478        assert_eq!(
1479            before_world,
1480            DisplayPoint::new(DisplayRow(0), 10),
1481            "previous_word_start from end should land at start of 'world'"
1482        );
1483
1484        // Ctrl+Left from start of "world" should land before fold.
1485        let start_of_world = DisplayPoint::new(DisplayRow(0), 10);
1486        let landed = previous_word_start(&snapshot, start_of_world);
1487        // The fold acts as a word, so we should land at the fold start (column 6).
1488        assert_eq!(
1489            landed,
1490            DisplayPoint::new(DisplayRow(0), 6),
1491            "previous_word_start from 'world' should land at fold start"
1492        );
1493
1494        // End key from start should go to end of line (column 15), not fold start.
1495        let end_pos = line_end(&snapshot, at_start, false);
1496        assert_eq!(
1497            end_pos,
1498            DisplayPoint::new(DisplayRow(0), 15),
1499            "line_end should go to actual end of line, not fold start"
1500        );
1501    }
1502
1503    fn init_test(cx: &mut gpui::App) {
1504        let settings_store = SettingsStore::test(cx);
1505        cx.set_global(settings_store);
1506        theme_settings::init(theme::LoadThemes::JustBase, cx);
1507        crate::init(cx);
1508    }
1509}