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