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