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;
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 cx,
900 )
901 });
902
903 // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
904 let mut id = 0;
905 let inlays = (0..buffer_snapshot.len())
906 .flat_map(|offset| {
907 [
908 Inlay {
909 id: InlayId::InlineCompletion(post_inc(&mut id)),
910 position: buffer_snapshot.anchor_at(offset, Bias::Left),
911 text: "test".into(),
912 },
913 Inlay {
914 id: InlayId::InlineCompletion(post_inc(&mut id)),
915 position: buffer_snapshot.anchor_at(offset, Bias::Right),
916 text: "test".into(),
917 },
918 Inlay {
919 id: InlayId::Hint(post_inc(&mut id)),
920 position: buffer_snapshot.anchor_at(offset, Bias::Left),
921 text: "test".into(),
922 },
923 Inlay {
924 id: InlayId::Hint(post_inc(&mut id)),
925 position: buffer_snapshot.anchor_at(offset, Bias::Right),
926 text: "test".into(),
927 },
928 ]
929 })
930 .collect();
931 let snapshot = display_map.update(cx, |map, cx| {
932 map.splice_inlays(&[], inlays, cx);
933 map.snapshot(cx)
934 });
935
936 assert_eq!(
937 find_preceding_boundary_display_point(
938 &snapshot,
939 buffer_snapshot.len().to_display_point(&snapshot),
940 FindRange::MultiLine,
941 |left, _| left == 'e',
942 ),
943 snapshot
944 .buffer_snapshot
945 .offset_to_point(5)
946 .to_display_point(&snapshot),
947 "Should not stop at inlays when looking for boundaries"
948 );
949 }
950
951 #[gpui::test]
952 fn test_next_word_end(cx: &mut gpui::App) {
953 init_test(cx);
954
955 fn assert(marked_text: &str, cx: &mut gpui::App) {
956 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
957 assert_eq!(
958 next_word_end(&snapshot, display_points[0]),
959 display_points[1]
960 );
961 }
962
963 assert("\nˇ loremˇ", cx);
964 assert(" ˇloremˇ", cx);
965 assert(" lorˇemˇ", cx);
966 assert(" loremˇ ˇ\nipsum\n", cx);
967 assert("\nˇ\nˇ\n\n", cx);
968 assert("loremˇ ipsumˇ ", cx);
969 assert("loremˇ-ˇipsum", cx);
970 assert("loremˇ#$@-ˇipsum", cx);
971 assert("loremˇ_ipsumˇ", cx);
972 assert(" ˇbcΔˇ", cx);
973 assert(" abˇ——ˇcd", cx);
974 }
975
976 #[gpui::test]
977 fn test_next_subword_end(cx: &mut gpui::App) {
978 init_test(cx);
979
980 fn assert(marked_text: &str, cx: &mut gpui::App) {
981 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
982 assert_eq!(
983 next_subword_end(&snapshot, display_points[0]),
984 display_points[1]
985 );
986 }
987
988 // Subword boundaries are respected
989 assert("loˇremˇ_ipsum", cx);
990 assert("ˇloremˇ_ipsum", cx);
991 assert("loremˇ_ipsumˇ", cx);
992 assert("loremˇ_ipsumˇ_dolor", cx);
993 assert("loˇremˇIpsum", cx);
994 assert("loremˇIpsumˇDolor", cx);
995
996 // Word boundaries are still respected
997 assert("\nˇ loremˇ", cx);
998 assert(" ˇloremˇ", cx);
999 assert(" lorˇemˇ", cx);
1000 assert(" loremˇ ˇ\nipsum\n", cx);
1001 assert("\nˇ\nˇ\n\n", cx);
1002 assert("loremˇ ipsumˇ ", cx);
1003 assert("loremˇ-ˇipsum", cx);
1004 assert("loremˇ#$@-ˇipsum", cx);
1005 assert("loremˇ_ipsumˇ", cx);
1006 assert(" ˇbcˇΔ", cx);
1007 assert(" abˇ——ˇcd", cx);
1008 }
1009
1010 #[gpui::test]
1011 fn test_find_boundary(cx: &mut gpui::App) {
1012 init_test(cx);
1013
1014 fn assert(
1015 marked_text: &str,
1016 cx: &mut gpui::App,
1017 is_boundary: impl FnMut(char, char) -> bool,
1018 ) {
1019 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1020 assert_eq!(
1021 find_boundary(
1022 &snapshot,
1023 display_points[0],
1024 FindRange::MultiLine,
1025 is_boundary,
1026 ),
1027 display_points[1]
1028 );
1029 }
1030
1031 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
1032 left == 'j' && right == 'k'
1033 });
1034 assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
1035 left == '\n' && right == 'i'
1036 });
1037 let mut line_count = 0;
1038 assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
1039 if left == '\n' {
1040 line_count += 1;
1041 line_count == 2
1042 } else {
1043 false
1044 }
1045 });
1046 }
1047
1048 #[gpui::test]
1049 fn test_surrounding_word(cx: &mut gpui::App) {
1050 init_test(cx);
1051
1052 fn assert(marked_text: &str, cx: &mut gpui::App) {
1053 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1054 assert_eq!(
1055 surrounding_word(&snapshot, display_points[1]),
1056 display_points[0]..display_points[2],
1057 "{}",
1058 marked_text
1059 );
1060 }
1061
1062 assert("ˇˇloremˇ ipsum", cx);
1063 assert("ˇloˇremˇ ipsum", cx);
1064 assert("ˇloremˇˇ ipsum", cx);
1065 assert("loremˇ ˇ ˇipsum", cx);
1066 assert("lorem\nˇˇˇ\nipsum", cx);
1067 assert("lorem\nˇˇipsumˇ", cx);
1068 assert("loremˇ,ˇˇ ipsum", cx);
1069 assert("ˇloremˇˇ, ipsum", cx);
1070 }
1071
1072 #[gpui::test]
1073 async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
1074 cx.update(|cx| {
1075 init_test(cx);
1076 });
1077
1078 let mut cx = EditorTestContext::new(cx).await;
1079 let editor = cx.editor.clone();
1080 let window = cx.window;
1081 _ = cx.update_window(window, |_, window, cx| {
1082 let text_layout_details = editor.read(cx).text_layout_details(window);
1083
1084 let font = font("Helvetica");
1085
1086 let buffer = cx.new(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
1087 let multibuffer = cx.new(|cx| {
1088 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1089 multibuffer.push_excerpts(
1090 buffer.clone(),
1091 [
1092 ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
1093 ExcerptRange::new(Point::new(2, 0)..Point::new(3, 2)),
1094 ],
1095 cx,
1096 );
1097 multibuffer
1098 });
1099 let display_map = cx.new(|cx| {
1100 DisplayMap::new(
1101 multibuffer,
1102 font,
1103 px(14.0),
1104 None,
1105 0,
1106 1,
1107 FoldPlaceholder::test(),
1108 cx,
1109 )
1110 });
1111 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1112
1113 assert_eq!(snapshot.text(), "abc\ndefg\n\nhijkl\nmn");
1114
1115 let col_2_x = snapshot
1116 .x_for_display_point(DisplayPoint::new(DisplayRow(0), 2), &text_layout_details);
1117
1118 // Can't move up into the first excerpt's header
1119 assert_eq!(
1120 up(
1121 &snapshot,
1122 DisplayPoint::new(DisplayRow(0), 2),
1123 SelectionGoal::HorizontalPosition(col_2_x.0),
1124 false,
1125 &text_layout_details
1126 ),
1127 (
1128 DisplayPoint::new(DisplayRow(0), 0),
1129 SelectionGoal::HorizontalPosition(col_2_x.0),
1130 ),
1131 );
1132 assert_eq!(
1133 up(
1134 &snapshot,
1135 DisplayPoint::new(DisplayRow(0), 0),
1136 SelectionGoal::None,
1137 false,
1138 &text_layout_details
1139 ),
1140 (
1141 DisplayPoint::new(DisplayRow(0), 0),
1142 SelectionGoal::HorizontalPosition(0.0),
1143 ),
1144 );
1145
1146 let col_4_x = snapshot
1147 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 4), &text_layout_details);
1148
1149 // Move up and down within first excerpt
1150 assert_eq!(
1151 up(
1152 &snapshot,
1153 DisplayPoint::new(DisplayRow(1), 4),
1154 SelectionGoal::HorizontalPosition(col_4_x.0),
1155 false,
1156 &text_layout_details
1157 ),
1158 (
1159 DisplayPoint::new(DisplayRow(0), 3),
1160 SelectionGoal::HorizontalPosition(col_4_x.0)
1161 ),
1162 );
1163 assert_eq!(
1164 down(
1165 &snapshot,
1166 DisplayPoint::new(DisplayRow(0), 3),
1167 SelectionGoal::HorizontalPosition(col_4_x.0),
1168 false,
1169 &text_layout_details
1170 ),
1171 (
1172 DisplayPoint::new(DisplayRow(1), 4),
1173 SelectionGoal::HorizontalPosition(col_4_x.0)
1174 ),
1175 );
1176
1177 let col_5_x = snapshot
1178 .x_for_display_point(DisplayPoint::new(DisplayRow(3), 5), &text_layout_details);
1179
1180 // Move up and down across second excerpt's header
1181 assert_eq!(
1182 up(
1183 &snapshot,
1184 DisplayPoint::new(DisplayRow(3), 5),
1185 SelectionGoal::HorizontalPosition(col_5_x.0),
1186 false,
1187 &text_layout_details
1188 ),
1189 (
1190 DisplayPoint::new(DisplayRow(1), 4),
1191 SelectionGoal::HorizontalPosition(col_5_x.0)
1192 ),
1193 );
1194 assert_eq!(
1195 down(
1196 &snapshot,
1197 DisplayPoint::new(DisplayRow(1), 4),
1198 SelectionGoal::HorizontalPosition(col_5_x.0),
1199 false,
1200 &text_layout_details
1201 ),
1202 (
1203 DisplayPoint::new(DisplayRow(3), 5),
1204 SelectionGoal::HorizontalPosition(col_5_x.0)
1205 ),
1206 );
1207
1208 let max_point_x = snapshot
1209 .x_for_display_point(DisplayPoint::new(DisplayRow(4), 2), &text_layout_details);
1210
1211 // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1212 assert_eq!(
1213 down(
1214 &snapshot,
1215 DisplayPoint::new(DisplayRow(4), 0),
1216 SelectionGoal::HorizontalPosition(0.0),
1217 false,
1218 &text_layout_details
1219 ),
1220 (
1221 DisplayPoint::new(DisplayRow(4), 2),
1222 SelectionGoal::HorizontalPosition(0.0)
1223 ),
1224 );
1225 assert_eq!(
1226 down(
1227 &snapshot,
1228 DisplayPoint::new(DisplayRow(4), 2),
1229 SelectionGoal::HorizontalPosition(max_point_x.0),
1230 false,
1231 &text_layout_details
1232 ),
1233 (
1234 DisplayPoint::new(DisplayRow(4), 2),
1235 SelectionGoal::HorizontalPosition(max_point_x.0)
1236 ),
1237 );
1238 });
1239 }
1240
1241 fn init_test(cx: &mut gpui::App) {
1242 let settings_store = SettingsStore::test(cx);
1243 cx.set_global(settings_store);
1244 workspace::init_settings(cx);
1245 theme::init(theme::LoadThemes::JustBase, cx);
1246 language::init(cx);
1247 crate::init(cx);
1248 Project::init_settings(cx);
1249 }
1250}