Debian Codegraph @

helix-core/src/selection.rs

raw symbols SCIP
1 //! Selections are the primary editing construct. Even cursors are
2 //! defined as a selection range.
3 //!
4 //! All positioning is done via `char` offsets into the buffer.
5 use crate::{
6 graphemes::{
7 ensure_grapheme_boundary_next, ensure_grapheme_boundary_prev, next_grapheme_boundary,
8 prev_grapheme_boundary,
9 },
10 line_ending::get_line_ending,
11 movement::Direction,
12 tree_sitter::Node,
13 Assoc, ChangeSet, RopeSlice,
14 };
15 use helix_stdx::range::is_subset;
16 use helix_stdx::rope::{self, RopeSliceExt};
17 use smallvec::{smallvec, SmallVec};
18 use std::{borrow::Cow, iter, slice};
19
20 /// A single selection range.
21 ///
22 /// A range consists of an "anchor" and "head" position in
23 /// the text. The head is the part that the user moves when
24 /// directly extending a selection. The head and anchor
25 /// can be in any order, or even share the same position.
26 ///
27 /// The anchor and head positions use gap indexing, meaning
28 /// that their indices represent the gaps *between* `char`s
29 /// rather than the `char`s themselves. For example, 1
30 /// represents the position between the first and second `char`.
31 ///
32 /// Below are some examples of `Range` configurations.
33 /// The anchor and head indices are shown as "(anchor, head)"
34 /// tuples, followed by example text with "[" and "]" symbols
35 /// representing the anchor and head positions:
36 ///
37 /// - (0, 3): `[Som]e text`.
38 /// - (3, 0): `]Som[e text`.
39 /// - (2, 7): `So[me te]xt`.
40 /// - (1, 1): `S[]ome text`.
41 ///
42 /// Ranges are considered to be inclusive on the left and
43 /// exclusive on the right, regardless of anchor-head ordering.
44 /// This means, for example, that non-zero-width ranges that
45 /// are directly adjacent, sharing an edge, do not overlap.
46 /// However, a zero-width range will overlap with the shared
47 /// left-edge of another range.
48 ///
49 /// By convention, user-facing ranges are considered to have
50 /// a block cursor on the head-side of the range that spans a
51 /// single grapheme inward from the range's edge. There are a
52 /// variety of helper methods on `Range` for working in terms of
53 /// that block cursor, all of which have `cursor` in their name.
54 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55 pub struct Range {
56 /// The anchor of the range: the side that doesn't move when extending.
57 pub anchor: usize,
58 /// The head of the range, moved when extending.
59 pub head: usize,
60 /// The previous visual offset (softwrapped lines and columns) from
61 /// the start of the line
62 pub old_visual_position: Option<(u32, u32)>,
63 }
64
65 impl Range {
66 pub fn new(anchor: usize, head: usize) -> Self {
67 Self {
68 anchor,
69 head,
70 old_visual_position: None,
71 }
72 }
73
74 pub fn point(head: usize) -> Self {
75 Self::new(head, head)
76 }
77
78 pub fn from_node(node: Node, text: RopeSlice, direction: Direction) -> Self {
79 let from = text.byte_to_char(node.start_byte() as usize);
80 let to = text.byte_to_char(node.end_byte() as usize);
81 Range::new(from, to).with_direction(direction)
82 }
83
84 /// Start of the range.
85 #[inline]
86 #[must_use]
87 pub fn from(&self) -> usize {
88 std::cmp::min(self.anchor, self.head)
89 }
90
91 /// End of the range.
92 #[inline]
93 #[must_use]
94 pub fn to(&self) -> usize {
95 std::cmp::max(self.anchor, self.head)
96 }
97
98 /// Total length of the range.
99 #[inline]
100 #[must_use]
101 pub fn len(&self) -> usize {
102 self.to() - self.from()
103 }
104
105 /// The (inclusive) range of lines that the range overlaps.
106 #[inline]
107 #[must_use]
108 pub fn line_range(&self, text: RopeSlice) -> (usize, usize) {
109 let from = self.from();
110 let to = if self.is_empty() {
111 self.to()
112 } else {
113 prev_grapheme_boundary(text, self.to()).max(from)
114 };
115
116 (text.char_to_line(from), text.char_to_line(to))
117 }
118
119 /// `true` when head and anchor are at the same position.
120 #[inline]
121 pub fn is_empty(&self) -> bool {
122 self.anchor == self.head
123 }
124
125 /// `Direction::Backward` when head < anchor.
126 /// `Direction::Forward` otherwise.
127 #[inline]
128 #[must_use]
129 pub fn direction(&self) -> Direction {
130 if self.head < self.anchor {
131 Direction::Backward
132 } else {
133 Direction::Forward
134 }
135 }
136
137 /// Flips the direction of the selection
138 pub fn flip(&self) -> Self {
139 Self {
140 anchor: self.head,
141 head: self.anchor,
142 old_visual_position: self.old_visual_position,
143 }
144 }
145
146 /// Returns the selection if it goes in the direction of `direction`,
147 /// flipping the selection otherwise.
148 pub fn with_direction(self, direction: Direction) -> Self {
149 if self.direction() == direction {
150 self
151 } else {
152 self.flip()
153 }
154 }
155
156 /// Check two ranges for overlap.
157 #[must_use]
158 pub fn overlaps(&self, other: &Self) -> bool {
159 // To my eye, it's non-obvious why this works, but I arrived
160 // at it after transforming the slower version that explicitly
161 // enumerated more cases. The unit tests are thorough.
162 self.from() == other.from() || (self.to() > other.from() && other.to() > self.from())
163 }
164
165 #[inline]
166 pub fn contains_range(&self, other: &Self) -> bool {
167 self.from() <= other.from() && self.to() >= other.to()
168 }
169
170 pub fn contains(&self, pos: usize) -> bool {
171 self.from() <= pos && pos < self.to()
172 }
173
174 /// Map a range through a set of changes. Returns a new range representing
175 /// the same position after the changes are applied. Note that this
176 /// function runs in O(N) (N is number of changes) and can therefore
177 /// cause performance problems if run for a large number of ranges as the
178 /// complexity is then O(MN) (for multicuror M=N usually). Instead use
179 /// [Selection::map] or [ChangeSet::update_positions].
180 pub fn map(mut self, changes: &ChangeSet) -> Self {
181 use std::cmp::Ordering;
182 if changes.is_empty() {
183 return self;
184 }
185
186 let positions_to_map = match self.anchor.cmp(&self.head) {
187 Ordering::Equal => [
188 (&mut self.anchor, Assoc::AfterSticky),
189 (&mut self.head, Assoc::AfterSticky),
190 ],
191 Ordering::Less => [
192 (&mut self.anchor, Assoc::AfterSticky),
193 (&mut self.head, Assoc::BeforeSticky),
194 ],
195 Ordering::Greater => [
196 (&mut self.head, Assoc::AfterSticky),
197 (&mut self.anchor, Assoc::BeforeSticky),
198 ],
199 };
200 changes.update_positions(positions_to_map.into_iter());
201 self.old_visual_position = None;
202 self
203 }
204
205 /// Extend the range to cover at least `from` `to`.
206 #[must_use]
207 pub fn extend(&self, from: usize, to: usize) -> Self {
208 debug_assert!(from <= to);
209
210 if self.anchor <= self.head {
211 Self {
212 anchor: self.anchor.min(from),
213 head: self.head.max(to),
214 old_visual_position: None,
215 }
216 } else {
217 Self {
218 anchor: self.anchor.max(to),
219 head: self.head.min(from),
220 old_visual_position: None,
221 }
222 }
223 }
224
225 /// Returns a range that encompasses both input ranges.
226 ///
227 /// This is like `extend()`, but tries to negotiate the
228 /// anchor/head ordering between the two input ranges.
229 #[must_use]
230 pub fn merge(&self, other: Self) -> Self {
231 if self.anchor > self.head && other.anchor > other.head {
232 Range {
233 anchor: self.anchor.max(other.anchor),
234 head: self.head.min(other.head),
235 old_visual_position: None,
236 }
237 } else {
238 Range {
239 anchor: self.from().min(other.from()),
240 head: self.to().max(other.to()),
241 old_visual_position: None,
242 }
243 }
244 }
245
246 // groupAt
247
248 /// Returns the text inside this range given the text of the whole buffer.
249 ///
250 /// The returned `Cow` is a reference if the range of text is inside a single
251 /// chunk of the rope. Otherwise a copy of the text is returned. Consider
252 /// using `slice` instead if you do not need a `Cow` or `String` to avoid copying.
253 #[inline]
254 pub fn fragment<'a, 'b: 'a>(&'a self, text: RopeSlice<'b>) -> Cow<'b, str> {
255 self.slice(text).into()
256 }
257
258 /// Returns the text inside this range given the text of the whole buffer.
259 ///
260 /// The returned value is a reference to the passed slice. This method never
261 /// copies any contents.
262 #[inline]
263 pub fn slice<'a, 'b: 'a>(&'a self, text: RopeSlice<'b>) -> RopeSlice<'b> {
264 text.slice(self.from()..self.to())
265 }
266
267 //--------------------------------
268 // Alignment methods.
269
270 /// Compute a possibly new range from this range, with its ends
271 /// shifted as needed to align with grapheme boundaries.
272 ///
273 /// Zero-width ranges will always stay zero-width, and non-zero-width
274 /// ranges will never collapse to zero-width.
275 #[must_use]
276 pub fn grapheme_aligned(&self, slice: RopeSlice) -> Self {
277 use std::cmp::Ordering;
278 let (new_anchor, new_head) = match self.anchor.cmp(&self.head) {
279 Ordering::Equal => {
280 let pos = ensure_grapheme_boundary_prev(slice, self.anchor);
281 (pos, pos)
282 }
283 Ordering::Less => (
284 ensure_grapheme_boundary_prev(slice, self.anchor),
285 ensure_grapheme_boundary_next(slice, self.head),
286 ),
287 Ordering::Greater => (
288 ensure_grapheme_boundary_next(slice, self.anchor),
289 ensure_grapheme_boundary_prev(slice, self.head),
290 ),
291 };
292 Range {
293 anchor: new_anchor,
294 head: new_head,
295 old_visual_position: if new_anchor == self.anchor {
296 self.old_visual_position
297 } else {
298 None
299 },
300 }
301 }
302
303 /// Compute a possibly new range from this range, attempting to ensure
304 /// a minimum range width of 1 char by shifting the head in the forward
305 /// direction as needed.
306 ///
307 /// This method will never shift the anchor, and will only shift the
308 /// head in the forward direction. Therefore, this method can fail
309 /// at ensuring the minimum width if and only if the passed range is
310 /// both zero-width and at the end of the `RopeSlice`.
311 ///
312 /// If the input range is grapheme-boundary aligned, the returned range
313 /// will also be. Specifically, if the head needs to shift to achieve
314 /// the minimum width, it will shift to the next grapheme boundary.
315 #[must_use]
316 #[inline]
317 pub fn min_width_1(&self, slice: RopeSlice) -> Self {
318 if self.anchor == self.head {
319 Range {
320 anchor: self.anchor,
321 head: next_grapheme_boundary(slice, self.head),
322 old_visual_position: self.old_visual_position,
323 }
324 } else {
325 *self
326 }
327 }
328
329 //--------------------------------
330 // Block-cursor methods.
331
332 /// Gets the left-side position of the block cursor.
333 #[must_use]
334 #[inline]
335 pub fn cursor(self, text: RopeSlice) -> usize {
336 if self.head > self.anchor {
337 prev_grapheme_boundary(text, self.head)
338 } else {
339 self.head
340 }
341 }
342
343 /// Puts the left side of the block cursor at `char_idx`, optionally extending.
344 ///
345 /// This follows "1-width" semantics, and therefore does a combination of anchor
346 /// and head moves to behave as if both the front and back of the range are 1-width
347 /// blocks
348 ///
349 /// This method assumes that the range and `char_idx` are already properly
350 /// grapheme-aligned.
351 #[must_use]
352 #[inline]
353 pub fn put_cursor(self, text: RopeSlice, char_idx: usize, extend: bool) -> Range {
354 if extend {
355 let anchor = if self.head >= self.anchor && char_idx < self.anchor {
356 next_grapheme_boundary(text, self.anchor)
357 } else if self.head < self.anchor && char_idx >= self.anchor {
358 prev_grapheme_boundary(text, self.anchor)
359 } else {
360 self.anchor
361 };
362
363 if anchor <= char_idx {
364 Range::new(anchor, next_grapheme_boundary(text, char_idx))
365 } else {
366 Range::new(anchor, char_idx)
367 }
368 } else {
369 Range::point(char_idx)
370 }
371 }
372
373 /// The line number that the block-cursor is on.
374 #[inline]
375 #[must_use]
376 pub fn cursor_line(&self, text: RopeSlice) -> usize {
377 text.char_to_line(self.cursor(text))
378 }
379
380 /// Returns true if this Range covers a single grapheme in the given text
381 pub fn is_single_grapheme(&self, doc: RopeSlice) -> bool {
382 let mut graphemes = doc.slice(self.from()..self.to()).graphemes();
383 let first = graphemes.next();
384 let second = graphemes.next();
385 first.is_some() && second.is_none()
386 }
387
388 /// Converts this char range into an in order byte range, discarding
389 /// direction.
390 pub fn into_byte_range(&self, text: RopeSlice) -> (usize, usize) {
391 (text.char_to_byte(self.from()), text.char_to_byte(self.to()))
392 }
393 }
394
395 impl From<(usize, usize)> for Range {
396 fn from((anchor, head): (usize, usize)) -> Self {
397 Self {
398 anchor,
399 head,
400 old_visual_position: None,
401 }
402 }
403 }
404
405 impl From<Range> for helix_stdx::Range {
406 fn from(range: Range) -> Self {
407 Self {
408 start: range.from(),
409 end: range.to(),
410 }
411 }
412 }
413
414 /// A selection consists of one or more selection ranges.
415 /// invariant: A selection can never be empty (always contains at least primary range).
416 #[derive(Debug, Clone, PartialEq, Eq)]
417 pub struct Selection {
418 ranges: SmallVec<[Range; 1]>,
419 primary_index: usize,
420 }
421
422 #[allow(clippy::len_without_is_empty)] // a Selection is never empty
423 impl Selection {
424 // eq
425
426 #[inline]
427 #[must_use]
428 pub fn primary(&self) -> Range {
429 self.ranges[self.primary_index]
430 }
431
432 #[inline]
433 #[must_use]
434 pub fn primary_mut(&mut self) -> &mut Range {
435 &mut self.ranges[self.primary_index]
436 }
437
438 /// Ensure selection containing only the primary selection.
439 pub fn into_single(self) -> Self {
440 if self.ranges.len() == 1 {
441 self
442 } else {
443 Self {
444 ranges: smallvec![self.ranges[self.primary_index]],
445 primary_index: 0,
446 }
447 }
448 }
449
450 /// Adds a new range to the selection and makes it the primary range.
451 pub fn push(mut self, range: Range) -> Self {
452 self.ranges.push(range);
453 self.set_primary_index(self.ranges().len() - 1);
454 self.normalize()
455 }
456
457 /// Removes a range from the selection.
458 pub fn remove(mut self, index: usize) -> Self {
459 assert!(
460 self.ranges.len() > 1,
461 "can't remove the last range from a selection!"
462 );
463
464 self.ranges.remove(index);
465 if index < self.primary_index || self.primary_index == self.ranges.len() {
466 self.primary_index -= 1;
467 }
468 self
469 }
470
471 /// Replace a range in the selection with a new range.
472 pub fn replace(mut self, index: usize, range: Range) -> Self {
473 self.ranges[index] = range;
474 self.normalize()
475 }
476
477 /// Map selections over a set of changes. Useful for adjusting the selection position after
478 /// applying changes to a document.
479 pub fn map(self, changes: &ChangeSet) -> Self {
480 self.map_no_normalize(changes).normalize()
481 }
482
483 /// Map selections over a set of changes. Useful for adjusting the selection position after
484 /// applying changes to a document. Doesn't normalize the selection
485 pub fn map_no_normalize(mut self, changes: &ChangeSet) -> Self {
486 if changes.is_empty() {
487 return self;
488 }
489
490 let positions_to_map = self.ranges.iter_mut().flat_map(|range| {
491 use std::cmp::Ordering;
492 range.old_visual_position = None;
493 match range.anchor.cmp(&range.head) {
494 Ordering::Equal => [
495 (&mut range.anchor, Assoc::AfterSticky),
496 (&mut range.head, Assoc::AfterSticky),
497 ],
498 Ordering::Less => [
499 (&mut range.anchor, Assoc::AfterSticky),
500 (&mut range.head, Assoc::BeforeSticky),
501 ],
502 Ordering::Greater => [
503 (&mut range.head, Assoc::AfterSticky),
504 (&mut range.anchor, Assoc::BeforeSticky),
505 ],
506 }
507 });
508 changes.update_positions(positions_to_map);
509 self
510 }
511
512 pub fn ranges(&self) -> &[Range] {
513 &self.ranges
514 }
515
516 /// Returns an iterator over the line ranges of each range in the selection.
517 ///
518 /// Adjacent and overlapping line ranges of the [Range]s in the selection are merged.
519 pub fn line_ranges<'a>(&'a self, text: RopeSlice<'a>) -> LineRangeIter<'a> {
520 LineRangeIter {
521 ranges: self.ranges.iter().peekable(),
522 text,
523 }
524 }
525
526 pub fn range_bounds(&self) -> impl Iterator<Item = helix_stdx::Range> + '_ {
527 self.ranges.iter().map(|&range| range.into())
528 }
529
530 pub fn primary_index(&self) -> usize {
531 self.primary_index
532 }
533
534 pub fn set_primary_index(&mut self, idx: usize) {
535 assert!(idx < self.ranges.len());
536 self.primary_index = idx;
537 }
538
539 #[must_use]
540 /// Constructs a selection holding a single range.
541 pub fn single(anchor: usize, head: usize) -> Self {
542 Self {
543 ranges: smallvec![Range {
544 anchor,
545 head,
546 old_visual_position: None
547 }],
548 primary_index: 0,
549 }
550 }
551
552 /// Constructs a selection holding a single cursor.
553 pub fn point(pos: usize) -> Self {
554 Self::single(pos, pos)
555 }
556
557 /// Normalizes a `Selection`.
558 ///
559 /// Ranges are sorted by [Range::from], with overlapping ranges merged.
560 fn normalize(mut self) -> Self {
561 if self.len() < 2 {
562 return self;
563 }
564 let mut primary = self.ranges[self.primary_index];
565 self.ranges.sort_unstable_by_key(Range::from);
566
567 self.ranges.dedup_by(|curr_range, prev_range| {
568 if prev_range.overlaps(curr_range) {
569 let new_range = curr_range.merge(*prev_range);
570 if prev_range == &primary || curr_range == &primary {
571 primary = new_range;
572 }
573 *prev_range = new_range;
574 true
575 } else {
576 false
577 }
578 });
579
580 self.primary_index = self
581 .ranges
582 .iter()
583 .position(|&range| range == primary)
584 .unwrap();
585
586 self
587 }
588
589 /// Replaces ranges with one spanning from first to last range.
590 pub fn merge_ranges(self) -> Self {
591 let first = self.ranges.first().unwrap();
592 let last = self.ranges.last().unwrap();
593 Selection::new(smallvec![first.merge(*last)], 0)
594 }
595
596 /// Merges all ranges that are consecutive.
597 pub fn merge_consecutive_ranges(mut self) -> Self {
598 let mut primary = self.ranges[self.primary_index];
599
600 self.ranges.dedup_by(|curr_range, prev_range| {
601 if prev_range.to() == curr_range.from() {
602 let new_range = curr_range.merge(*prev_range);
603 if prev_range == &primary || curr_range == &primary {
604 primary = new_range;
605 }
606 *prev_range = new_range;
607 true
608 } else {
609 false
610 }
611 });
612
613 self.primary_index = self
614 .ranges
615 .iter()
616 .position(|&range| range == primary)
617 .unwrap();
618
619 self
620 }
621
622 #[must_use]
623 pub fn new(ranges: SmallVec<[Range; 1]>, primary_index: usize) -> Self {
624 assert!(!ranges.is_empty());
625 debug_assert!(primary_index < ranges.len());
626
627 let selection = Self {
628 ranges,
629 primary_index,
630 };
631
632 selection.normalize()
633 }
634
635 /// Takes a closure and maps each `Range` over the closure.
636 pub fn transform<F>(mut self, mut f: F) -> Self
637 where
638 F: FnMut(Range) -> Range,
639 {
640 for range in self.ranges.iter_mut() {
641 *range = f(*range)
642 }
643 self.normalize()
644 }
645
646 /// Takes a closure and maps each `Range` over the closure to multiple `Range`s.
647 pub fn transform_iter<F, I>(mut self, f: F) -> Self
648 where
649 F: FnMut(Range) -> I,
650 I: Iterator<Item = Range>,
651 {
652 self.ranges = self.ranges.into_iter().flat_map(f).collect();
653 self.normalize()
654 }
655
656 // Ensures the selection adheres to the following invariants:
657 // 1. All ranges are grapheme aligned.
658 // 2. All ranges are at least 1 character wide, unless at the
659 // very end of the document.
660 // 3. Ranges are non-overlapping.
661 // 4. Ranges are sorted by their position in the text.
662 pub fn ensure_invariants(self, text: RopeSlice) -> Self {
663 self.transform(|r| r.min_width_1(text).grapheme_aligned(text))
664 .normalize()
665 }
666
667 /// Transforms the selection into all of the left-side head positions,
668 /// using block-cursor semantics.
669 pub fn cursors(self, text: RopeSlice) -> Self {
670 self.transform(|range| Range::point(range.cursor(text)))
671 }
672
673 pub fn fragments<'a>(
674 &'a self,
675 text: RopeSlice<'a>,
676 ) -> impl DoubleEndedIterator<Item = Cow<'a, str>> + ExactSizeIterator<Item = Cow<'a, str>>
677 {
678 self.ranges.iter().map(move |range| range.fragment(text))
679 }
680
681 pub fn slices<'a>(
682 &'a self,
683 text: RopeSlice<'a>,
684 ) -> impl DoubleEndedIterator<Item = RopeSlice<'a>> + ExactSizeIterator<Item = RopeSlice<'a>> + 'a
685 {
686 self.ranges.iter().map(move |range| range.slice(text))
687 }
688
689 #[inline(always)]
690 pub fn iter(&self) -> std::slice::Iter<'_, Range> {
691 self.ranges.iter()
692 }
693
694 #[inline(always)]
695 pub fn len(&self) -> usize {
696 self.ranges.len()
697 }
698
699 /// returns true if self ⊇ other
700 pub fn contains(&self, other: &Selection) -> bool {
701 is_subset::<true>(self.range_bounds(), other.range_bounds())
702 }
703 }
704
705 impl<'a> IntoIterator for &'a Selection {
706 type Item = &'a Range;
707 type IntoIter = std::slice::Iter<'a, Range>;
708
709 fn into_iter(self) -> std::slice::Iter<'a, Range> {
710 self.ranges().iter()
711 }
712 }
713
714 impl IntoIterator for Selection {
715 type Item = Range;
716 type IntoIter = smallvec::IntoIter<[Range; 1]>;
717
718 fn into_iter(self) -> smallvec::IntoIter<[Range; 1]> {
719 self.ranges.into_iter()
720 }
721 }
722
723 impl FromIterator<Range> for Selection {
724 fn from_iter<T: IntoIterator<Item = Range>>(ranges: T) -> Self {
725 Self::new(ranges.into_iter().collect(), 0)
726 }
727 }
728
729 impl From<Range> for Selection {
730 fn from(range: Range) -> Self {
731 Self {
732 ranges: smallvec![range],
733 primary_index: 0,
734 }
735 }
736 }
737
738 pub struct LineRangeIter<'a> {
739 ranges: iter::Peekable<slice::Iter<'a, Range>>,
740 text: RopeSlice<'a>,
741 }
742
743 impl Iterator for LineRangeIter<'_> {
744 type Item = (usize, usize);
745
746 fn next(&mut self) -> Option<Self::Item> {
747 let (start, mut end) = self.ranges.next()?.line_range(self.text);
748 while let Some((next_start, next_end)) =
749 self.ranges.peek().map(|range| range.line_range(self.text))
750 {
751 // Merge overlapping and adjacent ranges.
752 // This subtraction cannot underflow because the ranges are sorted.
753 if next_start - end <= 1 {
754 end = next_end;
755 self.ranges.next();
756 } else {
757 break;
758 }
759 }
760
761 Some((start, end))
762 }
763 }
764
765 // TODO: checkSelection -> check if valid for doc length && sorted
766
767 pub fn keep_or_remove_matches(
768 text: RopeSlice,
769 selection: &Selection,
770 regex: &rope::Regex,
771 remove: bool,
772 ) -> Option<Selection> {
773 let result: SmallVec<_> = selection
774 .iter()
775 .filter(|range| regex.is_match(text.regex_input_at(range.from()..range.to())) ^ remove)
776 .copied()
777 .collect();
778
779 // TODO: figure out a new primary index
780 if !result.is_empty() {
781 return Some(Selection::new(result, 0));
782 }
783 None
784 }
785
786 // TODO: support to split on capture #N instead of whole match
787 pub fn select_on_matches(
788 text: RopeSlice,
789 selection: &Selection,
790 regex: &rope::Regex,
791 ) -> Option<Selection> {
792 let mut result = SmallVec::with_capacity(selection.len());
793
794 for sel in selection {
795 for mat in regex.find_iter(text.regex_input_at(sel.from()..sel.to())) {
796 // TODO: retain range direction
797
798 let start = text.byte_to_char(mat.start());
799 let end = text.byte_to_char(mat.end());
800
801 let range = Range::new(start, end);
802 // Make sure the match is not right outside of the selection.
803 // These invalid matches can come from using RegEx anchors like `^`, `$`
804 if range != Range::point(sel.to()) {
805 result.push(range);
806 }
807 }
808 }
809
810 // TODO: figure out a new primary index
811 if !result.is_empty() {
812 return Some(Selection::new(result, 0));
813 }
814
815 None
816 }
817
818 pub fn split_on_newline(text: RopeSlice, selection: &Selection) -> Selection {
819 let mut result = SmallVec::with_capacity(selection.len());
820
821 for sel in selection {
822 // Special case: zero-width selection.
823 if sel.from() == sel.to() {
824 result.push(*sel);
825 continue;
826 }
827
828 let sel_start = sel.from();
829 let sel_end = sel.to();
830
831 let mut start = sel_start;
832
833 for line in sel.slice(text).lines() {
834 let Some(line_ending) = get_line_ending(&line) else {
835 break;
836 };
837 let line_end = start + line.len_chars();
838 // TODO: retain range direction
839 result.push(Range::new(start, line_end - line_ending.len_chars()));
840 start = line_end;
841 }
842
843 if start < sel_end {
844 result.push(Range::new(start, sel_end));
845 }
846 }
847
848 // TODO: figure out a new primary index
849 Selection::new(result, 0)
850 }
851
852 pub fn split_on_matches(text: RopeSlice, selection: &Selection, regex: &rope::Regex) -> Selection {
853 let mut result = SmallVec::with_capacity(selection.len());
854
855 for sel in selection {
856 // Special case: zero-width selection.
857 if sel.from() == sel.to() {
858 result.push(*sel);
859 continue;
860 }
861
862 let sel_start = sel.from();
863 let sel_end = sel.to();
864 let mut start = sel_start;
865
866 for mat in regex.find_iter(text.regex_input_at(sel_start..sel_end)) {
867 // TODO: retain range direction
868 let end = text.byte_to_char(mat.start());
869 result.push(Range::new(start, end));
870 start = text.byte_to_char(mat.end());
871 }
872
873 if start < sel_end {
874 result.push(Range::new(start, sel_end));
875 }
876 }
877
878 // TODO: figure out a new primary index
879 Selection::new(result, 0)
880 }
881
882 #[cfg(test)]
883 mod test {
884 use super::*;
885 use crate::Rope;
886
887 #[test]
888 #[should_panic]
889 fn test_new_empty() {
890 let _ = Selection::new(smallvec![], 0);
891 }
892
893 #[test]
894 fn test_create_normalizes_and_merges() {
895 let sel = Selection::new(
896 smallvec![
897 Range::new(10, 12),
898 Range::new(6, 7),
899 Range::new(4, 5),
900 Range::new(3, 4),
901 Range::new(0, 6),
902 Range::new(7, 8),
903 Range::new(9, 13),
904 Range::new(13, 14),
905 ],
906 0,
907 );
908
909 let res = sel
910 .ranges
911 .into_iter()
912 .map(|range| format!("{}/{}", range.anchor, range.head))
913 .collect::<Vec<String>>()
914 .join(",");
915
916 assert_eq!(res, "0/6,6/7,7/8,9/13,13/14");
917
918 // it correctly calculates a new primary index
919 let sel = Selection::new(
920 smallvec![Range::new(0, 2), Range::new(1, 5), Range::new(4, 7)],
921 2,
922 );
923
924 let res = sel
925 .ranges
926 .into_iter()
927 .map(|range| format!("{}/{}", range.anchor, range.head))
928 .collect::<Vec<String>>()
929 .join(",");
930
931 assert_eq!(res, "0/7");
932 assert_eq!(sel.primary_index, 0);
933 }
934
935 #[test]
936 fn test_create_merges_adjacent_points() {
937 let sel = Selection::new(
938 smallvec![
939 Range::new(10, 12),
940 Range::new(12, 12),
941 Range::new(12, 12),
942 Range::new(10, 10),
943 Range::new(8, 10),
944 ],
945 0,
946 );
947
948 let res = sel
949 .ranges
950 .into_iter()
951 .map(|range| format!("{}/{}", range.anchor, range.head))
952 .collect::<Vec<String>>()
953 .join(",");
954
955 assert_eq!(res, "8/10,10/12,12/12");
956 }
957
958 #[test]
959 fn test_contains() {
960 let range = Range::new(10, 12);
961
962 assert!(!range.contains(9));
963 assert!(range.contains(10));
964 assert!(range.contains(11));
965 assert!(!range.contains(12));
966 assert!(!range.contains(13));
967
968 let range = Range::new(9, 6);
969 assert!(!range.contains(9));
970 assert!(range.contains(7));
971 assert!(range.contains(6));
972 }
973
974 #[test]
975 fn test_overlaps() {
976 fn overlaps(a: (usize, usize), b: (usize, usize)) -> bool {
977 Range::new(a.0, a.1).overlaps(&Range::new(b.0, b.1))
978 }
979
980 // Two non-zero-width ranges, no overlap.
981 assert!(!overlaps((0, 3), (3, 6)));
982 assert!(!overlaps((0, 3), (6, 3)));
983 assert!(!overlaps((3, 0), (3, 6)));
984 assert!(!overlaps((3, 0), (6, 3)));
985 assert!(!overlaps((3, 6), (0, 3)));
986 assert!(!overlaps((3, 6), (3, 0)));
987 assert!(!overlaps((6, 3), (0, 3)));
988 assert!(!overlaps((6, 3), (3, 0)));
989
990 // Two non-zero-width ranges, overlap.
991 assert!(overlaps((0, 4), (3, 6)));
992 assert!(overlaps((0, 4), (6, 3)));
993 assert!(overlaps((4, 0), (3, 6)));
994 assert!(overlaps((4, 0), (6, 3)));
995 assert!(overlaps((3, 6), (0, 4)));
996 assert!(overlaps((3, 6), (4, 0)));
997 assert!(overlaps((6, 3), (0, 4)));
998 assert!(overlaps((6, 3), (4, 0)));
999
1000 // Zero-width and non-zero-width range, no overlap.
1001 assert!(!overlaps((0, 3), (3, 3)));
1002 assert!(!overlaps((3, 0), (3, 3)));
1003 assert!(!overlaps((3, 3), (0, 3)));
1004 assert!(!overlaps((3, 3), (3, 0)));
1005
1006 // Zero-width and non-zero-width range, overlap.
1007 assert!(overlaps((1, 4), (1, 1)));
1008 assert!(overlaps((4, 1), (1, 1)));
1009 assert!(overlaps((1, 1), (1, 4)));
1010 assert!(overlaps((1, 1), (4, 1)));
1011
1012 assert!(overlaps((1, 4), (3, 3)));
1013 assert!(overlaps((4, 1), (3, 3)));
1014 assert!(overlaps((3, 3), (1, 4)));
1015 assert!(overlaps((3, 3), (4, 1)));
1016
1017 // Two zero-width ranges, no overlap.
1018 assert!(!overlaps((0, 0), (1, 1)));
1019 assert!(!overlaps((1, 1), (0, 0)));
1020
1021 // Two zero-width ranges, overlap.
1022 assert!(overlaps((1, 1), (1, 1)));
1023 }
1024
1025 #[test]
1026 fn test_grapheme_aligned() {
1027 let r = Rope::from_str("\r\nHi\r\n");
1028 let s = r.slice(..);
1029
1030 // Zero-width.
1031 assert_eq!(Range::new(0, 0).grapheme_aligned(s), Range::new(0, 0));
1032 assert_eq!(Range::new(1, 1).grapheme_aligned(s), Range::new(0, 0));
1033 assert_eq!(Range::new(2, 2).grapheme_aligned(s), Range::new(2, 2));
1034 assert_eq!(Range::new(3, 3).grapheme_aligned(s), Range::new(3, 3));
1035 assert_eq!(Range::new(4, 4).grapheme_aligned(s), Range::new(4, 4));
1036 assert_eq!(Range::new(5, 5).grapheme_aligned(s), Range::new(4, 4));
1037 assert_eq!(Range::new(6, 6).grapheme_aligned(s), Range::new(6, 6));
1038
1039 // Forward.
1040 assert_eq!(Range::new(0, 1).grapheme_aligned(s), Range::new(0, 2));
1041 assert_eq!(Range::new(1, 2).grapheme_aligned(s), Range::new(0, 2));
1042 assert_eq!(Range::new(2, 3).grapheme_aligned(s), Range::new(2, 3));
1043 assert_eq!(Range::new(3, 4).grapheme_aligned(s), Range::new(3, 4));
1044 assert_eq!(Range::new(4, 5).grapheme_aligned(s), Range::new(4, 6));
1045 assert_eq!(Range::new(5, 6).grapheme_aligned(s), Range::new(4, 6));
1046
1047 assert_eq!(Range::new(0, 2).grapheme_aligned(s), Range::new(0, 2));
1048 assert_eq!(Range::new(1, 3).grapheme_aligned(s), Range::new(0, 3));
1049 assert_eq!(Range::new(2, 4).grapheme_aligned(s), Range::new(2, 4));
1050 assert_eq!(Range::new(3, 5).grapheme_aligned(s), Range::new(3, 6));
1051 assert_eq!(Range::new(4, 6).grapheme_aligned(s), Range::new(4, 6));
1052
1053 // Reverse.
1054 assert_eq!(Range::new(1, 0).grapheme_aligned(s), Range::new(2, 0));
1055 assert_eq!(Range::new(2, 1).grapheme_aligned(s), Range::new(2, 0));
1056 assert_eq!(Range::new(3, 2).grapheme_aligned(s), Range::new(3, 2));
1057 assert_eq!(Range::new(4, 3).grapheme_aligned(s), Range::new(4, 3));
1058 assert_eq!(Range::new(5, 4).grapheme_aligned(s), Range::new(6, 4));
1059 assert_eq!(Range::new(6, 5).grapheme_aligned(s), Range::new(6, 4));
1060
1061 assert_eq!(Range::new(2, 0).grapheme_aligned(s), Range::new(2, 0));
1062 assert_eq!(Range::new(3, 1).grapheme_aligned(s), Range::new(3, 0));
1063 assert_eq!(Range::new(4, 2).grapheme_aligned(s), Range::new(4, 2));
1064 assert_eq!(Range::new(5, 3).grapheme_aligned(s), Range::new(6, 3));
1065 assert_eq!(Range::new(6, 4).grapheme_aligned(s), Range::new(6, 4));
1066 }
1067
1068 #[test]
1069 fn test_min_width_1() {
1070 let r = Rope::from_str("\r\nHi\r\n");
1071 let s = r.slice(..);
1072
1073 // Zero-width.
1074 assert_eq!(Range::new(0, 0).min_width_1(s), Range::new(0, 2));
1075 assert_eq!(Range::new(1, 1).min_width_1(s), Range::new(1, 2));
1076 assert_eq!(Range::new(2, 2).min_width_1(s), Range::new(2, 3));
1077 assert_eq!(Range::new(3, 3).min_width_1(s), Range::new(3, 4));
1078 assert_eq!(Range::new(4, 4).min_width_1(s), Range::new(4, 6));
1079 assert_eq!(Range::new(5, 5).min_width_1(s), Range::new(5, 6));
1080 assert_eq!(Range::new(6, 6).min_width_1(s), Range::new(6, 6));
1081
1082 // Forward.
1083 assert_eq!(Range::new(0, 1).min_width_1(s), Range::new(0, 1));
1084 assert_eq!(Range::new(1, 2).min_width_1(s), Range::new(1, 2));
1085 assert_eq!(Range::new(2, 3).min_width_1(s), Range::new(2, 3));
1086 assert_eq!(Range::new(3, 4).min_width_1(s), Range::new(3, 4));
1087 assert_eq!(Range::new(4, 5).min_width_1(s), Range::new(4, 5));
1088 assert_eq!(Range::new(5, 6).min_width_1(s), Range::new(5, 6));
1089
1090 // Reverse.
1091 assert_eq!(Range::new(1, 0).min_width_1(s), Range::new(1, 0));
1092 assert_eq!(Range::new(2, 1).min_width_1(s), Range::new(2, 1));
1093 assert_eq!(Range::new(3, 2).min_width_1(s), Range::new(3, 2));
1094 assert_eq!(Range::new(4, 3).min_width_1(s), Range::new(4, 3));
1095 assert_eq!(Range::new(5, 4).min_width_1(s), Range::new(5, 4));
1096 assert_eq!(Range::new(6, 5).min_width_1(s), Range::new(6, 5));
1097 }
1098
1099 #[test]
1100 fn test_select_on_matches() {
1101 let r = Rope::from_str("Nobody expects the Spanish inquisition");
1102 let s = r.slice(..);
1103
1104 let selection = Selection::single(0, r.len_chars());
1105 assert_eq!(
1106 select_on_matches(s, &selection, &rope::Regex::new(r"[A-Z][a-z]*").unwrap()),
1107 Some(Selection::new(
1108 smallvec![Range::new(0, 6), Range::new(19, 26)],
1109 0
1110 ))
1111 );
1112
1113 let r = Rope::from_str("This\nString\n\ncontains multiple\nlines");
1114 let s = r.slice(..);
1115
1116 let start_of_line = rope::RegexBuilder::new()
1117 .syntax(rope::Config::new().multi_line(true))
1118 .build(r"^")
1119 .unwrap();
1120 let end_of_line = rope::RegexBuilder::new()
1121 .syntax(rope::Config::new().multi_line(true))
1122 .build(r"$")
1123 .unwrap();
1124
1125 // line without ending
1126 assert_eq!(
1127 select_on_matches(s, &Selection::single(0, 4), &start_of_line),
1128 Some(Selection::single(0, 0))
1129 );
1130 assert_eq!(
1131 select_on_matches(s, &Selection::single(0, 4), &end_of_line),
1132 None
1133 );
1134 // line with ending
1135 assert_eq!(
1136 select_on_matches(s, &Selection::single(0, 5), &start_of_line),
1137 Some(Selection::single(0, 0))
1138 );
1139 assert_eq!(
1140 select_on_matches(s, &Selection::single(0, 5), &end_of_line),
1141 Some(Selection::single(4, 4))
1142 );
1143 // line with start of next line
1144 assert_eq!(
1145 select_on_matches(s, &Selection::single(0, 6), &start_of_line),
1146 Some(Selection::new(
1147 smallvec![Range::point(0), Range::point(5)],
1148 0
1149 ))
1150 );
1151 assert_eq!(
1152 select_on_matches(s, &Selection::single(0, 6), &end_of_line),
1153 Some(Selection::single(4, 4))
1154 );
1155
1156 // multiple lines
1157 assert_eq!(
1158 select_on_matches(
1159 s,
1160 &Selection::single(0, s.len_chars()),
1161 &rope::RegexBuilder::new()
1162 .syntax(rope::Config::new().multi_line(true))
1163 .build(r"^[a-z ]*$")
1164 .unwrap()
1165 ),
1166 Some(Selection::new(
1167 smallvec![Range::point(12), Range::new(13, 30), Range::new(31, 36)],
1168 0
1169 ))
1170 );
1171 }
1172
1173 #[test]
1174 fn test_select_on_matches_crlf() {
1175 let r = Rope::from_str("This\r\nString\r\n\r\ncontains multiple\r\nlines");
1176 let s = r.slice(..);
1177
1178 let start_of_line = rope::RegexBuilder::new()
1179 .syntax(rope::Config::new().multi_line(true).crlf(true))
1180 .build(r"^")
1181 .unwrap();
1182 let end_of_line = rope::RegexBuilder::new()
1183 .syntax(rope::Config::new().multi_line(true).crlf(true))
1184 .build(r"$")
1185 .unwrap();
1186
1187 // line without ending
1188 assert_eq!(
1189 select_on_matches(s, &Selection::single(0, 4), &start_of_line),
1190 Some(Selection::single(0, 0))
1191 );
1192 assert_eq!(
1193 select_on_matches(s, &Selection::single(0, 4), &end_of_line),
1194 None
1195 );
1196 // line with ending
1197 assert_eq!(
1198 select_on_matches(s, &Selection::single(0, 5), &start_of_line),
1199 Some(Selection::single(0, 0))
1200 );
1201 assert_eq!(
1202 select_on_matches(s, &Selection::single(0, 5), &end_of_line),
1203 Some(Selection::single(4, 4))
1204 );
1205 // line with start of next line
1206 assert_eq!(
1207 select_on_matches(s, &Selection::single(0, 7), &start_of_line),
1208 Some(Selection::new(
1209 smallvec![Range::point(0), Range::point(6)],
1210 0
1211 ))
1212 );
1213 assert_eq!(
1214 select_on_matches(s, &Selection::single(0, 6), &end_of_line),
1215 Some(Selection::single(4, 4))
1216 );
1217
1218 // multiple lines
1219 assert_eq!(
1220 select_on_matches(
1221 s,
1222 &Selection::single(0, s.len_chars()),
1223 &rope::RegexBuilder::new()
1224 .syntax(rope::Config::new().multi_line(true).crlf(true))
1225 .build(r"^[a-z ]*$")
1226 .unwrap()
1227 ),
1228 Some(Selection::new(
1229 smallvec![Range::point(14), Range::new(16, 33), Range::new(35, 40)],
1230 0
1231 ))
1232 );
1233 }
1234
1235 #[test]
1236 fn test_line_range() {
1237 let r = Rope::from_str("\r\nHi\r\nthere!");
1238 let s = r.slice(..);
1239
1240 // Zero-width ranges.
1241 assert_eq!(Range::new(0, 0).line_range(s), (0, 0));
1242 assert_eq!(Range::new(1, 1).line_range(s), (0, 0));
1243 assert_eq!(Range::new(2, 2).line_range(s), (1, 1));
1244 assert_eq!(Range::new(3, 3).line_range(s), (1, 1));
1245
1246 // Forward ranges.
1247 assert_eq!(Range::new(0, 1).line_range(s), (0, 0));
1248 assert_eq!(Range::new(0, 2).line_range(s), (0, 0));
1249 assert_eq!(Range::new(0, 3).line_range(s), (0, 1));
1250 assert_eq!(Range::new(1, 2).line_range(s), (0, 0));
1251 assert_eq!(Range::new(2, 3).line_range(s), (1, 1));
1252 assert_eq!(Range::new(3, 8).line_range(s), (1, 2));
1253 assert_eq!(Range::new(0, 12).line_range(s), (0, 2));
1254
1255 // Reverse ranges.
1256 assert_eq!(Range::new(1, 0).line_range(s), (0, 0));
1257 assert_eq!(Range::new(2, 0).line_range(s), (0, 0));
1258 assert_eq!(Range::new(3, 0).line_range(s), (0, 1));
1259 assert_eq!(Range::new(2, 1).line_range(s), (0, 0));
1260 assert_eq!(Range::new(3, 2).line_range(s), (1, 1));
1261 assert_eq!(Range::new(8, 3).line_range(s), (1, 2));
1262 assert_eq!(Range::new(12, 0).line_range(s), (0, 2));
1263 }
1264
1265 #[test]
1266 fn selection_line_ranges() {
1267 let (text, selection) = crate::test::print(
1268 r#" L0
1269 #[|these]# line #(|ranges)# are #(|merged)# L1
1270 L2
1271 single one-line #(|range)# L3
1272 L4
1273 single #(|multiline L5
1274 range)# L6
1275 L7
1276 these #(|multiline L8
1277 ranges)# are #(|also L9
1278 merged)# L10
1279 L11
1280 adjacent #(|ranges)# L12
1281 are merged #(|the same way)# L13
1282 "#,
1283 );
1284 let rope = Rope::from_str(&text);
1285 assert_eq!(
1286 vec![(1, 1), (3, 3), (5, 6), (8, 10), (12, 13)],
1287 selection.line_ranges(rope.slice(..)).collect::<Vec<_>>(),
1288 );
1289 }
1290
1291 #[test]
1292 fn test_cursor() {
1293 let r = Rope::from_str("\r\nHi\r\nthere!");
1294 let s = r.slice(..);
1295
1296 // Zero-width ranges.
1297 assert_eq!(Range::new(0, 0).cursor(s), 0);
1298 assert_eq!(Range::new(2, 2).cursor(s), 2);
1299 assert_eq!(Range::new(3, 3).cursor(s), 3);
1300
1301 // Forward ranges.
1302 assert_eq!(Range::new(0, 2).cursor(s), 0);
1303 assert_eq!(Range::new(0, 3).cursor(s), 2);
1304 assert_eq!(Range::new(3, 6).cursor(s), 4);
1305
1306 // Reverse ranges.
1307 assert_eq!(Range::new(2, 0).cursor(s), 0);
1308 assert_eq!(Range::new(6, 2).cursor(s), 2);
1309 assert_eq!(Range::new(6, 3).cursor(s), 3);
1310 }
1311
1312 #[test]
1313 fn test_put_cursor() {
1314 let r = Rope::from_str("\r\nHi\r\nthere!");
1315 let s = r.slice(..);
1316
1317 // Zero-width ranges.
1318 assert_eq!(Range::new(0, 0).put_cursor(s, 0, true), Range::new(0, 2));
1319 assert_eq!(Range::new(0, 0).put_cursor(s, 2, true), Range::new(0, 3));
1320 assert_eq!(Range::new(2, 3).put_cursor(s, 4, true), Range::new(2, 6));
1321 assert_eq!(Range::new(2, 8).put_cursor(s, 4, true), Range::new(2, 6));
1322 assert_eq!(Range::new(8, 8).put_cursor(s, 4, true), Range::new(9, 4));
1323
1324 // Forward ranges.
1325 assert_eq!(Range::new(3, 6).put_cursor(s, 0, true), Range::new(4, 0));
1326 assert_eq!(Range::new(3, 6).put_cursor(s, 2, true), Range::new(4, 2));
1327 assert_eq!(Range::new(3, 6).put_cursor(s, 3, true), Range::new(3, 4));
1328 assert_eq!(Range::new(3, 6).put_cursor(s, 4, true), Range::new(3, 6));
1329 assert_eq!(Range::new(3, 6).put_cursor(s, 6, true), Range::new(3, 7));
1330 assert_eq!(Range::new(3, 6).put_cursor(s, 8, true), Range::new(3, 9));
1331
1332 // Reverse ranges.
1333 assert_eq!(Range::new(6, 3).put_cursor(s, 0, true), Range::new(6, 0));
1334 assert_eq!(Range::new(6, 3).put_cursor(s, 2, true), Range::new(6, 2));
1335 assert_eq!(Range::new(6, 3).put_cursor(s, 3, true), Range::new(6, 3));
1336 assert_eq!(Range::new(6, 3).put_cursor(s, 4, true), Range::new(6, 4));
1337 assert_eq!(Range::new(6, 3).put_cursor(s, 6, true), Range::new(4, 7));
1338 assert_eq!(Range::new(6, 3).put_cursor(s, 8, true), Range::new(4, 9));
1339 }
1340
1341 #[test]
1342 fn test_split_on_matches() {
1343 let text = Rope::from(" abcd efg wrs xyz 123 456");
1344
1345 let selection = Selection::new(smallvec![Range::new(0, 9), Range::new(11, 20),], 0);
1346
1347 let result = split_on_matches(
1348 text.slice(..),
1349 &selection,
1350 &rope::Regex::new(r"\s+").unwrap(),
1351 );
1352
1353 assert_eq!(
1354 result.ranges(),
1355 &[
1356 // TODO: rather than this behavior, maybe we want it
1357 // to be based on which side is the anchor?
1358 //
1359 // We get a leading zero-width range when there's
1360 // a leading match because ranges are inclusive on
1361 // the left. Imagine, for example, if the entire
1362 // selection range were matched: you'd still want
1363 // at least one range to remain after the split.
1364 Range::new(0, 0),
1365 Range::new(1, 5),
1366 Range::new(6, 9),
1367 Range::new(11, 13),
1368 Range::new(16, 19),
1369 // In contrast to the comment above, there is no
1370 // _trailing_ zero-width range despite the trailing
1371 // match, because ranges are exclusive on the right.
1372 ]
1373 );
1374
1375 assert_eq!(
1376 result.fragments(text.slice(..)).collect::<Vec<_>>(),
1377 &["", "abcd", "efg", "rs", "xyz"]
1378 );
1379 }
1380
1381 #[test]
1382 fn test_merge_consecutive_ranges() {
1383 let selection = Selection::new(
1384 smallvec![
1385 Range::new(0, 1),
1386 Range::new(1, 10),
1387 Range::new(15, 20),
1388 Range::new(25, 26),
1389 Range::new(26, 30)
1390 ],
1391 4,
1392 );
1393
1394 let result = selection.merge_consecutive_ranges();
1395
1396 assert_eq!(
1397 result.ranges(),
1398 &[Range::new(0, 10), Range::new(15, 20), Range::new(25, 30)]
1399 );
1400 assert_eq!(result.primary_index, 2);
1401
1402 let selection = Selection::new(smallvec![Range::new(0, 1)], 0);
1403 let result = selection.merge_consecutive_ranges();
1404
1405 assert_eq!(result.ranges(), &[Range::new(0, 1)]);
1406 assert_eq!(result.primary_index, 0);
1407
1408 let selection = Selection::new(
1409 smallvec![
1410 Range::new(0, 1),
1411 Range::new(1, 5),
1412 Range::new(5, 8),
1413 Range::new(8, 10),
1414 Range::new(10, 15),
1415 Range::new(18, 25)
1416 ],
1417 3,
1418 );
1419
1420 let result = selection.merge_consecutive_ranges();
1421
1422 assert_eq!(result.ranges(), &[Range::new(0, 15), Range::new(18, 25)]);
1423 assert_eq!(result.primary_index, 0);
1424 }
1425
1426 #[test]
1427 fn test_selection_contains() {
1428 fn contains(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
1429 let sela = Selection::new(a.iter().map(|a| Range::new(a.0, a.1)).collect(), 0);
1430 let selb = Selection::new(b.iter().map(|b| Range::new(b.0, b.1)).collect(), 0);
1431 sela.contains(&selb)
1432 }
1433
1434 // exact match
1435 assert!(contains(vec!((1, 1)), vec!((1, 1))));
1436
1437 // larger set contains smaller
1438 assert!(contains(vec!((1, 1), (2, 2), (3, 3)), vec!((2, 2))));
1439
1440 // multiple matches
1441 assert!(contains(vec!((1, 1), (2, 2)), vec!((1, 1), (2, 2))));
1442
1443 // smaller set can't contain bigger
1444 assert!(!contains(vec!((1, 1)), vec!((1, 1), (2, 2))));
1445
1446 assert!(contains(
1447 vec!((1, 1), (2, 4), (5, 6), (7, 9), (10, 13)),
1448 vec!((3, 4), (7, 9))
1449 ));
1450 assert!(!contains(vec!((1, 1), (5, 6)), vec!((1, 6))));
1451
1452 // multiple ranges of other are all contained in some ranges of self,
1453 assert!(contains(
1454 vec!((1, 4), (7, 10)),
1455 vec!((1, 2), (3, 4), (7, 9))
1456 ));
1457 }
1458 }