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