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 {
516 break;
517 }
518
519 offset -= ch.len_utf8();
520 prev_ch = Some(ch);
521 }
522
523 offset.to_point(buffer_snapshot)
524}
525
526/// Scans for a boundary preceding the given start point `from` until a boundary is found,
527/// indicated by the given predicate returning true.
528/// The predicate is called with the character to the left and right of the candidate boundary location.
529/// 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.
530pub fn find_preceding_boundary_display_point(
531 map: &DisplaySnapshot,
532 from: DisplayPoint,
533 find_range: FindRange,
534 is_boundary: impl FnMut(char, char) -> bool,
535) -> DisplayPoint {
536 let result = find_preceding_boundary_point(
537 &map.buffer_snapshot,
538 from.to_point(map),
539 find_range,
540 is_boundary,
541 );
542 map.clip_point(result.to_display_point(map), Bias::Left)
543}
544
545/// Scans for a boundary following the given start point until a boundary is found, indicated by the
546/// given predicate returning true. The predicate is called with the character to the left and right
547/// of the candidate boundary location, and will be called with `\n` characters indicating the start
548/// or end of a line. The function supports optionally returning the point just before the boundary
549/// is found via return_point_before_boundary.
550pub fn find_boundary_point(
551 map: &DisplaySnapshot,
552 from: DisplayPoint,
553 find_range: FindRange,
554 mut is_boundary: impl FnMut(char, char) -> bool,
555 return_point_before_boundary: bool,
556) -> DisplayPoint {
557 let mut offset = from.to_offset(map, Bias::Right);
558 let mut prev_offset = offset;
559 let mut prev_ch = None;
560
561 for ch in map.buffer_snapshot.chars_at(offset) {
562 if find_range == FindRange::SingleLine && ch == '\n' {
563 break;
564 }
565 if let Some(prev_ch) = prev_ch
566 && is_boundary(prev_ch, ch)
567 {
568 if return_point_before_boundary {
569 return map.clip_point(prev_offset.to_display_point(map), Bias::Right);
570 } else {
571 break;
572 }
573 }
574 prev_offset = offset;
575 offset += ch.len_utf8();
576 prev_ch = Some(ch);
577 }
578 map.clip_point(offset.to_display_point(map), Bias::Right)
579}
580
581pub fn find_preceding_boundary_trail(
582 map: &DisplaySnapshot,
583 head: DisplayPoint,
584 mut is_boundary: impl FnMut(char, char) -> bool,
585) -> (Option<DisplayPoint>, DisplayPoint) {
586 let mut offset = head.to_offset(map, Bias::Left);
587 let mut trail_offset = None;
588
589 let mut prev_ch = map.buffer_snapshot.chars_at(offset).next();
590 let mut forward = map.buffer_snapshot.reversed_chars_at(offset).peekable();
591
592 // Skip newlines
593 while let Some(&ch) = forward.peek() {
594 if ch == '\n' {
595 prev_ch = forward.next();
596 offset -= ch.len_utf8();
597 trail_offset = Some(offset);
598 } else {
599 break;
600 }
601 }
602
603 // Find the boundary
604 let start_offset = offset;
605 for ch in forward {
606 if let Some(prev_ch) = prev_ch
607 && is_boundary(prev_ch, ch)
608 {
609 if start_offset == offset {
610 trail_offset = Some(offset);
611 } else {
612 break;
613 }
614 }
615 offset -= ch.len_utf8();
616 prev_ch = Some(ch);
617 }
618
619 let trail = trail_offset
620 .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Left));
621
622 (
623 trail,
624 map.clip_point(offset.to_display_point(map), Bias::Left),
625 )
626}
627
628/// Finds the location of a boundary
629pub fn find_boundary_trail(
630 map: &DisplaySnapshot,
631 head: DisplayPoint,
632 mut is_boundary: impl FnMut(char, char) -> bool,
633) -> (Option<DisplayPoint>, DisplayPoint) {
634 let mut offset = head.to_offset(map, Bias::Right);
635 let mut trail_offset = None;
636
637 let mut prev_ch = map.buffer_snapshot.reversed_chars_at(offset).next();
638 let mut forward = map.buffer_snapshot.chars_at(offset).peekable();
639
640 // Skip newlines
641 while let Some(&ch) = forward.peek() {
642 if ch == '\n' {
643 prev_ch = forward.next();
644 offset += ch.len_utf8();
645 trail_offset = Some(offset);
646 } else {
647 break;
648 }
649 }
650
651 // Find the boundary
652 let start_offset = offset;
653 for ch in forward {
654 if let Some(prev_ch) = prev_ch
655 && is_boundary(prev_ch, ch)
656 {
657 if start_offset == offset {
658 trail_offset = Some(offset);
659 } else {
660 break;
661 }
662 }
663 offset += ch.len_utf8();
664 prev_ch = Some(ch);
665 }
666
667 let trail = trail_offset
668 .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Right));
669
670 (
671 trail,
672 map.clip_point(offset.to_display_point(map), Bias::Right),
673 )
674}
675
676pub fn find_boundary(
677 map: &DisplaySnapshot,
678 from: DisplayPoint,
679 find_range: FindRange,
680 is_boundary: impl FnMut(char, char) -> bool,
681) -> DisplayPoint {
682 find_boundary_point(map, from, find_range, is_boundary, false)
683}
684
685pub fn find_boundary_exclusive(
686 map: &DisplaySnapshot,
687 from: DisplayPoint,
688 find_range: FindRange,
689 is_boundary: impl FnMut(char, char) -> bool,
690) -> DisplayPoint {
691 find_boundary_point(map, from, find_range, is_boundary, true)
692}
693
694/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
695/// The returned value also contains a range of the start/end of a returned character in
696/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
697pub fn chars_after(
698 map: &DisplaySnapshot,
699 mut offset: usize,
700) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
701 map.buffer_snapshot.chars_at(offset).map(move |ch| {
702 let before = offset;
703 offset += ch.len_utf8();
704 (ch, before..offset)
705 })
706}
707
708/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
709/// The returned value also contains a range of the start/end of a returned character in
710/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
711pub fn chars_before(
712 map: &DisplaySnapshot,
713 mut offset: usize,
714) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
715 map.buffer_snapshot
716 .reversed_chars_at(offset)
717 .map(move |ch| {
718 let after = offset;
719 offset -= ch.len_utf8();
720 (ch, offset..after)
721 })
722}
723
724/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
725/// within a passed range.
726///
727/// The line ranges are **always* going to be in bounds of a requested range, which means that
728/// the first and the last lines might not necessarily represent the
729/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
730pub fn split_display_range_by_lines(
731 map: &DisplaySnapshot,
732 range: Range<DisplayPoint>,
733) -> Vec<Range<DisplayPoint>> {
734 let mut result = Vec::new();
735
736 let mut start = range.start;
737 // Loop over all the covered rows until the one containing the range end
738 for row in range.start.row().0..range.end.row().0 {
739 let row_end_column = map.line_len(DisplayRow(row));
740 let end = map.clip_point(
741 DisplayPoint::new(DisplayRow(row), row_end_column),
742 Bias::Left,
743 );
744 if start != end {
745 result.push(start..end);
746 }
747 start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
748 }
749
750 // Add the final range from the start of the last end to the original range end.
751 result.push(start..range.end);
752
753 result
754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759 use crate::{
760 Buffer, DisplayMap, DisplayRow, ExcerptRange, FoldPlaceholder, MultiBuffer,
761 display_map::Inlay,
762 test::{editor_test_context::EditorTestContext, marked_display_snapshot},
763 };
764 use gpui::{AppContext as _, font, px};
765 use language::Capability;
766 use project::{Project, project_settings::DiagnosticSeverity};
767 use settings::SettingsStore;
768 use util::post_inc;
769
770 #[gpui::test]
771 fn test_previous_word_start(cx: &mut gpui::App) {
772 init_test(cx);
773
774 fn assert(marked_text: &str, cx: &mut gpui::App) {
775 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
776 let actual = previous_word_start(&snapshot, display_points[1]);
777 let expected = display_points[0];
778 if actual != expected {
779 eprintln!(
780 "previous_word_start mismatch for '{}': actual={:?}, expected={:?}",
781 marked_text, actual, expected
782 );
783 }
784 assert_eq!(actual, expected);
785 }
786
787 assert("\nˇ ˇlorem", cx);
788 assert("ˇ\nˇ lorem", cx);
789 assert(" ˇloremˇ", cx);
790 assert("ˇ ˇlorem", cx);
791 assert(" ˇlorˇem", cx);
792 assert("\nlorem\nˇ ˇipsum", cx);
793 assert("\n\nˇ\nˇ", cx);
794 assert(" ˇlorem ˇipsum", cx);
795 assert("ˇlorem-ˇipsum", cx);
796 assert("loremˇ-#$@ˇipsum", cx);
797 assert("ˇlorem_ˇipsum", cx);
798 assert(" ˇdefγˇ", cx);
799 assert(" ˇbcΔˇ", cx);
800 // Test punctuation skipping behavior
801 assert("ˇhello.ˇ", cx);
802 assert("helloˇ...ˇ", cx);
803 assert("helloˇ.---..ˇtest", cx);
804 assert("test ˇ.--ˇtest", cx);
805 assert("oneˇ,;:!?ˇtwo", cx);
806 }
807
808 #[gpui::test]
809 fn test_previous_subword_start(cx: &mut gpui::App) {
810 init_test(cx);
811
812 fn assert(marked_text: &str, cx: &mut gpui::App) {
813 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
814 assert_eq!(
815 previous_subword_start(&snapshot, display_points[1]),
816 display_points[0]
817 );
818 }
819
820 // Subword boundaries are respected
821 assert("lorem_ˇipˇsum", cx);
822 assert("lorem_ˇipsumˇ", cx);
823 assert("ˇlorem_ˇipsum", cx);
824 assert("lorem_ˇipsum_ˇdolor", cx);
825 assert("loremˇIpˇsum", cx);
826 assert("loremˇIpsumˇ", cx);
827
828 // Word boundaries are still respected
829 assert("\nˇ ˇlorem", cx);
830 assert(" ˇloremˇ", cx);
831 assert(" ˇlorˇem", cx);
832 assert("\nlorem\nˇ ˇipsum", cx);
833 assert("\n\nˇ\nˇ", cx);
834 assert(" ˇlorem ˇipsum", cx);
835 assert("loremˇ-ˇipsum", cx);
836 assert("loremˇ-#$@ˇipsum", cx);
837 assert(" ˇdefγˇ", cx);
838 assert(" bcˇΔˇ", cx);
839 assert(" ˇbcδˇ", cx);
840 assert(" abˇ——ˇcd", cx);
841 }
842
843 #[gpui::test]
844 fn test_find_preceding_boundary(cx: &mut gpui::App) {
845 init_test(cx);
846
847 fn assert(
848 marked_text: &str,
849 cx: &mut gpui::App,
850 is_boundary: impl FnMut(char, char) -> bool,
851 ) {
852 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
853 assert_eq!(
854 find_preceding_boundary_display_point(
855 &snapshot,
856 display_points[1],
857 FindRange::MultiLine,
858 is_boundary
859 ),
860 display_points[0]
861 );
862 }
863
864 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
865 left == 'c' && right == 'd'
866 });
867 assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
868 left == '\n' && right == 'g'
869 });
870 let mut line_count = 0;
871 assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
872 if left == '\n' {
873 line_count += 1;
874 line_count == 2
875 } else {
876 false
877 }
878 });
879 }
880
881 #[gpui::test]
882 fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::App) {
883 init_test(cx);
884
885 let input_text = "abcdefghijklmnopqrstuvwxys";
886 let font = font("Helvetica");
887 let font_size = px(14.0);
888 let buffer = MultiBuffer::build_simple(input_text, cx);
889 let buffer_snapshot = buffer.read(cx).snapshot(cx);
890
891 let display_map = cx.new(|cx| {
892 DisplayMap::new(
893 buffer,
894 font,
895 font_size,
896 None,
897 1,
898 1,
899 FoldPlaceholder::test(),
900 DiagnosticSeverity::Warning,
901 cx,
902 )
903 });
904
905 // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
906 let mut id = 0;
907 let inlays = (0..buffer_snapshot.len())
908 .flat_map(|offset| {
909 [
910 Inlay::edit_prediction(
911 post_inc(&mut id),
912 buffer_snapshot.anchor_at(offset, Bias::Left),
913 "test",
914 ),
915 Inlay::edit_prediction(
916 post_inc(&mut id),
917 buffer_snapshot.anchor_at(offset, Bias::Right),
918 "test",
919 ),
920 Inlay::mock_hint(
921 post_inc(&mut id),
922 buffer_snapshot.anchor_at(offset, Bias::Left),
923 "test",
924 ),
925 Inlay::mock_hint(
926 post_inc(&mut id),
927 buffer_snapshot.anchor_at(offset, Bias::Right),
928 "test",
929 ),
930 ]
931 })
932 .collect();
933 let snapshot = display_map.update(cx, |map, cx| {
934 map.splice_inlays(&[], inlays, cx);
935 map.snapshot(cx)
936 });
937
938 assert_eq!(
939 find_preceding_boundary_display_point(
940 &snapshot,
941 buffer_snapshot.len().to_display_point(&snapshot),
942 FindRange::MultiLine,
943 |left, _| left == 'e',
944 ),
945 snapshot
946 .buffer_snapshot
947 .offset_to_point(5)
948 .to_display_point(&snapshot),
949 "Should not stop at inlays when looking for boundaries"
950 );
951 }
952
953 #[gpui::test]
954 fn test_next_word_end(cx: &mut gpui::App) {
955 init_test(cx);
956
957 fn assert(marked_text: &str, cx: &mut gpui::App) {
958 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
959 let actual = next_word_end(&snapshot, display_points[0]);
960 let expected = display_points[1];
961 if actual != expected {
962 eprintln!(
963 "next_word_end mismatch for '{}': actual={:?}, expected={:?}",
964 marked_text, actual, expected
965 );
966 }
967 assert_eq!(actual, expected);
968 }
969
970 assert("\nˇ loremˇ", cx);
971 assert(" ˇloremˇ", cx);
972 assert(" lorˇemˇ", cx);
973 assert(" loremˇ ˇ\nipsum\n", cx);
974 assert("\nˇ\nˇ\n\n", cx);
975 assert("loremˇ ipsumˇ ", cx);
976 assert("loremˇ-ipsumˇ", cx);
977 assert("loremˇ#$@-ˇipsum", cx);
978 assert("loremˇ_ipsumˇ", cx);
979 assert(" ˇbcΔˇ", cx);
980 assert(" abˇ——ˇcd", cx);
981 // Test punctuation skipping behavior
982 assert("ˇ.helloˇ", cx);
983 assert("display_pointsˇ[0ˇ]", cx);
984 assert("ˇ...ˇhello", cx);
985 assert("helloˇ.---..ˇtest", cx);
986 assert("testˇ.--ˇ test", cx);
987 assert("oneˇ,;:!?ˇtwo", cx);
988 }
989
990 #[gpui::test]
991 fn test_next_subword_end(cx: &mut gpui::App) {
992 init_test(cx);
993
994 fn assert(marked_text: &str, cx: &mut gpui::App) {
995 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
996 assert_eq!(
997 next_subword_end(&snapshot, display_points[0]),
998 display_points[1]
999 );
1000 }
1001
1002 // Subword boundaries are respected
1003 assert("loˇremˇ_ipsum", cx);
1004 assert("ˇloremˇ_ipsum", cx);
1005 assert("loremˇ_ipsumˇ", cx);
1006 assert("loremˇ_ipsumˇ_dolor", cx);
1007 assert("loˇremˇIpsum", cx);
1008 assert("loremˇIpsumˇDolor", cx);
1009
1010 // Word boundaries are still respected
1011 assert("\nˇ loremˇ", cx);
1012 assert(" ˇloremˇ", cx);
1013 assert(" lorˇemˇ", cx);
1014 assert(" loremˇ ˇ\nipsum\n", cx);
1015 assert("\nˇ\nˇ\n\n", cx);
1016 assert("loremˇ ipsumˇ ", cx);
1017 assert("loremˇ-ˇipsum", cx);
1018 assert("loremˇ#$@-ˇipsum", cx);
1019 assert("loremˇ_ipsumˇ", cx);
1020 assert(" ˇbcˇΔ", cx);
1021 assert(" abˇ——ˇcd", cx);
1022 }
1023
1024 #[gpui::test]
1025 fn test_find_boundary(cx: &mut gpui::App) {
1026 init_test(cx);
1027
1028 fn assert(
1029 marked_text: &str,
1030 cx: &mut gpui::App,
1031 is_boundary: impl FnMut(char, char) -> bool,
1032 ) {
1033 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
1034 assert_eq!(
1035 find_boundary(
1036 &snapshot,
1037 display_points[0],
1038 FindRange::MultiLine,
1039 is_boundary,
1040 ),
1041 display_points[1]
1042 );
1043 }
1044
1045 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
1046 left == 'j' && right == 'k'
1047 });
1048 assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
1049 left == '\n' && right == 'i'
1050 });
1051 let mut line_count = 0;
1052 assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
1053 if left == '\n' {
1054 line_count += 1;
1055 line_count == 2
1056 } else {
1057 false
1058 }
1059 });
1060 }
1061
1062 #[gpui::test]
1063 async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
1064 cx.update(|cx| {
1065 init_test(cx);
1066 });
1067
1068 let mut cx = EditorTestContext::new(cx).await;
1069 let editor = cx.editor.clone();
1070 let window = cx.window;
1071 _ = cx.update_window(window, |_, window, cx| {
1072 let text_layout_details = editor.read(cx).text_layout_details(window);
1073
1074 let font = font("Helvetica");
1075
1076 let buffer = cx.new(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
1077 let multibuffer = cx.new(|cx| {
1078 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1079 multibuffer.push_excerpts(
1080 buffer.clone(),
1081 [
1082 ExcerptRange::new(Point::new(0, 0)..Point::new(1, 4)),
1083 ExcerptRange::new(Point::new(2, 0)..Point::new(3, 2)),
1084 ],
1085 cx,
1086 );
1087 multibuffer
1088 });
1089 let display_map = cx.new(|cx| {
1090 DisplayMap::new(
1091 multibuffer,
1092 font,
1093 px(14.0),
1094 None,
1095 0,
1096 1,
1097 FoldPlaceholder::test(),
1098 DiagnosticSeverity::Warning,
1099 cx,
1100 )
1101 });
1102 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1103
1104 assert_eq!(snapshot.text(), "abc\ndefg\n\nhijkl\nmn");
1105
1106 let col_2_x = snapshot
1107 .x_for_display_point(DisplayPoint::new(DisplayRow(0), 2), &text_layout_details);
1108
1109 // Can't move up into the first excerpt's header
1110 assert_eq!(
1111 up(
1112 &snapshot,
1113 DisplayPoint::new(DisplayRow(0), 2),
1114 SelectionGoal::HorizontalPosition(col_2_x.0),
1115 false,
1116 &text_layout_details
1117 ),
1118 (
1119 DisplayPoint::new(DisplayRow(0), 0),
1120 SelectionGoal::HorizontalPosition(col_2_x.0),
1121 ),
1122 );
1123 assert_eq!(
1124 up(
1125 &snapshot,
1126 DisplayPoint::new(DisplayRow(0), 0),
1127 SelectionGoal::None,
1128 false,
1129 &text_layout_details
1130 ),
1131 (
1132 DisplayPoint::new(DisplayRow(0), 0),
1133 SelectionGoal::HorizontalPosition(0.0),
1134 ),
1135 );
1136
1137 let col_4_x = snapshot
1138 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 4), &text_layout_details);
1139
1140 // Move up and down within first excerpt
1141 assert_eq!(
1142 up(
1143 &snapshot,
1144 DisplayPoint::new(DisplayRow(1), 4),
1145 SelectionGoal::HorizontalPosition(col_4_x.0),
1146 false,
1147 &text_layout_details
1148 ),
1149 (
1150 DisplayPoint::new(DisplayRow(0), 3),
1151 SelectionGoal::HorizontalPosition(col_4_x.0)
1152 ),
1153 );
1154 assert_eq!(
1155 down(
1156 &snapshot,
1157 DisplayPoint::new(DisplayRow(0), 3),
1158 SelectionGoal::HorizontalPosition(col_4_x.0),
1159 false,
1160 &text_layout_details
1161 ),
1162 (
1163 DisplayPoint::new(DisplayRow(1), 4),
1164 SelectionGoal::HorizontalPosition(col_4_x.0)
1165 ),
1166 );
1167
1168 let col_5_x = snapshot
1169 .x_for_display_point(DisplayPoint::new(DisplayRow(3), 5), &text_layout_details);
1170
1171 // Move up and down across second excerpt's header
1172 assert_eq!(
1173 up(
1174 &snapshot,
1175 DisplayPoint::new(DisplayRow(3), 5),
1176 SelectionGoal::HorizontalPosition(col_5_x.0),
1177 false,
1178 &text_layout_details
1179 ),
1180 (
1181 DisplayPoint::new(DisplayRow(1), 4),
1182 SelectionGoal::HorizontalPosition(col_5_x.0)
1183 ),
1184 );
1185 assert_eq!(
1186 down(
1187 &snapshot,
1188 DisplayPoint::new(DisplayRow(1), 4),
1189 SelectionGoal::HorizontalPosition(col_5_x.0),
1190 false,
1191 &text_layout_details
1192 ),
1193 (
1194 DisplayPoint::new(DisplayRow(3), 5),
1195 SelectionGoal::HorizontalPosition(col_5_x.0)
1196 ),
1197 );
1198
1199 let max_point_x = snapshot
1200 .x_for_display_point(DisplayPoint::new(DisplayRow(4), 2), &text_layout_details);
1201
1202 // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1203 assert_eq!(
1204 down(
1205 &snapshot,
1206 DisplayPoint::new(DisplayRow(4), 0),
1207 SelectionGoal::HorizontalPosition(0.0),
1208 false,
1209 &text_layout_details
1210 ),
1211 (
1212 DisplayPoint::new(DisplayRow(4), 2),
1213 SelectionGoal::HorizontalPosition(0.0)
1214 ),
1215 );
1216 assert_eq!(
1217 down(
1218 &snapshot,
1219 DisplayPoint::new(DisplayRow(4), 2),
1220 SelectionGoal::HorizontalPosition(max_point_x.0),
1221 false,
1222 &text_layout_details
1223 ),
1224 (
1225 DisplayPoint::new(DisplayRow(4), 2),
1226 SelectionGoal::HorizontalPosition(max_point_x.0)
1227 ),
1228 );
1229 });
1230 }
1231
1232 fn init_test(cx: &mut gpui::App) {
1233 let settings_store = SettingsStore::test(cx);
1234 cx.set_global(settings_store);
1235 workspace::init_settings(cx);
1236 theme::init(theme::LoadThemes::JustBase, cx);
1237 language::init(cx);
1238 crate::init(cx);
1239 Project::init_settings(cx);
1240 }
1241}