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::{CharKind, 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, doing nothing
  62// if that point is at the end of the 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 {
 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    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 268        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(right))
 269            || left == '\n'
 270    })
 271}
 272
 273/// Returns a position of the previous word boundary, where a word character is defined as either
 274/// uppercase letter, lowercase letter, '_' character, language-specific word character (like '-' in CSS) or newline.
 275pub fn previous_word_start_or_newline(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 276    let raw_point = point.to_point(map);
 277    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 278
 279    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 280        (classifier.kind(left) != classifier.kind(right) && !right.is_whitespace())
 281            || left == '\n'
 282            || right == '\n'
 283    })
 284}
 285
 286/// Returns a position of the previous subword boundary, where a subword is defined as a run of
 287/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 288/// lowerspace characters and uppercase characters.
 289pub fn previous_subword_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 290    let raw_point = point.to_point(map);
 291    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 292
 293    find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
 294        let is_word_start =
 295            classifier.kind(left) != classifier.kind(right) && !right.is_whitespace();
 296        let is_subword_start = classifier.is_word('-') && left == '-' && right != '-'
 297            || left == '_' && right != '_'
 298            || left.is_lowercase() && right.is_uppercase();
 299        is_word_start || is_subword_start || left == '\n'
 300    })
 301}
 302
 303/// Returns a position of the next word boundary, where a word character is defined as either
 304/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
 305pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 306    let raw_point = point.to_point(map);
 307    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 308
 309    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 310        (classifier.kind(left) != classifier.kind(right) && !classifier.is_whitespace(left))
 311            || right == '\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, language-specific word character (like '-' in CSS) or newline.
 317pub fn next_word_end_or_newline(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
 321    let mut on_starting_row = true;
 322    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 323        if left == '\n' {
 324            on_starting_row = false;
 325        }
 326        (classifier.kind(left) != classifier.kind(right)
 327            && ((on_starting_row && !left.is_whitespace())
 328                || (!on_starting_row && !right.is_whitespace())))
 329            || right == '\n'
 330    })
 331}
 332
 333/// Returns a position of the next subword boundary, where a subword is defined as a run of
 334/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
 335/// lowerspace characters and uppercase characters.
 336pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
 337    let raw_point = point.to_point(map);
 338    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 339
 340    find_boundary(map, point, FindRange::MultiLine, |left, right| {
 341        let is_word_end =
 342            (classifier.kind(left) != classifier.kind(right)) && !classifier.is_whitespace(left);
 343        let is_subword_end = classifier.is_word('-') && left != '-' && right == '-'
 344            || left != '_' && right == '_'
 345            || left.is_lowercase() && right.is_uppercase();
 346        is_word_end || is_subword_end || right == '\n'
 347    })
 348}
 349
 350/// Returns a position of the start of the current paragraph, where a paragraph
 351/// is defined as a run of non-blank lines.
 352pub fn start_of_paragraph(
 353    map: &DisplaySnapshot,
 354    display_point: DisplayPoint,
 355    mut count: usize,
 356) -> DisplayPoint {
 357    let point = display_point.to_point(map);
 358    if point.row == 0 {
 359        return DisplayPoint::zero();
 360    }
 361
 362    let mut found_non_blank_line = false;
 363    for row in (0..point.row + 1).rev() {
 364        let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
 365        if found_non_blank_line && blank {
 366            if count <= 1 {
 367                return Point::new(row, 0).to_display_point(map);
 368            }
 369            count -= 1;
 370            found_non_blank_line = false;
 371        }
 372
 373        found_non_blank_line |= !blank;
 374    }
 375
 376    DisplayPoint::zero()
 377}
 378
 379/// Returns a position of the end of the current paragraph, where a paragraph
 380/// is defined as a run of non-blank lines.
 381pub fn end_of_paragraph(
 382    map: &DisplaySnapshot,
 383    display_point: DisplayPoint,
 384    mut count: usize,
 385) -> DisplayPoint {
 386    let point = display_point.to_point(map);
 387    if point.row == map.buffer_snapshot.max_row().0 {
 388        return map.max_point();
 389    }
 390
 391    let mut found_non_blank_line = false;
 392    for row in point.row..=map.buffer_snapshot.max_row().0 {
 393        let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
 394        if found_non_blank_line && blank {
 395            if count <= 1 {
 396                return Point::new(row, 0).to_display_point(map);
 397            }
 398            count -= 1;
 399            found_non_blank_line = false;
 400        }
 401
 402        found_non_blank_line |= !blank;
 403    }
 404
 405    map.max_point()
 406}
 407
 408pub fn start_of_excerpt(
 409    map: &DisplaySnapshot,
 410    display_point: DisplayPoint,
 411    direction: Direction,
 412) -> DisplayPoint {
 413    let point = map.display_point_to_point(display_point, Bias::Left);
 414    let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point..point) else {
 415        return display_point;
 416    };
 417    match direction {
 418        Direction::Prev => {
 419            let mut start = excerpt.start_anchor().to_display_point(&map);
 420            if start >= display_point && start.row() > DisplayRow(0) {
 421                let Some(excerpt) = map.buffer_snapshot.excerpt_before(excerpt.id()) else {
 422                    return display_point;
 423                };
 424                start = excerpt.start_anchor().to_display_point(&map);
 425            }
 426            start
 427        }
 428        Direction::Next => {
 429            let mut end = excerpt.end_anchor().to_display_point(&map);
 430            *end.row_mut() += 1;
 431            map.clip_point(end, Bias::Right)
 432        }
 433    }
 434}
 435
 436pub fn end_of_excerpt(
 437    map: &DisplaySnapshot,
 438    display_point: DisplayPoint,
 439    direction: Direction,
 440) -> DisplayPoint {
 441    let point = map.display_point_to_point(display_point, Bias::Left);
 442    let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point..point) else {
 443        return display_point;
 444    };
 445    match direction {
 446        Direction::Prev => {
 447            let mut start = excerpt.start_anchor().to_display_point(&map);
 448            if start.row() > DisplayRow(0) {
 449                *start.row_mut() -= 1;
 450            }
 451            start = map.clip_point(start, Bias::Left);
 452            *start.column_mut() = 0;
 453            start
 454        }
 455        Direction::Next => {
 456            let mut end = excerpt.end_anchor().to_display_point(&map);
 457            *end.column_mut() = 0;
 458            if end <= display_point {
 459                *end.row_mut() += 1;
 460                let point_end = map.display_point_to_point(end, Bias::Right);
 461                let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point_end..point_end)
 462                else {
 463                    return display_point;
 464                };
 465                end = excerpt.end_anchor().to_display_point(&map);
 466                *end.column_mut() = 0;
 467            }
 468            end
 469        }
 470    }
 471}
 472
 473/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 474/// indicated by the given predicate returning true.
 475/// The predicate is called with the character to the left and right of the candidate boundary location.
 476/// 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.
 477pub fn find_preceding_boundary_point(
 478    buffer_snapshot: &MultiBufferSnapshot,
 479    from: Point,
 480    find_range: FindRange,
 481    mut is_boundary: impl FnMut(char, char) -> bool,
 482) -> Point {
 483    let mut prev_ch = None;
 484    let mut offset = from.to_offset(buffer_snapshot);
 485
 486    for ch in buffer_snapshot.reversed_chars_at(offset) {
 487        if find_range == FindRange::SingleLine && ch == '\n' {
 488            break;
 489        }
 490        if let Some(prev_ch) = prev_ch {
 491            if is_boundary(ch, prev_ch) {
 492                break;
 493            }
 494        }
 495
 496        offset -= ch.len_utf8();
 497        prev_ch = Some(ch);
 498    }
 499
 500    offset.to_point(buffer_snapshot)
 501}
 502
 503/// Scans for a boundary preceding the given start point `from` until a boundary is found,
 504/// indicated by the given predicate returning true.
 505/// The predicate is called with the character to the left and right of the candidate boundary location.
 506/// 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.
 507pub fn find_preceding_boundary_display_point(
 508    map: &DisplaySnapshot,
 509    from: DisplayPoint,
 510    find_range: FindRange,
 511    is_boundary: impl FnMut(char, char) -> bool,
 512) -> DisplayPoint {
 513    let result = find_preceding_boundary_point(
 514        &map.buffer_snapshot,
 515        from.to_point(map),
 516        find_range,
 517        is_boundary,
 518    );
 519    map.clip_point(result.to_display_point(map), Bias::Left)
 520}
 521
 522/// Scans for a boundary following the given start point until a boundary is found, indicated by the
 523/// given predicate returning true. The predicate is called with the character to the left and right
 524/// of the candidate boundary location, and will be called with `\n` characters indicating the start
 525/// or end of a line. The function supports optionally returning the point just before the boundary
 526/// is found via return_point_before_boundary.
 527pub fn find_boundary_point(
 528    map: &DisplaySnapshot,
 529    from: DisplayPoint,
 530    find_range: FindRange,
 531    mut is_boundary: impl FnMut(char, char) -> bool,
 532    return_point_before_boundary: bool,
 533) -> DisplayPoint {
 534    let mut offset = from.to_offset(map, Bias::Right);
 535    let mut prev_offset = offset;
 536    let mut prev_ch = None;
 537
 538    for ch in map.buffer_snapshot.chars_at(offset) {
 539        if find_range == FindRange::SingleLine && ch == '\n' {
 540            break;
 541        }
 542        if let Some(prev_ch) = prev_ch {
 543            if is_boundary(prev_ch, ch) {
 544                if return_point_before_boundary {
 545                    return map.clip_point(prev_offset.to_display_point(map), Bias::Right);
 546                } else {
 547                    break;
 548                }
 549            }
 550        }
 551        prev_offset = offset;
 552        offset += ch.len_utf8();
 553        prev_ch = Some(ch);
 554    }
 555    map.clip_point(offset.to_display_point(map), Bias::Right)
 556}
 557
 558pub fn find_preceding_boundary_trail(
 559    map: &DisplaySnapshot,
 560    head: DisplayPoint,
 561    mut is_boundary: impl FnMut(char, char) -> bool,
 562) -> (Option<DisplayPoint>, DisplayPoint) {
 563    let mut offset = head.to_offset(map, Bias::Left);
 564    let mut trail_offset = None;
 565
 566    let mut prev_ch = map.buffer_snapshot.chars_at(offset).next();
 567    let mut forward = map.buffer_snapshot.reversed_chars_at(offset).peekable();
 568
 569    // Skip newlines
 570    while let Some(&ch) = forward.peek() {
 571        if ch == '\n' {
 572            prev_ch = forward.next();
 573            offset -= ch.len_utf8();
 574            trail_offset = Some(offset);
 575        } else {
 576            break;
 577        }
 578    }
 579
 580    // Find the boundary
 581    let start_offset = offset;
 582    for ch in forward {
 583        if let Some(prev_ch) = prev_ch {
 584            if is_boundary(prev_ch, ch) {
 585                if start_offset == offset {
 586                    trail_offset = Some(offset);
 587                } else {
 588                    break;
 589                }
 590            }
 591        }
 592        offset -= ch.len_utf8();
 593        prev_ch = Some(ch);
 594    }
 595
 596    let trail = trail_offset
 597        .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Left));
 598
 599    (
 600        trail,
 601        map.clip_point(offset.to_display_point(map), Bias::Left),
 602    )
 603}
 604
 605/// Finds the location of a boundary
 606pub fn find_boundary_trail(
 607    map: &DisplaySnapshot,
 608    head: DisplayPoint,
 609    mut is_boundary: impl FnMut(char, char) -> bool,
 610) -> (Option<DisplayPoint>, DisplayPoint) {
 611    let mut offset = head.to_offset(map, Bias::Right);
 612    let mut trail_offset = None;
 613
 614    let mut prev_ch = map.buffer_snapshot.reversed_chars_at(offset).next();
 615    let mut forward = map.buffer_snapshot.chars_at(offset).peekable();
 616
 617    // Skip newlines
 618    while let Some(&ch) = forward.peek() {
 619        if ch == '\n' {
 620            prev_ch = forward.next();
 621            offset += ch.len_utf8();
 622            trail_offset = Some(offset);
 623        } else {
 624            break;
 625        }
 626    }
 627
 628    // Find the boundary
 629    let start_offset = offset;
 630    for ch in forward {
 631        if let Some(prev_ch) = prev_ch {
 632            if is_boundary(prev_ch, ch) {
 633                if start_offset == offset {
 634                    trail_offset = Some(offset);
 635                } else {
 636                    break;
 637                }
 638            }
 639        }
 640        offset += ch.len_utf8();
 641        prev_ch = Some(ch);
 642    }
 643
 644    let trail = trail_offset
 645        .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Right));
 646
 647    (
 648        trail,
 649        map.clip_point(offset.to_display_point(map), Bias::Right),
 650    )
 651}
 652
 653pub fn find_boundary(
 654    map: &DisplaySnapshot,
 655    from: DisplayPoint,
 656    find_range: FindRange,
 657    is_boundary: impl FnMut(char, char) -> bool,
 658) -> DisplayPoint {
 659    find_boundary_point(map, from, find_range, is_boundary, false)
 660}
 661
 662pub fn find_boundary_exclusive(
 663    map: &DisplaySnapshot,
 664    from: DisplayPoint,
 665    find_range: FindRange,
 666    is_boundary: impl FnMut(char, char) -> bool,
 667) -> DisplayPoint {
 668    find_boundary_point(map, from, find_range, is_boundary, true)
 669}
 670
 671/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
 672/// The returned value also contains a range of the start/end of a returned character in
 673/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 674pub fn chars_after(
 675    map: &DisplaySnapshot,
 676    mut offset: usize,
 677) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
 678    map.buffer_snapshot.chars_at(offset).map(move |ch| {
 679        let before = offset;
 680        offset += ch.len_utf8();
 681        (ch, before..offset)
 682    })
 683}
 684
 685/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
 686/// The returned value also contains a range of the start/end of a returned character in
 687/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
 688pub fn chars_before(
 689    map: &DisplaySnapshot,
 690    mut offset: usize,
 691) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
 692    map.buffer_snapshot
 693        .reversed_chars_at(offset)
 694        .map(move |ch| {
 695            let after = offset;
 696            offset -= ch.len_utf8();
 697            (ch, offset..after)
 698        })
 699}
 700
 701pub(crate) fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
 702    let raw_point = point.to_point(map);
 703    let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
 704    let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
 705    let text = &map.buffer_snapshot;
 706    let next_char_kind = text.chars_at(ix).next().map(|c| classifier.kind(c));
 707    let prev_char_kind = text
 708        .reversed_chars_at(ix)
 709        .next()
 710        .map(|c| classifier.kind(c));
 711    prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
 712}
 713
 714pub(crate) fn surrounding_word(
 715    map: &DisplaySnapshot,
 716    position: DisplayPoint,
 717) -> Range<DisplayPoint> {
 718    let position = map
 719        .clip_point(position, Bias::Left)
 720        .to_offset(map, Bias::Left);
 721    let (range, _) = map.buffer_snapshot.surrounding_word(position, false);
 722    let start = range
 723        .start
 724        .to_point(&map.buffer_snapshot)
 725        .to_display_point(map);
 726    let end = range
 727        .end
 728        .to_point(&map.buffer_snapshot)
 729        .to_display_point(map);
 730    start..end
 731}
 732
 733/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
 734/// within a passed range.
 735///
 736/// The line ranges are **always* going to be in bounds of a requested range, which means that
 737/// the first and the last lines might not necessarily represent the
 738/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
 739pub fn split_display_range_by_lines(
 740    map: &DisplaySnapshot,
 741    range: Range<DisplayPoint>,
 742) -> Vec<Range<DisplayPoint>> {
 743    let mut result = Vec::new();
 744
 745    let mut start = range.start;
 746    // Loop over all the covered rows until the one containing the range end
 747    for row in range.start.row().0..range.end.row().0 {
 748        let row_end_column = map.line_len(DisplayRow(row));
 749        let end = map.clip_point(
 750            DisplayPoint::new(DisplayRow(row), row_end_column),
 751            Bias::Left,
 752        );
 753        if start != end {
 754            result.push(start..end);
 755        }
 756        start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
 757    }
 758
 759    // Add the final range from the start of the last end to the original range end.
 760    result.push(start..range.end);
 761
 762    result
 763}
 764
 765#[cfg(test)]
 766mod tests {
 767    use super::*;
 768    use crate::{
 769        Buffer, DisplayMap, DisplayRow, ExcerptRange, FoldPlaceholder, InlayId, MultiBuffer,
 770        display_map::Inlay,
 771        test::{editor_test_context::EditorTestContext, marked_display_snapshot},
 772    };
 773    use gpui::{AppContext as _, font, px};
 774    use language::Capability;
 775    use project::{Project, project_settings::DiagnosticSeverity};
 776    use settings::SettingsStore;
 777    use util::post_inc;
 778
 779    #[gpui::test]
 780    fn test_previous_word_start(cx: &mut gpui::App) {
 781        init_test(cx);
 782
 783        fn assert(marked_text: &str, cx: &mut gpui::App) {
 784            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 785            assert_eq!(
 786                previous_word_start(&snapshot, display_points[1]),
 787                display_points[0]
 788            );
 789        }
 790
 791        assert("\nˇ   ˇlorem", cx);
 792        assert("ˇ\nˇ   lorem", cx);
 793        assert("    ˇloremˇ", cx);
 794        assert("ˇ    ˇlorem", cx);
 795        assert("    ˇlorˇem", cx);
 796        assert("\nlorem\nˇ   ˇipsum", cx);
 797        assert("\n\nˇ\nˇ", cx);
 798        assert("    ˇlorem  ˇipsum", cx);
 799        assert("loremˇ-ˇipsum", cx);
 800        assert("loremˇ-#$@ˇipsum", cx);
 801        assert("ˇlorem_ˇipsum", cx);
 802        assert(" ˇdefγˇ", cx);
 803        assert(" ˇbcΔˇ", cx);
 804        assert(" abˇ——ˇcd", cx);
 805    }
 806
 807    #[gpui::test]
 808    fn test_previous_subword_start(cx: &mut gpui::App) {
 809        init_test(cx);
 810
 811        fn assert(marked_text: &str, cx: &mut gpui::App) {
 812            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 813            assert_eq!(
 814                previous_subword_start(&snapshot, display_points[1]),
 815                display_points[0]
 816            );
 817        }
 818
 819        // Subword boundaries are respected
 820        assert("lorem_ˇipˇsum", cx);
 821        assert("lorem_ˇipsumˇ", cx);
 822        assert("ˇlorem_ˇipsum", cx);
 823        assert("lorem_ˇipsum_ˇdolor", cx);
 824        assert("loremˇIpˇsum", cx);
 825        assert("loremˇIpsumˇ", cx);
 826
 827        // Word boundaries are still respected
 828        assert("\nˇ   ˇlorem", cx);
 829        assert("    ˇloremˇ", cx);
 830        assert("    ˇlorˇem", cx);
 831        assert("\nlorem\nˇ   ˇipsum", cx);
 832        assert("\n\nˇ\nˇ", cx);
 833        assert("    ˇlorem  ˇipsum", cx);
 834        assert("loremˇ-ˇipsum", cx);
 835        assert("loremˇ-#$@ˇipsum", cx);
 836        assert(" ˇdefγˇ", cx);
 837        assert(" bcˇΔˇ", cx);
 838        assert(" ˇbcδˇ", cx);
 839        assert(" abˇ——ˇcd", cx);
 840    }
 841
 842    #[gpui::test]
 843    fn test_find_preceding_boundary(cx: &mut gpui::App) {
 844        init_test(cx);
 845
 846        fn assert(
 847            marked_text: &str,
 848            cx: &mut gpui::App,
 849            is_boundary: impl FnMut(char, char) -> bool,
 850        ) {
 851            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 852            assert_eq!(
 853                find_preceding_boundary_display_point(
 854                    &snapshot,
 855                    display_points[1],
 856                    FindRange::MultiLine,
 857                    is_boundary
 858                ),
 859                display_points[0]
 860            );
 861        }
 862
 863        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
 864            left == 'c' && right == 'd'
 865        });
 866        assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
 867            left == '\n' && right == 'g'
 868        });
 869        let mut line_count = 0;
 870        assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
 871            if left == '\n' {
 872                line_count += 1;
 873                line_count == 2
 874            } else {
 875                false
 876            }
 877        });
 878    }
 879
 880    #[gpui::test]
 881    fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::App) {
 882        init_test(cx);
 883
 884        let input_text = "abcdefghijklmnopqrstuvwxys";
 885        let font = font("Helvetica");
 886        let font_size = px(14.0);
 887        let buffer = MultiBuffer::build_simple(input_text, cx);
 888        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 889
 890        let display_map = cx.new(|cx| {
 891            DisplayMap::new(
 892                buffer,
 893                font,
 894                font_size,
 895                None,
 896                1,
 897                1,
 898                FoldPlaceholder::test(),
 899                DiagnosticSeverity::Warning,
 900                cx,
 901            )
 902        });
 903
 904        // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
 905        let mut id = 0;
 906        let inlays = (0..buffer_snapshot.len())
 907            .flat_map(|offset| {
 908                [
 909                    Inlay {
 910                        id: InlayId::InlineCompletion(post_inc(&mut id)),
 911                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
 912                        text: "test".into(),
 913                    },
 914                    Inlay {
 915                        id: InlayId::InlineCompletion(post_inc(&mut id)),
 916                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
 917                        text: "test".into(),
 918                    },
 919                    Inlay {
 920                        id: InlayId::Hint(post_inc(&mut id)),
 921                        position: buffer_snapshot.anchor_at(offset, Bias::Left),
 922                        text: "test".into(),
 923                    },
 924                    Inlay {
 925                        id: InlayId::Hint(post_inc(&mut id)),
 926                        position: buffer_snapshot.anchor_at(offset, Bias::Right),
 927                        text: "test".into(),
 928                    },
 929                ]
 930            })
 931            .collect();
 932        let snapshot = display_map.update(cx, |map, cx| {
 933            map.splice_inlays(&[], inlays, cx);
 934            map.snapshot(cx)
 935        });
 936
 937        assert_eq!(
 938            find_preceding_boundary_display_point(
 939                &snapshot,
 940                buffer_snapshot.len().to_display_point(&snapshot),
 941                FindRange::MultiLine,
 942                |left, _| left == 'e',
 943            ),
 944            snapshot
 945                .buffer_snapshot
 946                .offset_to_point(5)
 947                .to_display_point(&snapshot),
 948            "Should not stop at inlays when looking for boundaries"
 949        );
 950    }
 951
 952    #[gpui::test]
 953    fn test_next_word_end(cx: &mut gpui::App) {
 954        init_test(cx);
 955
 956        fn assert(marked_text: &str, cx: &mut gpui::App) {
 957            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 958            assert_eq!(
 959                next_word_end(&snapshot, display_points[0]),
 960                display_points[1]
 961            );
 962        }
 963
 964        assert("\nˇ   loremˇ", cx);
 965        assert("    ˇloremˇ", cx);
 966        assert("    lorˇemˇ", cx);
 967        assert("    loremˇ    ˇ\nipsum\n", cx);
 968        assert("\nˇ\nˇ\n\n", cx);
 969        assert("loremˇ    ipsumˇ   ", cx);
 970        assert("loremˇ-ˇipsum", cx);
 971        assert("loremˇ#$@-ˇipsum", cx);
 972        assert("loremˇ_ipsumˇ", cx);
 973        assert(" ˇbcΔˇ", cx);
 974        assert(" abˇ——ˇcd", cx);
 975    }
 976
 977    #[gpui::test]
 978    fn test_next_subword_end(cx: &mut gpui::App) {
 979        init_test(cx);
 980
 981        fn assert(marked_text: &str, cx: &mut gpui::App) {
 982            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
 983            assert_eq!(
 984                next_subword_end(&snapshot, display_points[0]),
 985                display_points[1]
 986            );
 987        }
 988
 989        // Subword boundaries are respected
 990        assert("loˇremˇ_ipsum", cx);
 991        assert("ˇloremˇ_ipsum", cx);
 992        assert("loremˇ_ipsumˇ", cx);
 993        assert("loremˇ_ipsumˇ_dolor", cx);
 994        assert("loˇremˇIpsum", cx);
 995        assert("loremˇIpsumˇDolor", cx);
 996
 997        // Word boundaries are still respected
 998        assert("\nˇ   loremˇ", cx);
 999        assert("    ˇloremˇ", cx);
1000        assert("    lorˇemˇ", cx);
1001        assert("    loremˇ    ˇ\nipsum\n", cx);
1002        assert("\nˇ\nˇ\n\n", cx);
1003        assert("loremˇ    ipsumˇ   ", cx);
1004        assert("loremˇ-ˇipsum", cx);
1005        assert("loremˇ#$@-ˇipsum", cx);
1006        assert("loremˇ_ipsumˇ", cx);
1007        assert(" ˇbcˇΔ", cx);
1008        assert(" abˇ——ˇcd", cx);
1009    }
1010
1011    #[gpui::test]
1012    fn test_find_boundary(cx: &mut gpui::App) {
1013        init_test(cx);
1014
1015        fn assert(
1016            marked_text: &str,
1017            cx: &mut gpui::App,
1018            is_boundary: impl FnMut(char, char) -> bool,
1019        ) {
1020            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1021            assert_eq!(
1022                find_boundary(
1023                    &snapshot,
1024                    display_points[0],
1025                    FindRange::MultiLine,
1026                    is_boundary,
1027                ),
1028                display_points[1]
1029            );
1030        }
1031
1032        assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
1033            left == 'j' && right == 'k'
1034        });
1035        assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
1036            left == '\n' && right == 'i'
1037        });
1038        let mut line_count = 0;
1039        assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
1040            if left == '\n' {
1041                line_count += 1;
1042                line_count == 2
1043            } else {
1044                false
1045            }
1046        });
1047    }
1048
1049    #[gpui::test]
1050    fn test_surrounding_word(cx: &mut gpui::App) {
1051        init_test(cx);
1052
1053        fn assert(marked_text: &str, cx: &mut gpui::App) {
1054            let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1055            assert_eq!(
1056                surrounding_word(&snapshot, display_points[1]),
1057                display_points[0]..display_points[2],
1058                "{}",
1059                marked_text
1060            );
1061        }
1062
1063        assert("ˇˇloremˇ  ipsum", cx);
1064        assert("ˇloˇremˇ  ipsum", cx);
1065        assert("ˇloremˇˇ  ipsum", cx);
1066        assert("loremˇ ˇ  ˇipsum", cx);
1067        assert("lorem\nˇˇˇ\nipsum", cx);
1068        assert("lorem\nˇˇipsumˇ", cx);
1069        assert("loremˇ,ˇˇ ipsum", cx);
1070        assert("ˇloremˇˇ, ipsum", cx);
1071    }
1072
1073    #[gpui::test]
1074    async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
1075        cx.update(|cx| {
1076            init_test(cx);
1077        });
1078
1079        let mut cx = EditorTestContext::new(cx).await;
1080        let editor = cx.editor.clone();
1081        let window = cx.window;
1082        _ = cx.update_window(window, |_, window, cx| {
1083            let text_layout_details = editor.read(cx).text_layout_details(window);
1084
1085            let font = font("Helvetica");
1086
1087            let buffer = cx.new(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
1088            let multibuffer = cx.new(|cx| {
1089                let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1090                multibuffer.push_excerpts(
1091                    buffer.clone(),
1092                    [
1093                        ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
1094                        ExcerptRange::new(Point::new(2, 0)..Point::new(3, 2)),
1095                    ],
1096                    cx,
1097                );
1098                multibuffer
1099            });
1100            let display_map = cx.new(|cx| {
1101                DisplayMap::new(
1102                    multibuffer,
1103                    font,
1104                    px(14.0),
1105                    None,
1106                    0,
1107                    1,
1108                    FoldPlaceholder::test(),
1109                    DiagnosticSeverity::Warning,
1110                    cx,
1111                )
1112            });
1113            let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1114
1115            assert_eq!(snapshot.text(), "abc\ndefg\n\nhijkl\nmn");
1116
1117            let col_2_x = snapshot
1118                .x_for_display_point(DisplayPoint::new(DisplayRow(0), 2), &text_layout_details);
1119
1120            // Can't move up into the first excerpt's header
1121            assert_eq!(
1122                up(
1123                    &snapshot,
1124                    DisplayPoint::new(DisplayRow(0), 2),
1125                    SelectionGoal::HorizontalPosition(col_2_x.0),
1126                    false,
1127                    &text_layout_details
1128                ),
1129                (
1130                    DisplayPoint::new(DisplayRow(0), 0),
1131                    SelectionGoal::HorizontalPosition(col_2_x.0),
1132                ),
1133            );
1134            assert_eq!(
1135                up(
1136                    &snapshot,
1137                    DisplayPoint::new(DisplayRow(0), 0),
1138                    SelectionGoal::None,
1139                    false,
1140                    &text_layout_details
1141                ),
1142                (
1143                    DisplayPoint::new(DisplayRow(0), 0),
1144                    SelectionGoal::HorizontalPosition(0.0),
1145                ),
1146            );
1147
1148            let col_4_x = snapshot
1149                .x_for_display_point(DisplayPoint::new(DisplayRow(1), 4), &text_layout_details);
1150
1151            // Move up and down within first excerpt
1152            assert_eq!(
1153                up(
1154                    &snapshot,
1155                    DisplayPoint::new(DisplayRow(1), 4),
1156                    SelectionGoal::HorizontalPosition(col_4_x.0),
1157                    false,
1158                    &text_layout_details
1159                ),
1160                (
1161                    DisplayPoint::new(DisplayRow(0), 3),
1162                    SelectionGoal::HorizontalPosition(col_4_x.0)
1163                ),
1164            );
1165            assert_eq!(
1166                down(
1167                    &snapshot,
1168                    DisplayPoint::new(DisplayRow(0), 3),
1169                    SelectionGoal::HorizontalPosition(col_4_x.0),
1170                    false,
1171                    &text_layout_details
1172                ),
1173                (
1174                    DisplayPoint::new(DisplayRow(1), 4),
1175                    SelectionGoal::HorizontalPosition(col_4_x.0)
1176                ),
1177            );
1178
1179            let col_5_x = snapshot
1180                .x_for_display_point(DisplayPoint::new(DisplayRow(3), 5), &text_layout_details);
1181
1182            // Move up and down across second excerpt's header
1183            assert_eq!(
1184                up(
1185                    &snapshot,
1186                    DisplayPoint::new(DisplayRow(3), 5),
1187                    SelectionGoal::HorizontalPosition(col_5_x.0),
1188                    false,
1189                    &text_layout_details
1190                ),
1191                (
1192                    DisplayPoint::new(DisplayRow(1), 4),
1193                    SelectionGoal::HorizontalPosition(col_5_x.0)
1194                ),
1195            );
1196            assert_eq!(
1197                down(
1198                    &snapshot,
1199                    DisplayPoint::new(DisplayRow(1), 4),
1200                    SelectionGoal::HorizontalPosition(col_5_x.0),
1201                    false,
1202                    &text_layout_details
1203                ),
1204                (
1205                    DisplayPoint::new(DisplayRow(3), 5),
1206                    SelectionGoal::HorizontalPosition(col_5_x.0)
1207                ),
1208            );
1209
1210            let max_point_x = snapshot
1211                .x_for_display_point(DisplayPoint::new(DisplayRow(4), 2), &text_layout_details);
1212
1213            // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1214            assert_eq!(
1215                down(
1216                    &snapshot,
1217                    DisplayPoint::new(DisplayRow(4), 0),
1218                    SelectionGoal::HorizontalPosition(0.0),
1219                    false,
1220                    &text_layout_details
1221                ),
1222                (
1223                    DisplayPoint::new(DisplayRow(4), 2),
1224                    SelectionGoal::HorizontalPosition(0.0)
1225                ),
1226            );
1227            assert_eq!(
1228                down(
1229                    &snapshot,
1230                    DisplayPoint::new(DisplayRow(4), 2),
1231                    SelectionGoal::HorizontalPosition(max_point_x.0),
1232                    false,
1233                    &text_layout_details
1234                ),
1235                (
1236                    DisplayPoint::new(DisplayRow(4), 2),
1237                    SelectionGoal::HorizontalPosition(max_point_x.0)
1238                ),
1239            );
1240        });
1241    }
1242
1243    fn init_test(cx: &mut gpui::App) {
1244        let settings_store = SettingsStore::test(cx);
1245        cx.set_global(settings_store);
1246        workspace::init_settings(cx);
1247        theme::init(theme::LoadThemes::JustBase, cx);
1248        language::init(cx);
1249        crate::init(cx);
1250        Project::init_settings(cx);
1251    }
1252}