movement.rs

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