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::{
6 char_kind, scroll::ScrollAnchor, CharKind, DisplayRow, EditorStyle, RowExt, ToOffset, ToPoint,
7};
8use gpui::{px, Pixels, WindowTextSystem};
9use language::Point;
10use multi_buffer::{MultiBufferRow, MultiBufferSnapshot};
11use serde::Deserialize;
12
13use std::{ops::Range, sync::Arc};
14
15/// Defines search strategy for items in `movement` module.
16/// `FindRange::SingeLine` only looks for a match on a single line at a time, whereas
17/// `FindRange::MultiLine` keeps going until the end of a string.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
19pub enum FindRange {
20 SingleLine,
21 MultiLine,
22}
23
24/// TextLayoutDetails encompasses everything we need to move vertically
25/// taking into account variable width characters.
26pub struct TextLayoutDetails {
27 pub(crate) text_system: Arc<WindowTextSystem>,
28 pub(crate) editor_style: EditorStyle,
29 pub(crate) rem_size: Pixels,
30 pub scroll_anchor: ScrollAnchor,
31 pub visible_rows: Option<f32>,
32 pub vertical_scroll_margin: f32,
33}
34
35/// Returns a column to the left of the current point, wrapping
36/// to the previous line if that point is at the start of line.
37pub fn left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
38 if point.column() > 0 {
39 *point.column_mut() -= 1;
40 } else if point.row().0 > 0 {
41 *point.row_mut() -= 1;
42 *point.column_mut() = map.line_len(point.row());
43 }
44 map.clip_point(point, Bias::Left)
45}
46
47/// Returns a column to the left of the current point, doing nothing if
48/// that point is already at the start of line.
49pub fn saturating_left(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
50 if point.column() > 0 {
51 *point.column_mut() -= 1;
52 } else if point.column() == 0 {
53 // If the current sofr_wrap mode is used, the column corresponding to the display is 0,
54 // which does not necessarily mean that the actual beginning of a paragraph
55 if map.display_point_to_fold_point(point, Bias::Left).column() > 0 {
56 return left(map, point);
57 }
58 }
59 map.clip_point(point, Bias::Left)
60}
61
62/// Returns a column to the right of the current point, doing nothing
63// if that point is at the end of the line.
64pub fn right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
65 if point.column() < map.line_len(point.row()) {
66 *point.column_mut() += 1;
67 } else if point.row() < map.max_point().row() {
68 *point.row_mut() += 1;
69 *point.column_mut() = 0;
70 }
71 map.clip_point(point, Bias::Right)
72}
73
74/// Returns a column to the right of the current point, not performing any wrapping
75/// if that point is already at the end of line.
76pub fn saturating_right(map: &DisplaySnapshot, mut point: DisplayPoint) -> DisplayPoint {
77 *point.column_mut() += 1;
78 map.clip_point(point, Bias::Right)
79}
80
81/// Returns a display point for the preceding displayed line (which might be a soft-wrapped line).
82pub fn up(
83 map: &DisplaySnapshot,
84 start: DisplayPoint,
85 goal: SelectionGoal,
86 preserve_column_at_start: bool,
87 text_layout_details: &TextLayoutDetails,
88) -> (DisplayPoint, SelectionGoal) {
89 up_by_rows(
90 map,
91 start,
92 1,
93 goal,
94 preserve_column_at_start,
95 text_layout_details,
96 )
97}
98
99/// Returns a display point for the next displayed line (which might be a soft-wrapped line).
100pub fn down(
101 map: &DisplaySnapshot,
102 start: DisplayPoint,
103 goal: SelectionGoal,
104 preserve_column_at_end: bool,
105 text_layout_details: &TextLayoutDetails,
106) -> (DisplayPoint, SelectionGoal) {
107 down_by_rows(
108 map,
109 start,
110 1,
111 goal,
112 preserve_column_at_end,
113 text_layout_details,
114 )
115}
116
117pub(crate) fn up_by_rows(
118 map: &DisplaySnapshot,
119 start: DisplayPoint,
120 row_count: u32,
121 goal: SelectionGoal,
122 preserve_column_at_start: bool,
123 text_layout_details: &TextLayoutDetails,
124) -> (DisplayPoint, SelectionGoal) {
125 let mut goal_x = match goal {
126 SelectionGoal::HorizontalPosition(x) => x.into(),
127 SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
128 SelectionGoal::HorizontalRange { end, .. } => end.into(),
129 _ => map.x_for_display_point(start, text_layout_details),
130 };
131
132 let prev_row = DisplayRow(start.row().0.saturating_sub(row_count));
133 let mut point = map.clip_point(
134 DisplayPoint::new(prev_row, map.line_len(prev_row)),
135 Bias::Left,
136 );
137 if point.row() < start.row() {
138 *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
139 } else if preserve_column_at_start {
140 return (start, goal);
141 } else {
142 point = DisplayPoint::new(DisplayRow(0), 0);
143 goal_x = px(0.);
144 }
145
146 let mut clipped_point = map.clip_point(point, Bias::Left);
147 if clipped_point.row() < point.row() {
148 clipped_point = map.clip_point(point, Bias::Right);
149 }
150 (
151 clipped_point,
152 SelectionGoal::HorizontalPosition(goal_x.into()),
153 )
154}
155
156pub(crate) fn down_by_rows(
157 map: &DisplaySnapshot,
158 start: DisplayPoint,
159 row_count: u32,
160 goal: SelectionGoal,
161 preserve_column_at_end: bool,
162 text_layout_details: &TextLayoutDetails,
163) -> (DisplayPoint, SelectionGoal) {
164 let mut goal_x = match goal {
165 SelectionGoal::HorizontalPosition(x) => x.into(),
166 SelectionGoal::WrappedHorizontalPosition((_, x)) => x.into(),
167 SelectionGoal::HorizontalRange { end, .. } => end.into(),
168 _ => map.x_for_display_point(start, text_layout_details),
169 };
170
171 let new_row = DisplayRow(start.row().0 + row_count);
172 let mut point = map.clip_point(DisplayPoint::new(new_row, 0), Bias::Right);
173 if point.row() > start.row() {
174 *point.column_mut() = map.display_column_for_x(point.row(), goal_x, text_layout_details)
175 } else if preserve_column_at_end {
176 return (start, goal);
177 } else {
178 point = map.max_point();
179 goal_x = map.x_for_display_point(point, text_layout_details)
180 }
181
182 let mut clipped_point = map.clip_point(point, Bias::Right);
183 if clipped_point.row() > point.row() {
184 clipped_point = map.clip_point(point, Bias::Left);
185 }
186 (
187 clipped_point,
188 SelectionGoal::HorizontalPosition(goal_x.into()),
189 )
190}
191
192/// Returns a position of the start of line.
193/// If `stop_at_soft_boundaries` is true, the returned position is that of the
194/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
195/// Otherwise it's always going to be the start of a logical line.
196pub fn line_beginning(
197 map: &DisplaySnapshot,
198 display_point: DisplayPoint,
199 stop_at_soft_boundaries: bool,
200) -> DisplayPoint {
201 let point = display_point.to_point(map);
202 let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
203 let line_start = map.prev_line_boundary(point).1;
204
205 if stop_at_soft_boundaries && display_point != soft_line_start {
206 soft_line_start
207 } else {
208 line_start
209 }
210}
211
212/// Returns the last indented position on a given line.
213/// If `stop_at_soft_boundaries` is true, the returned [`DisplayPoint`] is that of a
214/// displayed line (e.g. if there's soft wrap it's gonna be returned),
215/// otherwise it's always going to be a start of a logical line.
216pub fn indented_line_beginning(
217 map: &DisplaySnapshot,
218 display_point: DisplayPoint,
219 stop_at_soft_boundaries: bool,
220) -> DisplayPoint {
221 let point = display_point.to_point(map);
222 let soft_line_start = map.clip_point(DisplayPoint::new(display_point.row(), 0), Bias::Right);
223 let indent_start = Point::new(
224 point.row,
225 map.buffer_snapshot
226 .indent_size_for_line(MultiBufferRow(point.row))
227 .len,
228 )
229 .to_display_point(map);
230 let line_start = map.prev_line_boundary(point).1;
231
232 if stop_at_soft_boundaries && soft_line_start > indent_start && display_point != soft_line_start
233 {
234 soft_line_start
235 } else if stop_at_soft_boundaries && display_point != indent_start {
236 indent_start
237 } else {
238 line_start
239 }
240}
241
242/// Returns a position of the end of line.
243
244/// If `stop_at_soft_boundaries` is true, the returned position is that of the
245/// displayed line (e.g. it could actually be in the middle of a text line if that line is soft-wrapped).
246/// Otherwise it's always going to be the end of a logical line.
247pub fn line_end(
248 map: &DisplaySnapshot,
249 display_point: DisplayPoint,
250 stop_at_soft_boundaries: bool,
251) -> DisplayPoint {
252 let soft_line_end = map.clip_point(
253 DisplayPoint::new(display_point.row(), map.line_len(display_point.row())),
254 Bias::Left,
255 );
256 if stop_at_soft_boundaries && display_point != soft_line_end {
257 soft_line_end
258 } else {
259 map.next_line_boundary(display_point.to_point(map)).1
260 }
261}
262
263/// Returns a position of the previous word boundary, where a word character is defined as either
264/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
265pub fn previous_word_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
266 let raw_point = point.to_point(map);
267 let scope = map.buffer_snapshot.language_scope_at(raw_point);
268
269 find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
270 (char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace())
271 || left == '\n'
272 })
273}
274
275/// Returns a position of the previous subword boundary, where a subword is defined as a run of
276/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
277/// lowerspace characters and uppercase characters.
278pub fn previous_subword_start(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
279 let raw_point = point.to_point(map);
280 let scope = map.buffer_snapshot.language_scope_at(raw_point);
281
282 find_preceding_boundary_display_point(map, point, FindRange::MultiLine, |left, right| {
283 let is_word_start =
284 char_kind(&scope, left) != char_kind(&scope, right) && !right.is_whitespace();
285 let is_subword_start =
286 left == '_' && right != '_' || left.is_lowercase() && right.is_uppercase();
287 is_word_start || is_subword_start || left == '\n'
288 })
289}
290
291/// Returns a position of the next word boundary, where a word character is defined as either
292/// uppercase letter, lowercase letter, '_' character or language-specific word character (like '-' in CSS).
293pub fn next_word_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
294 let raw_point = point.to_point(map);
295 let scope = map.buffer_snapshot.language_scope_at(raw_point);
296
297 find_boundary(map, point, FindRange::MultiLine, |left, right| {
298 (char_kind(&scope, left) != char_kind(&scope, right) && !left.is_whitespace())
299 || right == '\n'
300 })
301}
302
303/// Returns a position of the next subword boundary, where a subword is defined as a run of
304/// word characters of the same "subkind" - where subcharacter kinds are '_' character,
305/// lowerspace characters and uppercase characters.
306pub fn next_subword_end(map: &DisplaySnapshot, point: DisplayPoint) -> DisplayPoint {
307 let raw_point = point.to_point(map);
308 let scope = map.buffer_snapshot.language_scope_at(raw_point);
309
310 find_boundary(map, point, FindRange::MultiLine, |left, right| {
311 let is_word_end =
312 (char_kind(&scope, left) != char_kind(&scope, right)) && !left.is_whitespace();
313 let is_subword_end =
314 left != '_' && right == '_' || left.is_lowercase() && right.is_uppercase();
315 is_word_end || is_subword_end || right == '\n'
316 })
317}
318
319/// Returns a position of the start of the current paragraph, where a paragraph
320/// is defined as a run of non-blank lines.
321pub fn start_of_paragraph(
322 map: &DisplaySnapshot,
323 display_point: DisplayPoint,
324 mut count: usize,
325) -> DisplayPoint {
326 let point = display_point.to_point(map);
327 if point.row == 0 {
328 return DisplayPoint::zero();
329 }
330
331 let mut found_non_blank_line = false;
332 for row in (0..point.row + 1).rev() {
333 let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
334 if found_non_blank_line && blank {
335 if count <= 1 {
336 return Point::new(row, 0).to_display_point(map);
337 }
338 count -= 1;
339 found_non_blank_line = false;
340 }
341
342 found_non_blank_line |= !blank;
343 }
344
345 DisplayPoint::zero()
346}
347
348/// Returns a position of the end of the current paragraph, where a paragraph
349/// is defined as a run of non-blank lines.
350pub fn end_of_paragraph(
351 map: &DisplaySnapshot,
352 display_point: DisplayPoint,
353 mut count: usize,
354) -> DisplayPoint {
355 let point = display_point.to_point(map);
356 if point.row == map.max_buffer_row().0 {
357 return map.max_point();
358 }
359
360 let mut found_non_blank_line = false;
361 for row in point.row..map.max_buffer_row().next_row().0 {
362 let blank = map.buffer_snapshot.is_line_blank(MultiBufferRow(row));
363 if found_non_blank_line && blank {
364 if count <= 1 {
365 return Point::new(row, 0).to_display_point(map);
366 }
367 count -= 1;
368 found_non_blank_line = false;
369 }
370
371 found_non_blank_line |= !blank;
372 }
373
374 map.max_point()
375}
376
377/// Scans for a boundary preceding the given start point `from` until a boundary is found,
378/// indicated by the given predicate returning true.
379/// The predicate is called with the character to the left and right of the candidate boundary location.
380/// 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.
381pub fn find_preceding_boundary_point(
382 buffer_snapshot: &MultiBufferSnapshot,
383 from: Point,
384 find_range: FindRange,
385 mut is_boundary: impl FnMut(char, char) -> bool,
386) -> Point {
387 let mut prev_ch = None;
388 let mut offset = from.to_offset(&buffer_snapshot);
389
390 for ch in buffer_snapshot.reversed_chars_at(offset) {
391 if find_range == FindRange::SingleLine && ch == '\n' {
392 break;
393 }
394 if let Some(prev_ch) = prev_ch {
395 if is_boundary(ch, prev_ch) {
396 break;
397 }
398 }
399
400 offset -= ch.len_utf8();
401 prev_ch = Some(ch);
402 }
403
404 offset.to_point(&buffer_snapshot)
405}
406
407/// Scans for a boundary preceding the given start point `from` until a boundary is found,
408/// indicated by the given predicate returning true.
409/// The predicate is called with the character to the left and right of the candidate boundary location.
410/// 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.
411pub fn find_preceding_boundary_display_point(
412 map: &DisplaySnapshot,
413 from: DisplayPoint,
414 find_range: FindRange,
415 is_boundary: impl FnMut(char, char) -> bool,
416) -> DisplayPoint {
417 let result = find_preceding_boundary_point(
418 &map.buffer_snapshot,
419 from.to_point(map),
420 find_range,
421 is_boundary,
422 );
423 map.clip_point(result.to_display_point(map), Bias::Left)
424}
425
426/// Scans for a boundary following the given start point until a boundary is found, indicated by the
427/// given predicate returning true. The predicate is called with the character to the left and right
428/// of the candidate boundary location, and will be called with `\n` characters indicating the start
429/// or end of a line. The function supports optionally returning the point just before the boundary
430/// is found via return_point_before_boundary.
431pub fn find_boundary_point(
432 map: &DisplaySnapshot,
433 from: DisplayPoint,
434 find_range: FindRange,
435 mut is_boundary: impl FnMut(char, char) -> bool,
436 return_point_before_boundary: bool,
437) -> DisplayPoint {
438 let mut offset = from.to_offset(&map, Bias::Right);
439 let mut prev_offset = offset;
440 let mut prev_ch = None;
441
442 for ch in map.buffer_snapshot.chars_at(offset) {
443 if find_range == FindRange::SingleLine && ch == '\n' {
444 break;
445 }
446 if let Some(prev_ch) = prev_ch {
447 if is_boundary(prev_ch, ch) {
448 if return_point_before_boundary {
449 return map.clip_point(prev_offset.to_display_point(map), Bias::Right);
450 } else {
451 break;
452 }
453 }
454 }
455 prev_offset = offset;
456 offset += ch.len_utf8();
457 prev_ch = Some(ch);
458 }
459 map.clip_point(offset.to_display_point(map), Bias::Right)
460}
461
462pub fn find_boundary(
463 map: &DisplaySnapshot,
464 from: DisplayPoint,
465 find_range: FindRange,
466 is_boundary: impl FnMut(char, char) -> bool,
467) -> DisplayPoint {
468 return find_boundary_point(map, from, find_range, is_boundary, false);
469}
470
471pub fn find_boundary_exclusive(
472 map: &DisplaySnapshot,
473 from: DisplayPoint,
474 find_range: FindRange,
475 is_boundary: impl FnMut(char, char) -> bool,
476) -> DisplayPoint {
477 return find_boundary_point(map, from, find_range, is_boundary, true);
478}
479
480/// Returns an iterator over the characters following a given offset in the [`DisplaySnapshot`].
481/// The returned value also contains a range of the start/end of a returned character in
482/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
483pub fn chars_after(
484 map: &DisplaySnapshot,
485 mut offset: usize,
486) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
487 map.buffer_snapshot.chars_at(offset).map(move |ch| {
488 let before = offset;
489 offset = offset + ch.len_utf8();
490 (ch, before..offset)
491 })
492}
493
494/// Returns a reverse iterator over the characters following a given offset in the [`DisplaySnapshot`].
495/// The returned value also contains a range of the start/end of a returned character in
496/// the [`DisplaySnapshot`]. The offsets are relative to the start of a buffer.
497pub fn chars_before(
498 map: &DisplaySnapshot,
499 mut offset: usize,
500) -> impl Iterator<Item = (char, Range<usize>)> + '_ {
501 map.buffer_snapshot
502 .reversed_chars_at(offset)
503 .map(move |ch| {
504 let after = offset;
505 offset = offset - ch.len_utf8();
506 (ch, offset..after)
507 })
508}
509
510pub(crate) fn is_inside_word(map: &DisplaySnapshot, point: DisplayPoint) -> bool {
511 let raw_point = point.to_point(map);
512 let scope = map.buffer_snapshot.language_scope_at(raw_point);
513 let ix = map.clip_point(point, Bias::Left).to_offset(map, Bias::Left);
514 let text = &map.buffer_snapshot;
515 let next_char_kind = text.chars_at(ix).next().map(|c| char_kind(&scope, c));
516 let prev_char_kind = text
517 .reversed_chars_at(ix)
518 .next()
519 .map(|c| char_kind(&scope, c));
520 prev_char_kind.zip(next_char_kind) == Some((CharKind::Word, CharKind::Word))
521}
522
523pub(crate) fn surrounding_word(
524 map: &DisplaySnapshot,
525 position: DisplayPoint,
526) -> Range<DisplayPoint> {
527 let position = map
528 .clip_point(position, Bias::Left)
529 .to_offset(map, Bias::Left);
530 let (range, _) = map.buffer_snapshot.surrounding_word(position);
531 let start = range
532 .start
533 .to_point(&map.buffer_snapshot)
534 .to_display_point(map);
535 let end = range
536 .end
537 .to_point(&map.buffer_snapshot)
538 .to_display_point(map);
539 start..end
540}
541
542/// Returns a list of lines (represented as a [`DisplayPoint`] range) contained
543/// within a passed range.
544///
545/// The line ranges are **always* going to be in bounds of a requested range, which means that
546/// the first and the last lines might not necessarily represent the
547/// full range of a logical line (as their `.start`/`.end` values are clipped to those of a passed in range).
548pub fn split_display_range_by_lines(
549 map: &DisplaySnapshot,
550 range: Range<DisplayPoint>,
551) -> Vec<Range<DisplayPoint>> {
552 let mut result = Vec::new();
553
554 let mut start = range.start;
555 // Loop over all the covered rows until the one containing the range end
556 for row in range.start.row().0..range.end.row().0 {
557 let row_end_column = map.line_len(DisplayRow(row));
558 let end = map.clip_point(
559 DisplayPoint::new(DisplayRow(row), row_end_column),
560 Bias::Left,
561 );
562 if start != end {
563 result.push(start..end);
564 }
565 start = map.clip_point(DisplayPoint::new(DisplayRow(row + 1), 0), Bias::Left);
566 }
567
568 // Add the final range from the start of the last end to the original range end.
569 result.push(start..range.end);
570
571 result
572}
573
574#[cfg(test)]
575mod tests {
576 use super::*;
577 use crate::{
578 display_map::Inlay,
579 test::{editor_test_context::EditorTestContext, marked_display_snapshot},
580 Buffer, DisplayMap, DisplayRow, ExcerptRange, InlayId, MultiBuffer,
581 };
582 use gpui::{font, Context as _};
583 use language::Capability;
584 use project::Project;
585 use settings::SettingsStore;
586 use util::post_inc;
587
588 #[gpui::test]
589 fn test_previous_word_start(cx: &mut gpui::AppContext) {
590 init_test(cx);
591
592 fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
593 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
594 assert_eq!(
595 previous_word_start(&snapshot, display_points[1]),
596 display_points[0]
597 );
598 }
599
600 assert("\nˇ ˇlorem", cx);
601 assert("ˇ\nˇ lorem", cx);
602 assert(" ˇloremˇ", cx);
603 assert("ˇ ˇlorem", cx);
604 assert(" ˇlorˇem", cx);
605 assert("\nlorem\nˇ ˇipsum", cx);
606 assert("\n\nˇ\nˇ", cx);
607 assert(" ˇlorem ˇipsum", cx);
608 assert("loremˇ-ˇipsum", cx);
609 assert("loremˇ-#$@ˇipsum", cx);
610 assert("ˇlorem_ˇipsum", cx);
611 assert(" ˇdefγˇ", cx);
612 assert(" ˇbcΔˇ", cx);
613 assert(" abˇ——ˇcd", cx);
614 }
615
616 #[gpui::test]
617 fn test_previous_subword_start(cx: &mut gpui::AppContext) {
618 init_test(cx);
619
620 fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
621 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
622 assert_eq!(
623 previous_subword_start(&snapshot, display_points[1]),
624 display_points[0]
625 );
626 }
627
628 // Subword boundaries are respected
629 assert("lorem_ˇipˇsum", cx);
630 assert("lorem_ˇipsumˇ", cx);
631 assert("ˇlorem_ˇipsum", cx);
632 assert("lorem_ˇipsum_ˇdolor", cx);
633 assert("loremˇIpˇsum", cx);
634 assert("loremˇIpsumˇ", cx);
635
636 // Word boundaries are still respected
637 assert("\nˇ ˇlorem", cx);
638 assert(" ˇloremˇ", cx);
639 assert(" ˇlorˇem", cx);
640 assert("\nlorem\nˇ ˇipsum", cx);
641 assert("\n\nˇ\nˇ", cx);
642 assert(" ˇlorem ˇipsum", cx);
643 assert("loremˇ-ˇipsum", cx);
644 assert("loremˇ-#$@ˇipsum", cx);
645 assert(" ˇdefγˇ", cx);
646 assert(" bcˇΔˇ", cx);
647 assert(" ˇbcδˇ", cx);
648 assert(" abˇ——ˇcd", cx);
649 }
650
651 #[gpui::test]
652 fn test_find_preceding_boundary(cx: &mut gpui::AppContext) {
653 init_test(cx);
654
655 fn assert(
656 marked_text: &str,
657 cx: &mut gpui::AppContext,
658 is_boundary: impl FnMut(char, char) -> bool,
659 ) {
660 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
661 assert_eq!(
662 find_preceding_boundary_display_point(
663 &snapshot,
664 display_points[1],
665 FindRange::MultiLine,
666 is_boundary
667 ),
668 display_points[0]
669 );
670 }
671
672 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
673 left == 'c' && right == 'd'
674 });
675 assert("abcdef\nˇgh\nijˇk", cx, |left, right| {
676 left == '\n' && right == 'g'
677 });
678 let mut line_count = 0;
679 assert("abcdef\nˇgh\nijˇk", cx, |left, _| {
680 if left == '\n' {
681 line_count += 1;
682 line_count == 2
683 } else {
684 false
685 }
686 });
687 }
688
689 #[gpui::test]
690 fn test_find_preceding_boundary_with_inlays(cx: &mut gpui::AppContext) {
691 init_test(cx);
692
693 let input_text = "abcdefghijklmnopqrstuvwxys";
694 let font = font("Helvetica");
695 let font_size = px(14.0);
696 let buffer = MultiBuffer::build_simple(input_text, cx);
697 let buffer_snapshot = buffer.read(cx).snapshot(cx);
698 let display_map =
699 cx.new_model(|cx| DisplayMap::new(buffer, font, font_size, None, 1, 1, cx));
700
701 // add all kinds of inlays between two word boundaries: we should be able to cross them all, when looking for another boundary
702 let mut id = 0;
703 let inlays = (0..buffer_snapshot.len())
704 .flat_map(|offset| {
705 [
706 Inlay {
707 id: InlayId::Suggestion(post_inc(&mut id)),
708 position: buffer_snapshot.anchor_at(offset, Bias::Left),
709 text: "test".into(),
710 },
711 Inlay {
712 id: InlayId::Suggestion(post_inc(&mut id)),
713 position: buffer_snapshot.anchor_at(offset, Bias::Right),
714 text: "test".into(),
715 },
716 Inlay {
717 id: InlayId::Hint(post_inc(&mut id)),
718 position: buffer_snapshot.anchor_at(offset, Bias::Left),
719 text: "test".into(),
720 },
721 Inlay {
722 id: InlayId::Hint(post_inc(&mut id)),
723 position: buffer_snapshot.anchor_at(offset, Bias::Right),
724 text: "test".into(),
725 },
726 ]
727 })
728 .collect();
729 let snapshot = display_map.update(cx, |map, cx| {
730 map.splice_inlays(Vec::new(), inlays, cx);
731 map.snapshot(cx)
732 });
733
734 assert_eq!(
735 find_preceding_boundary_display_point(
736 &snapshot,
737 buffer_snapshot.len().to_display_point(&snapshot),
738 FindRange::MultiLine,
739 |left, _| left == 'e',
740 ),
741 snapshot
742 .buffer_snapshot
743 .offset_to_point(5)
744 .to_display_point(&snapshot),
745 "Should not stop at inlays when looking for boundaries"
746 );
747 }
748
749 #[gpui::test]
750 fn test_next_word_end(cx: &mut gpui::AppContext) {
751 init_test(cx);
752
753 fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
754 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
755 assert_eq!(
756 next_word_end(&snapshot, display_points[0]),
757 display_points[1]
758 );
759 }
760
761 assert("\nˇ loremˇ", cx);
762 assert(" ˇloremˇ", cx);
763 assert(" lorˇemˇ", cx);
764 assert(" loremˇ ˇ\nipsum\n", cx);
765 assert("\nˇ\nˇ\n\n", cx);
766 assert("loremˇ ipsumˇ ", cx);
767 assert("loremˇ-ˇipsum", cx);
768 assert("loremˇ#$@-ˇipsum", cx);
769 assert("loremˇ_ipsumˇ", cx);
770 assert(" ˇbcΔˇ", cx);
771 assert(" abˇ——ˇcd", cx);
772 }
773
774 #[gpui::test]
775 fn test_next_subword_end(cx: &mut gpui::AppContext) {
776 init_test(cx);
777
778 fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
779 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
780 assert_eq!(
781 next_subword_end(&snapshot, display_points[0]),
782 display_points[1]
783 );
784 }
785
786 // Subword boundaries are respected
787 assert("loˇremˇ_ipsum", cx);
788 assert("ˇloremˇ_ipsum", cx);
789 assert("loremˇ_ipsumˇ", cx);
790 assert("loremˇ_ipsumˇ_dolor", cx);
791 assert("loˇremˇIpsum", cx);
792 assert("loremˇIpsumˇDolor", cx);
793
794 // Word boundaries are still respected
795 assert("\nˇ loremˇ", cx);
796 assert(" ˇloremˇ", cx);
797 assert(" lorˇemˇ", cx);
798 assert(" loremˇ ˇ\nipsum\n", cx);
799 assert("\nˇ\nˇ\n\n", cx);
800 assert("loremˇ ipsumˇ ", cx);
801 assert("loremˇ-ˇipsum", cx);
802 assert("loremˇ#$@-ˇipsum", cx);
803 assert("loremˇ_ipsumˇ", cx);
804 assert(" ˇbcˇΔ", cx);
805 assert(" abˇ——ˇcd", cx);
806 }
807
808 #[gpui::test]
809 fn test_find_boundary(cx: &mut gpui::AppContext) {
810 init_test(cx);
811
812 fn assert(
813 marked_text: &str,
814 cx: &mut gpui::AppContext,
815 is_boundary: impl FnMut(char, char) -> bool,
816 ) {
817 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
818 assert_eq!(
819 find_boundary(
820 &snapshot,
821 display_points[0],
822 FindRange::MultiLine,
823 is_boundary,
824 ),
825 display_points[1]
826 );
827 }
828
829 assert("abcˇdef\ngh\nijˇk", cx, |left, right| {
830 left == 'j' && right == 'k'
831 });
832 assert("abˇcdef\ngh\nˇijk", cx, |left, right| {
833 left == '\n' && right == 'i'
834 });
835 let mut line_count = 0;
836 assert("abcˇdef\ngh\nˇijk", cx, |left, _| {
837 if left == '\n' {
838 line_count += 1;
839 line_count == 2
840 } else {
841 false
842 }
843 });
844 }
845
846 #[gpui::test]
847 fn test_surrounding_word(cx: &mut gpui::AppContext) {
848 init_test(cx);
849
850 fn assert(marked_text: &str, cx: &mut gpui::AppContext) {
851 let (snapshot, display_points) = marked_display_snapshot(marked_text, cx);
852 assert_eq!(
853 surrounding_word(&snapshot, display_points[1]),
854 display_points[0]..display_points[2],
855 "{}",
856 marked_text
857 );
858 }
859
860 assert("ˇˇloremˇ ipsum", cx);
861 assert("ˇloˇremˇ ipsum", cx);
862 assert("ˇloremˇˇ ipsum", cx);
863 assert("loremˇ ˇ ˇipsum", cx);
864 assert("lorem\nˇˇˇ\nipsum", cx);
865 assert("lorem\nˇˇipsumˇ", cx);
866 assert("loremˇ,ˇˇ ipsum", cx);
867 assert("ˇloremˇˇ, ipsum", cx);
868 }
869
870 #[gpui::test]
871 async fn test_move_up_and_down_with_excerpts(cx: &mut gpui::TestAppContext) {
872 cx.update(|cx| {
873 init_test(cx);
874 });
875
876 let mut cx = EditorTestContext::new(cx).await;
877 let editor = cx.editor.clone();
878 let window = cx.window;
879 _ = cx.update_window(window, |_, cx| {
880 let text_layout_details =
881 editor.update(cx, |editor, cx| editor.text_layout_details(cx));
882
883 let font = font("Helvetica");
884
885 let buffer = cx.new_model(|cx| Buffer::local("abc\ndefg\nhijkl\nmn", cx));
886 let multibuffer = cx.new_model(|cx| {
887 let mut multibuffer = MultiBuffer::new(0, Capability::ReadWrite);
888 multibuffer.push_excerpts(
889 buffer.clone(),
890 [
891 ExcerptRange {
892 context: Point::new(0, 0)..Point::new(1, 4),
893 primary: None,
894 },
895 ExcerptRange {
896 context: Point::new(2, 0)..Point::new(3, 2),
897 primary: None,
898 },
899 ],
900 cx,
901 );
902 multibuffer
903 });
904 let display_map =
905 cx.new_model(|cx| DisplayMap::new(multibuffer, font, px(14.0), None, 2, 2, cx));
906 let snapshot = display_map.update(cx, |map, cx| map.snapshot(cx));
907
908 assert_eq!(snapshot.text(), "\n\nabc\ndefg\n\n\nhijkl\nmn");
909
910 let col_2_x = snapshot
911 .x_for_display_point(DisplayPoint::new(DisplayRow(2), 2), &text_layout_details);
912
913 // Can't move up into the first excerpt's header
914 assert_eq!(
915 up(
916 &snapshot,
917 DisplayPoint::new(DisplayRow(2), 2),
918 SelectionGoal::HorizontalPosition(col_2_x.0),
919 false,
920 &text_layout_details
921 ),
922 (
923 DisplayPoint::new(DisplayRow(2), 0),
924 SelectionGoal::HorizontalPosition(0.0)
925 ),
926 );
927 assert_eq!(
928 up(
929 &snapshot,
930 DisplayPoint::new(DisplayRow(2), 0),
931 SelectionGoal::None,
932 false,
933 &text_layout_details
934 ),
935 (
936 DisplayPoint::new(DisplayRow(2), 0),
937 SelectionGoal::HorizontalPosition(0.0)
938 ),
939 );
940
941 let col_4_x = snapshot
942 .x_for_display_point(DisplayPoint::new(DisplayRow(3), 4), &text_layout_details);
943
944 // Move up and down within first excerpt
945 assert_eq!(
946 up(
947 &snapshot,
948 DisplayPoint::new(DisplayRow(3), 4),
949 SelectionGoal::HorizontalPosition(col_4_x.0),
950 false,
951 &text_layout_details
952 ),
953 (
954 DisplayPoint::new(DisplayRow(2), 3),
955 SelectionGoal::HorizontalPosition(col_4_x.0)
956 ),
957 );
958 assert_eq!(
959 down(
960 &snapshot,
961 DisplayPoint::new(DisplayRow(2), 3),
962 SelectionGoal::HorizontalPosition(col_4_x.0),
963 false,
964 &text_layout_details
965 ),
966 (
967 DisplayPoint::new(DisplayRow(3), 4),
968 SelectionGoal::HorizontalPosition(col_4_x.0)
969 ),
970 );
971
972 let col_5_x = snapshot
973 .x_for_display_point(DisplayPoint::new(DisplayRow(6), 5), &text_layout_details);
974
975 // Move up and down across second excerpt's header
976 assert_eq!(
977 up(
978 &snapshot,
979 DisplayPoint::new(DisplayRow(6), 5),
980 SelectionGoal::HorizontalPosition(col_5_x.0),
981 false,
982 &text_layout_details
983 ),
984 (
985 DisplayPoint::new(DisplayRow(3), 4),
986 SelectionGoal::HorizontalPosition(col_5_x.0)
987 ),
988 );
989 assert_eq!(
990 down(
991 &snapshot,
992 DisplayPoint::new(DisplayRow(3), 4),
993 SelectionGoal::HorizontalPosition(col_5_x.0),
994 false,
995 &text_layout_details
996 ),
997 (
998 DisplayPoint::new(DisplayRow(6), 5),
999 SelectionGoal::HorizontalPosition(col_5_x.0)
1000 ),
1001 );
1002
1003 let max_point_x = snapshot
1004 .x_for_display_point(DisplayPoint::new(DisplayRow(7), 2), &text_layout_details);
1005
1006 // Can't move down off the end
1007 assert_eq!(
1008 down(
1009 &snapshot,
1010 DisplayPoint::new(DisplayRow(7), 0),
1011 SelectionGoal::HorizontalPosition(0.0),
1012 false,
1013 &text_layout_details
1014 ),
1015 (
1016 DisplayPoint::new(DisplayRow(7), 2),
1017 SelectionGoal::HorizontalPosition(max_point_x.0)
1018 ),
1019 );
1020 assert_eq!(
1021 down(
1022 &snapshot,
1023 DisplayPoint::new(DisplayRow(7), 2),
1024 SelectionGoal::HorizontalPosition(max_point_x.0),
1025 false,
1026 &text_layout_details
1027 ),
1028 (
1029 DisplayPoint::new(DisplayRow(7), 2),
1030 SelectionGoal::HorizontalPosition(max_point_x.0)
1031 ),
1032 );
1033 });
1034 }
1035
1036 fn init_test(cx: &mut gpui::AppContext) {
1037 let settings_store = SettingsStore::test(cx);
1038 cx.set_global(settings_store);
1039 theme::init(theme::LoadThemes::JustBase, cx);
1040 language::init(cx);
1041 crate::init(cx);
1042 Project::init_settings(cx);
1043 }
1044}