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::{scroll::ScrollAnchor, CharKind, DisplayRow, EditorStyle, ToOffset, ToPoint};
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 map.clip_point(start, Bias::Left)
452 }
453 Direction::Next => {
454 let mut end = excerpt.end_anchor().to_display_point(&map);
455 *end.column_mut() = 0;
456 if end <= display_point {
457 *end.row_mut() += 1;
458 let point_end = map.display_point_to_point(end, Bias::Right);
459 let Some(excerpt) = map.buffer_snapshot.excerpt_containing(point_end..point_end)
460 else {
461 return display_point;
462 };
463 end = excerpt.end_anchor().to_display_point(&map);
464 *end.column_mut() = 0;
465 }
466 end
467 }
468 }
469}
470
471/// Scans for a boundary preceding the given start point `from` until a boundary is found,
472/// indicated by the given predicate returning true.
473/// The predicate is called with the character to the left and right of the candidate boundary location.
474/// 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.
475pub fn find_preceding_boundary_point(
476 buffer_snapshot: &MultiBufferSnapshot,
477 from: Point,
478 find_range: FindRange,
479 mut is_boundary: impl FnMut(char, char) -> bool,
480) -> Point {
481 let mut prev_ch = None;
482 let mut offset = from.to_offset(buffer_snapshot);
483
484 for ch in buffer_snapshot.reversed_chars_at(offset) {
485 if find_range == FindRange::SingleLine && ch == '\n' {
486 break;
487 }
488 if let Some(prev_ch) = prev_ch {
489 if is_boundary(ch, prev_ch) {
490 break;
491 }
492 }
493
494 offset -= ch.len_utf8();
495 prev_ch = Some(ch);
496 }
497
498 offset.to_point(buffer_snapshot)
499}
500
501/// Scans for a boundary preceding the given start point `from` until a boundary is found,
502/// indicated by the given predicate returning true.
503/// The predicate is called with the character to the left and right of the candidate boundary location.
504/// 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.
505pub fn find_preceding_boundary_display_point(
506 map: &DisplaySnapshot,
507 from: DisplayPoint,
508 find_range: FindRange,
509 is_boundary: impl FnMut(char, char) -> bool,
510) -> DisplayPoint {
511 let result = find_preceding_boundary_point(
512 &map.buffer_snapshot,
513 from.to_point(map),
514 find_range,
515 is_boundary,
516 );
517 map.clip_point(result.to_display_point(map), Bias::Left)
518}
519
520/// Scans for a boundary following the given start point until a boundary is found, indicated by the
521/// given predicate returning true. The predicate is called with the character to the left and right
522/// of the candidate boundary location, and will be called with `\n` characters indicating the start
523/// or end of a line. The function supports optionally returning the point just before the boundary
524/// is found via return_point_before_boundary.
525pub fn find_boundary_point(
526 map: &DisplaySnapshot,
527 from: DisplayPoint,
528 find_range: FindRange,
529 mut is_boundary: impl FnMut(char, char) -> bool,
530 return_point_before_boundary: bool,
531) -> DisplayPoint {
532 let mut offset = from.to_offset(map, Bias::Right);
533 let mut prev_offset = offset;
534 let mut prev_ch = None;
535
536 for ch in map.buffer_snapshot.chars_at(offset) {
537 if find_range == FindRange::SingleLine && ch == '\n' {
538 break;
539 }
540 if let Some(prev_ch) = prev_ch {
541 if is_boundary(prev_ch, ch) {
542 if return_point_before_boundary {
543 return map.clip_point(prev_offset.to_display_point(map), Bias::Right);
544 } else {
545 break;
546 }
547 }
548 }
549 prev_offset = offset;
550 offset += ch.len_utf8();
551 prev_ch = Some(ch);
552 }
553 map.clip_point(offset.to_display_point(map), Bias::Right)
554}
555
556pub fn find_preceding_boundary_trail(
557 map: &DisplaySnapshot,
558 head: DisplayPoint,
559 mut is_boundary: impl FnMut(char, char) -> bool,
560) -> (Option<DisplayPoint>, DisplayPoint) {
561 let mut offset = head.to_offset(map, Bias::Left);
562 let mut trail_offset = None;
563
564 let mut prev_ch = map.buffer_snapshot.chars_at(offset).next();
565 let mut forward = map.buffer_snapshot.reversed_chars_at(offset).peekable();
566
567 // Skip newlines
568 while let Some(&ch) = forward.peek() {
569 if ch == '\n' {
570 prev_ch = forward.next();
571 offset -= ch.len_utf8();
572 trail_offset = Some(offset);
573 } else {
574 break;
575 }
576 }
577
578 // Find the boundary
579 let start_offset = offset;
580 for ch in forward {
581 if let Some(prev_ch) = prev_ch {
582 if is_boundary(prev_ch, ch) {
583 if start_offset == offset {
584 trail_offset = Some(offset);
585 } else {
586 break;
587 }
588 }
589 }
590 offset -= ch.len_utf8();
591 prev_ch = Some(ch);
592 }
593
594 let trail = trail_offset
595 .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Left));
596
597 (
598 trail,
599 map.clip_point(offset.to_display_point(map), Bias::Left),
600 )
601}
602
603/// Finds the location of a boundary
604pub fn find_boundary_trail(
605 map: &DisplaySnapshot,
606 head: DisplayPoint,
607 mut is_boundary: impl FnMut(char, char) -> bool,
608) -> (Option<DisplayPoint>, DisplayPoint) {
609 let mut offset = head.to_offset(map, Bias::Right);
610 let mut trail_offset = None;
611
612 let mut prev_ch = map.buffer_snapshot.reversed_chars_at(offset).next();
613 let mut forward = map.buffer_snapshot.chars_at(offset).peekable();
614
615 // Skip newlines
616 while let Some(&ch) = forward.peek() {
617 if ch == '\n' {
618 prev_ch = forward.next();
619 offset += ch.len_utf8();
620 trail_offset = Some(offset);
621 } else {
622 break;
623 }
624 }
625
626 // Find the boundary
627 let start_offset = offset;
628 for ch in forward {
629 if let Some(prev_ch) = prev_ch {
630 if is_boundary(prev_ch, ch) {
631 if start_offset == offset {
632 trail_offset = Some(offset);
633 } else {
634 break;
635 }
636 }
637 }
638 offset += ch.len_utf8();
639 prev_ch = Some(ch);
640 }
641
642 let trail = trail_offset
643 .map(|trail_offset: usize| map.clip_point(trail_offset.to_display_point(map), Bias::Right));
644
645 (
646 trail,
647 map.clip_point(offset.to_display_point(map), Bias::Right),
648 )
649}
650
651pub fn find_boundary(
652 map: &DisplaySnapshot,
653 from: DisplayPoint,
654 find_range: FindRange,
655 is_boundary: impl FnMut(char, char) -> bool,
656) -> DisplayPoint {
657 find_boundary_point(map, from, find_range, is_boundary, false)
658}
659
660pub fn find_boundary_exclusive(
661 map: &DisplaySnapshot,
662 from: DisplayPoint,
663 find_range: FindRange,
664 is_boundary: impl FnMut(char, char) -> bool,
665) -> DisplayPoint {
666 find_boundary_point(map, from, find_range, is_boundary, true)
667}
668
669/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
670/// The returned value also contains a range of the start/end of a returned character in
671/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
672pub fn chars_after(
673 map: &DisplaySnapshot,
674 mut offset: usize,
675) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
676 map.buffer_snapshot.chars_at(offset).map(move |ch| {
677 let before = offset;
678 offset += ch.len_utf8();
679 (ch, before..offset)
680 })
681}
682
683/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
684/// The returned value also contains a range of the start/end of a returned character in
685/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
686pub fn chars_before(
687 map: &DisplaySnapshot,
688 mut offset: usize,
689) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
690 map.buffer_snapshot
691 .reversed_chars_at(offset)
692 .map(move |ch| {
693 let after = offset;
694 offset -= ch.len_utf8();
695 (ch, offset..after)
696 })
697}
698
699pub(crate) fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
700 let raw_point = point.to_point(map);
701 let classifier = map.buffer_snapshot.char_classifier_at(raw_point);
702 let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
703 let text = &map.buffer_snapshot;
704 let next_char_kind = text.chars_at(ix).next().map(|c| classifier.kind(c));
705 let prev_char_kind = text
706 .reversed_chars_at(ix)
707 .next()
708 .map(|c| classifier.kind(c));
709 prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
710}
711
712pub(crate) fn surrounding_word(
713 map: &DisplaySnapshot,
714 position: DisplayPoint,
715) -> Range<DisplayPoint> {
716 let position = map
717 .clip_point(position, Bias::Left)
718 .to_offset(map, Bias::Left);
719 let (range, _) = map.buffer_snapshot.surrounding_word(position, false);
720 let start = range
721 .start
722 .to_point(&map.buffer_snapshot)
723 .to_display_point(map);
724 let end = range
725 .end
726 .to_point(&map.buffer_snapshot)
727 .to_display_point(map);
728 start..end
729}
730
731/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
732/// within a passed range.
733///
734/// The line ranges are **always* going to be in bounds of a requested range, which means that
735/// the first and the last lines might not necessarily represent the
736/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
737pub fn split_display_range_by_lines(
738 map: &DisplaySnapshot,
739 range: Range<DisplayPoint>,
740) -> Vec<Range<DisplayPoint>> {
741 let mut result = Vec::new();
742
743 let mut start = range.start;
744 // Loop over all the covered rows until the one containing the range end
745 for row in range.start.row().0..range.end.row().0 {
746 let row_end_column = map.line_len(DisplayRow(row));
747 let end = map.clip_point(
748 DisplayPoint::new(DisplayRow(row), row_end_column),
749 Bias::Left,
750 );
751 if start != end {
752 result.push(start..end);
753 }
754 start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
755 }
756
757 // Add the final range from the start of the last end to the original range end.
758 result.push(start..range.end);
759
760 result
761}
762
763#[cfg(test)]
764mod tests {
765 use super::*;
766 use crate::{
767 display_map::Inlay,
768 test::{editor_test_context::EditorTestContext, marked_display_snapshot},
769 Buffer, DisplayMap, DisplayRow, ExcerptRange, FoldPlaceholder, InlayId, MultiBuffer,
770 };
771 use gpui::{font, px, AppContext as _};
772 use language::Capability;
773 use project::Project;
774 use settings::SettingsStore;
775 use util::post_inc;
776
777 #[gpui::test]
778 fn test_previous_word_start(cx: &mut gpui::App) {
779 init_test(cx);
780
781 fn assert(marked_text: &str, cx: &mut gpui::App) {
782 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
783 assert_eq!(
784 previous_word_start(&snapshot, display_points[1]),
785 display_points[0]
786 );
787 }
788
789 assert("\nˇ ˇlorem", cx);
790 assert("ˇ\nˇ lorem", cx);
791 assert(" ˇloremˇ", cx);
792 assert("ˇ ˇlorem", cx);
793 assert(" ˇlorˇem", cx);
794 assert("\nlorem\nˇ ˇipsum", cx);
795 assert("\n\nˇ\nˇ", cx);
796 assert(" ˇlorem ˇipsum", cx);
797 assert("loremˇ-ˇipsum", cx);
798 assert("loremˇ-#$@ˇipsum", cx);
799 assert("ˇlorem_ˇipsum", cx);
800 assert(" ˇdefγˇ", cx);
801 assert(" ˇbcΔˇ", cx);
802 assert(" abˇ——ˇcd", cx);
803 }
804
805 #[gpui::test]
806 fn test_previous_subword_start(cx: &mut gpui::App) {
807 init_test(cx);
808
809 fn assert(marked_text: &str, cx: &mut gpui::App) {
810 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
811 assert_eq!(
812 previous_subword_start(&snapshot, display_points[1]),
813 display_points[0]
814 );
815 }
816
817 // Subword boundaries are respected
818 assert("lorem_ˇipˇsum", cx);
819 assert("lorem_ˇipsumˇ", cx);
820 assert("ˇlorem_ˇipsum", cx);
821 assert("lorem_ˇipsum_ˇdolor", cx);
822 assert("loremˇIpˇsum", cx);
823 assert("loremˇIpsumˇ", cx);
824
825 // Word boundaries are still respected
826 assert("\nˇ ˇlorem", cx);
827 assert(" ˇloremˇ", cx);
828 assert(" ˇlorˇem", cx);
829 assert("\nlorem\nˇ ˇipsum", cx);
830 assert("\n\nˇ\nˇ", cx);
831 assert(" ˇlorem ˇipsum", cx);
832 assert("loremˇ-ˇipsum", cx);
833 assert("loremˇ-#$@ˇipsum", cx);
834 assert(" ˇdefγˇ", cx);
835 assert(" bcˇΔˇ", cx);
836 assert(" ˇbcδˇ", cx);
837 assert(" abˇ——ˇcd", cx);
838 }
839
840 #[gpui::test]
841 fn test_find_preceding_boundary(cx: &mut gpui::App) {
842 init_test(cx);
843
844 fn assert(
845 marked_text: &str,
846 cx: &mut gpui::App,
847 is_boundary: impl FnMut(char, char) -> bool,
848 ) {
849 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
850 assert_eq!(
851 find_preceding_boundary_display_point(
852 &snapshot,
853 display_points[1],
854 FindRange::MultiLine,
855 is_boundary
856 ),
857 display_points[0]
858 );
859 }
860
861 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
862 left == 'c' && right == 'd'
863 });
864 assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
865 left == '\n' && right == 'g'
866 });
867 let mut line_count = 0;
868 assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
869 if left == '\n' {
870 line_count += 1;
871 line_count == 2
872 } else {
873 false
874 }
875 });
876 }
877
878 #[gpui::test]
879 fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::App) {
880 init_test(cx);
881
882 let input_text = "abcdefghijklmnopqrstuvwxys";
883 let font = font("Helvetica");
884 let font_size = px(14.0);
885 let buffer = MultiBuffer::build_simple(input_text, cx);
886 let buffer_snapshot = buffer.read(cx).snapshot(cx);
887
888 let display_map = cx.new(|cx| {
889 DisplayMap::new(
890 buffer,
891 font,
892 font_size,
893 None,
894 true,
895 1,
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 {
1093 context: Point::new(0, 0)..Point::new(1, 4),
1094 primary: None,
1095 },
1096 ExcerptRange {
1097 context: Point::new(2, 0)..Point::new(3, 2),
1098 primary: None,
1099 },
1100 ],
1101 cx,
1102 );
1103 multibuffer
1104 });
1105 let display_map = cx.new(|cx| {
1106 DisplayMap::new(
1107 multibuffer,
1108 font,
1109 px(14.0),
1110 None,
1111 true,
1112 0,
1113 2,
1114 0,
1115 FoldPlaceholder::test(),
1116 cx,
1117 )
1118 });
1119 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
1120
1121 assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
1122
1123 let col_2_x = snapshot
1124 .x_for_display_point(DisplayPoint::new(DisplayRow(2), 2), &text_layout_details);
1125
1126 // Can't move up into the first excerpt's header
1127 assert_eq!(
1128 up(
1129 &snapshot,
1130 DisplayPoint::new(DisplayRow(2), 2),
1131 SelectionGoal::HorizontalPosition(col_2_x.0),
1132 false,
1133 &text_layout_details
1134 ),
1135 (
1136 DisplayPoint::new(DisplayRow(2), 0),
1137 SelectionGoal::HorizontalPosition(col_2_x.0),
1138 ),
1139 );
1140 assert_eq!(
1141 up(
1142 &snapshot,
1143 DisplayPoint::new(DisplayRow(2), 0),
1144 SelectionGoal::None,
1145 false,
1146 &text_layout_details
1147 ),
1148 (
1149 DisplayPoint::new(DisplayRow(2), 0),
1150 SelectionGoal::HorizontalPosition(0.0),
1151 ),
1152 );
1153
1154 let col_4_x = snapshot
1155 .x_for_display_point(DisplayPoint::new(DisplayRow(3), 4), &text_layout_details);
1156
1157 // Move up and down within first excerpt
1158 assert_eq!(
1159 up(
1160 &snapshot,
1161 DisplayPoint::new(DisplayRow(3), 4),
1162 SelectionGoal::HorizontalPosition(col_4_x.0),
1163 false,
1164 &text_layout_details
1165 ),
1166 (
1167 DisplayPoint::new(DisplayRow(2), 3),
1168 SelectionGoal::HorizontalPosition(col_4_x.0)
1169 ),
1170 );
1171 assert_eq!(
1172 down(
1173 &snapshot,
1174 DisplayPoint::new(DisplayRow(2), 3),
1175 SelectionGoal::HorizontalPosition(col_4_x.0),
1176 false,
1177 &text_layout_details
1178 ),
1179 (
1180 DisplayPoint::new(DisplayRow(3), 4),
1181 SelectionGoal::HorizontalPosition(col_4_x.0)
1182 ),
1183 );
1184
1185 let col_5_x = snapshot
1186 .x_for_display_point(DisplayPoint::new(DisplayRow(6), 5), &text_layout_details);
1187
1188 // Move up and down across second excerpt's header
1189 assert_eq!(
1190 up(
1191 &snapshot,
1192 DisplayPoint::new(DisplayRow(6), 5),
1193 SelectionGoal::HorizontalPosition(col_5_x.0),
1194 false,
1195 &text_layout_details
1196 ),
1197 (
1198 DisplayPoint::new(DisplayRow(3), 4),
1199 SelectionGoal::HorizontalPosition(col_5_x.0)
1200 ),
1201 );
1202 assert_eq!(
1203 down(
1204 &snapshot,
1205 DisplayPoint::new(DisplayRow(3), 4),
1206 SelectionGoal::HorizontalPosition(col_5_x.0),
1207 false,
1208 &text_layout_details
1209 ),
1210 (
1211 DisplayPoint::new(DisplayRow(6), 5),
1212 SelectionGoal::HorizontalPosition(col_5_x.0)
1213 ),
1214 );
1215
1216 let max_point_x = snapshot
1217 .x_for_display_point(DisplayPoint::new(DisplayRow(7), 2), &text_layout_details);
1218
1219 // Can't move down off the end, and attempting to do so leaves the selection goal unchanged
1220 assert_eq!(
1221 down(
1222 &snapshot,
1223 DisplayPoint::new(DisplayRow(7), 0),
1224 SelectionGoal::HorizontalPosition(0.0),
1225 false,
1226 &text_layout_details
1227 ),
1228 (
1229 DisplayPoint::new(DisplayRow(7), 2),
1230 SelectionGoal::HorizontalPosition(0.0)
1231 ),
1232 );
1233 assert_eq!(
1234 down(
1235 &snapshot,
1236 DisplayPoint::new(DisplayRow(7), 2),
1237 SelectionGoal::HorizontalPosition(max_point_x.0),
1238 false,
1239 &text_layout_details
1240 ),
1241 (
1242 DisplayPoint::new(DisplayRow(7), 2),
1243 SelectionGoal::HorizontalPosition(max_point_x.0)
1244 ),
1245 );
1246 });
1247 }
1248
1249 fn init_test(cx: &mut gpui::App) {
1250 let settings_store = SettingsStore::test(cx);
1251 cx.set_global(settings_store);
1252 workspace::init_settings(cx);
1253 theme::init(theme::LoadThemes::JustBase, cx);
1254 language::init(cx);
1255 crate::init(cx);
1256 Project::init_settings(cx);
1257 }
1258}