1//! Selections are the primary editing construct. Even cursors are
2//! defined as a selection range.
4//! All positioning is done via `char` offsets into the buffer.
7 ensure_grapheme_boundary_next, ensure_grapheme_boundary_prev, next_grapheme_boundary,
8 prev_grapheme_boundary,
11 Assoc, ChangeSet, RopeGraphemes, RopeSlice,
13use smallvec::{smallvec, SmallVec};
16/// A single selection range.
18/// A range consists of an "anchor" and "head" position in
19/// the text. The head is the part that the user moves when
20/// directly extending a selection. The head and anchor
21/// can be in any order, or even share the same position.
23/// The anchor and head positions use gap indexing, meaning
24/// that their indices represent the gaps *between* `char`s
25/// rather than the `char`s themselves. For example, 1
26/// represents the position between the first and second `char`.
28/// Below are some examples of `Range` configurations.
29/// The anchor and head indices are shown as "(anchor, head)"
30/// tuples, followed by example text with "[" and "]" symbols
31/// representing the anchor and head positions:
33/// - (0, 3): `[Som]e text`.
34/// - (3, 0): `]Som[e text`.
35/// - (2, 7): `So[me te]xt`.
36/// - (1, 1): `S[]ome text`.
38/// Ranges are considered to be inclusive on the left and
39/// exclusive on the right, regardless of anchor-head ordering.
40/// This means, for example, that non-zero-width ranges that
41/// are directly adjecent, sharing an edge, do not overlap.
42/// However, a zero-width range will overlap with the shared
43/// left-edge of another range.
45/// By convention, user-facing ranges are considered to have
46/// a block cursor on the head-side of the range that spans a
47/// single grapheme inward from the range's edge. There are a
48/// variety of helper methods on `Range` for working in terms of
49/// that block cursor, all of which have `cursor` in their name.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52 /// The anchor of the range: the side that doesn't move when extending.
54 /// The head of the range, moved when extending.
56 /// The previous visual offset (softwrapped lines and columns) from
57 /// the start of the line
58 pub old_visual_position: Option<(u32, u32)>,
62 pub fn new(anchor: usize, head: usize) -> Self {
66 old_visual_position: None,
70 pub fn point(head: usize) -> Self {
74 /// Start of the range.
77 pub fn from(&self) -> usize {
78 std::cmp::min(self.anchor, self.head)
84 pub fn to(&self) -> usize {
85 std::cmp::max(self.anchor, self.head)
88 /// Total length of the range.
91 pub fn len(&self) -> usize {
92 self.to() - self.from()
95 /// The (inclusive) range of lines that the range overlaps.
98 pub fn line_range(&self, text: RopeSlice) -> (usize, usize) {
99 let from = self.from();
100 let to = if self.is_empty() {
103 prev_grapheme_boundary(text, self.to()).max(from)
106 (text.char_to_line(from), text.char_to_line(to))
109 /// `true` when head and anchor are at the same position.
111 pub fn is_empty(&self) -> bool {
112 self.anchor == self.head
115 /// `Direction::Backward` when head < anchor.
116 /// `Direction::Backward` otherwise.
119 pub fn direction(&self) -> Direction {
120 if self.head < self.anchor {
127 /// Flips the direction of the selection
128 pub fn flip(&self) -> Self {
132 old_visual_position: self.old_visual_position,
136 /// Returns the selection if it goes in the direction of `direction`,
137 /// flipping the selection otherwise.
138 pub fn with_direction(self, direction: Direction) -> Self {
139 if self.direction() == direction {
146 /// Check two ranges for overlap.
148 pub fn overlaps(&self, other: &Self) -> bool {
149 // To my eye, it's non-obvious why this works, but I arrived
150 // at it after transforming the slower version that explicitly
151 // enumerated more cases. The unit tests are thorough.
152 self.from() == other.from() || (self.to() > other.from() && other.to() > self.from())
156 pub fn contains_range(&self, other: &Self) -> bool {
157 self.from() <= other.from() && self.to() >= other.to()
160 pub fn contains(&self, pos: usize) -> bool {
161 self.from() <= pos && pos < self.to()
164 /// Map a range through a set of changes. Returns a new range representing the same position
165 /// after the changes are applied.
166 pub fn map(self, changes: &ChangeSet) -> Self {
167 use std::cmp::Ordering;
168 let (anchor, head) = match self.anchor.cmp(&self.head) {
170 changes.map_pos(self.anchor, Assoc::After),
171 changes.map_pos(self.head, Assoc::After),
174 changes.map_pos(self.anchor, Assoc::After),
175 changes.map_pos(self.head, Assoc::Before),
177 Ordering::Greater => (
178 changes.map_pos(self.anchor, Assoc::Before),
179 changes.map_pos(self.head, Assoc::After),
183 // We want to return a new `Range` with `horiz == None` every time,
184 // even if the anchor and head haven't changed, because we don't
185 // know if the *visual* position hasn't changed due to
186 // character-width or grapheme changes earlier in the text.
190 old_visual_position: None,
194 /// Extend the range to cover at least `from` `to`.
196 pub fn extend(&self, from: usize, to: usize) -> Self {
197 debug_assert!(from <= to);
199 if self.anchor <= self.head {
201 anchor: self.anchor.min(from),
202 head: self.head.max(to),
203 old_visual_position: None,
207 anchor: self.anchor.max(to),
208 head: self.head.min(from),
209 old_visual_position: None,
214 /// Returns a range that encompasses both input ranges.
216 /// This is like `extend()`, but tries to negotiate the
217 /// anchor/head ordering between the two input ranges.
219 pub fn merge(&self, other: Self) -> Self {
220 if self.anchor > self.head && other.anchor > other.head {
222 anchor: self.anchor.max(other.anchor),
223 head: self.head.min(other.head),
224 old_visual_position: None,
228 anchor: self.from().min(other.from()),
229 head: self.to().max(other.to()),
230 old_visual_position: None,
237 /// Returns the text inside this range given the text of the whole buffer.
239 /// The returned `Cow` is a reference if the range of text is inside a single
240 /// chunk of the rope. Otherwise a copy of the text is returned. Consider
241 /// using `slice` instead if you do not need a `Cow` or `String` to avoid copying.
243 pub fn fragment<'a, 'b: 'a>(&'a self, text: RopeSlice<'b>) -> Cow<'b, str> {
244 self.slice(text).into()
247 /// Returns the text inside this range given the text of the whole buffer.
249 /// The returned value is a reference to the passed slice. This method never
250 /// copies any contents.
252 pub fn slice<'a, 'b: 'a>(&'a self, text: RopeSlice<'b>) -> RopeSlice<'b> {
253 text.slice(self.from()..self.to())
256 //--------------------------------
257 // Alignment methods.
259 /// Compute a possibly new range from this range, with its ends
260 /// shifted as needed to align with grapheme boundaries.
262 /// Zero-width ranges will always stay zero-width, and non-zero-width
263 /// ranges will never collapse to zero-width.
265 pub fn grapheme_aligned(&self, slice: RopeSlice) -> Self {
266 use std::cmp::Ordering;
267 let (new_anchor, new_head) = match self.anchor.cmp(&self.head) {
269 let pos = ensure_grapheme_boundary_prev(slice, self.anchor);
273 ensure_grapheme_boundary_prev(slice, self.anchor),
274 ensure_grapheme_boundary_next(slice, self.head),
276 Ordering::Greater => (
277 ensure_grapheme_boundary_next(slice, self.anchor),
278 ensure_grapheme_boundary_prev(slice, self.head),
284 old_visual_position: if new_anchor == self.anchor {
285 self.old_visual_position
292 /// Compute a possibly new range from this range, attempting to ensure
293 /// a minimum range width of 1 char by shifting the head in the forward
294 /// direction as needed.
296 /// This method will never shift the anchor, and will only shift the
297 /// head in the forward direction. Therefore, this method can fail
298 /// at ensuring the minimum width if and only if the passed range is
299 /// both zero-width and at the end of the `RopeSlice`.
301 /// If the input range is grapheme-boundary aligned, the returned range
302 /// will also be. Specifically, if the head needs to shift to achieve
303 /// the minimum width, it will shift to the next grapheme boundary.
306 pub fn min_width_1(&self, slice: RopeSlice) -> Self {
307 if self.anchor == self.head {
310 head: next_grapheme_boundary(slice, self.head),
311 old_visual_position: self.old_visual_position,
318 //--------------------------------
319 // Block-cursor methods.
321 /// Gets the left-side position of the block cursor.
324 pub fn cursor(self, text: RopeSlice) -> usize {
325 if self.head > self.anchor {
326 prev_grapheme_boundary(text, self.head)
332 /// Puts the left side of the block cursor at `char_idx`, optionally extending.
334 /// This follows "1-width" semantics, and therefore does a combination of anchor
335 /// and head moves to behave as if both the front and back of the range are 1-width
338 /// This method assumes that the range and `char_idx` are already properly
339 /// grapheme-aligned.
342 pub fn put_cursor(self, text: RopeSlice, char_idx: usize, extend: bool) -> Range {
344 let anchor = if self.head >= self.anchor && char_idx < self.anchor {
345 next_grapheme_boundary(text, self.anchor)
346 } else if self.head < self.anchor && char_idx >= self.anchor {
347 prev_grapheme_boundary(text, self.anchor)
352 if anchor <= char_idx {
353 Range::new(anchor, next_grapheme_boundary(text, char_idx))
355 Range::new(anchor, char_idx)
358 Range::point(char_idx)
362 /// The line number that the block-cursor is on.
365 pub fn cursor_line(&self, text: RopeSlice) -> usize {
366 text.char_to_line(self.cursor(text))
369 /// Returns true if this Range covers a single grapheme in the given text
370 pub fn is_single_grapheme(&self, doc: RopeSlice) -> bool {
371 let mut graphemes = RopeGraphemes::new(doc.slice(self.from()..self.to()));
372 let first = graphemes.next();
373 let second = graphemes.next();
374 first.is_some() && second.is_none()
378impl From<(usize, usize)> for Range {
379 fn from((anchor, head): (usize, usize)) -> Self {
383 old_visual_position: None,
388/// A selection consists of one or more selection ranges.
389/// invariant: A selection can never be empty (always contains at least primary range).
390#[derive(Debug, Clone, PartialEq, Eq)]
391pub struct Selection {
392 ranges: SmallVec<[Range; 1]>,
393 primary_index: usize,
396#[allow(clippy::len_without_is_empty)] // a Selection is never empty
402 pub fn primary(&self) -> Range {
403 self.ranges[self.primary_index]
408 pub fn primary_mut(&mut self) -> &mut Range {
409 &mut self.ranges[self.primary_index]
412 /// Ensure selection containing only the primary selection.
413 pub fn into_single(self) -> Self {
414 if self.ranges.len() == 1 {
418 ranges: smallvec![self.ranges[self.primary_index]],
424 /// Adds a new range to the selection and makes it the primary range.
425 pub fn push(mut self, range: Range) -> Self {
426 self.ranges.push(range);
427 self.set_primary_index(self.ranges().len() - 1);
431 /// Removes a range from the selection.
432 pub fn remove(mut self, index: usize) -> Self {
434 self.ranges.len() > 1,
435 "can't remove the last range from a selection!"
438 self.ranges.remove(index);
439 if index < self.primary_index || self.primary_index == self.ranges.len() {
440 self.primary_index -= 1;
445 /// Replace a range in the selection with a new range.
446 pub fn replace(mut self, index: usize, range: Range) -> Self {
447 self.ranges[index] = range;
451 /// Map selections over a set of changes. Useful for adjusting the selection position after
452 /// applying changes to a document.
453 pub fn map(self, changes: &ChangeSet) -> Self {
454 if changes.is_empty() {
461 .map(|range| range.map(changes))
467 pub fn ranges(&self) -> &[Range] {
471 pub fn primary_index(&self) -> usize {
475 pub fn set_primary_index(&mut self, idx: usize) {
476 assert!(idx < self.ranges.len());
477 self.primary_index = idx;
481 /// Constructs a selection holding a single range.
482 pub fn single(anchor: usize, head: usize) -> Self {
484 ranges: smallvec![Range {
487 old_visual_position: None
493 /// Constructs a selection holding a single cursor.
494 pub fn point(pos: usize) -> Self {
495 Self::single(pos, pos)
498 /// Normalizes a `Selection`.
499 fn normalize(mut self) -> Self {
500 let mut primary = self.ranges[self.primary_index];
501 self.ranges.sort_unstable_by_key(Range::from);
503 self.ranges.dedup_by(|curr_range, prev_range| {
504 if prev_range.overlaps(curr_range) {
505 let new_range = curr_range.merge(*prev_range);
506 if prev_range == &primary || curr_range == &primary {
509 *prev_range = new_range;
516 self.primary_index = self
519 .position(|&range| range == primary)
525 // Merges all ranges that are consecutive
526 pub fn merge_consecutive_ranges(mut self) -> Self {
527 let mut primary = self.ranges[self.primary_index];
529 self.ranges.dedup_by(|curr_range, prev_range| {
530 if prev_range.to() == curr_range.from() {
531 let new_range = curr_range.merge(*prev_range);
532 if prev_range == &primary || curr_range == &primary {
535 *prev_range = new_range;
542 self.primary_index = self
545 .position(|&range| range == primary)
551 // TODO: consume an iterator or a vec to reduce allocations?
553 pub fn new(ranges: SmallVec<[Range; 1]>, primary_index: usize) -> Self {
554 assert!(!ranges.is_empty());
555 debug_assert!(primary_index < ranges.len());
557 let mut selection = Self {
562 if selection.ranges.len() > 1 {
563 // TODO: only normalize if needed (any ranges out of order)
564 selection = selection.normalize();
570 /// Takes a closure and maps each `Range` over the closure.
571 pub fn transform<F>(mut self, mut f: F) -> Self
573 F: FnMut(Range) -> Range,
575 for range in self.ranges.iter_mut() {
581 // Ensures the selection adheres to the following invariants:
582 // 1. All ranges are grapheme aligned.
583 // 2. All ranges are at least 1 character wide, unless at the
584 // very end of the document.
585 // 3. Ranges are non-overlapping.
586 // 4. Ranges are sorted by their position in the text.
587 pub fn ensure_invariants(self, text: RopeSlice) -> Self {
588 self.transform(|r| r.min_width_1(text).grapheme_aligned(text))
592 /// Transforms the selection into all of the left-side head positions,
593 /// using block-cursor semantics.
594 pub fn cursors(self, text: RopeSlice) -> Self {
595 self.transform(|range| Range::point(range.cursor(text)))
598 pub fn fragments<'a>(&'a self, text: RopeSlice<'a>) -> impl Iterator<Item = Cow<str>> + 'a {
599 self.ranges.iter().map(move |range| range.fragment(text))
602 pub fn slices<'a>(&'a self, text: RopeSlice<'a>) -> impl Iterator<Item = RopeSlice> + 'a {
603 self.ranges.iter().map(move |range| range.slice(text))
607 pub fn iter(&self) -> std::slice::Iter<'_, Range> {
612 pub fn len(&self) -> usize {
616 // returns true if self ⊇ other
617 pub fn contains(&self, other: &Selection) -> bool {
618 // can't contain other if it is larger
619 if other.len() > self.len() {
623 let (mut iter_self, mut iter_other) = (self.iter(), other.iter());
624 let (mut ele_self, mut ele_other) = (iter_self.next(), iter_other.next());
627 match (ele_self, ele_other) {
628 (Some(ra), Some(rb)) => {
629 if !ra.contains_range(rb) {
630 // `self` doesn't contain next element from `other`, advance `self`, we need to match all from `other`
631 ele_self = iter_self.next();
633 // matched element from `other`, advance `other`
634 ele_other = iter_other.next();
638 // exhausted `self`, we can't match the reminder of `other`
642 // no elements from `other` left to match, `self` contains `other`
650impl<'a> IntoIterator for &'a Selection {
651 type Item = &'a Range;
652 type IntoIter = std::slice::Iter<'a, Range>;
654 fn into_iter(self) -> std::slice::Iter<'a, Range> {
659// TODO: checkSelection -> check if valid for doc length && sorted
661pub fn keep_or_remove_matches(
663 selection: &Selection,
664 regex: &crate::regex::Regex,
666) -> Option<Selection> {
667 let result: SmallVec<_> = selection
669 .filter(|range| regex.is_match(&range.fragment(text)) ^ remove)
673 // TODO: figure out a new primary index
674 if !result.is_empty() {
675 return Some(Selection::new(result, 0));
680pub fn select_on_matches(
682 selection: &Selection,
683 regex: &crate::regex::Regex,
684) -> Option<Selection> {
685 let mut result = SmallVec::with_capacity(selection.len());
687 for sel in selection {
688 // TODO: can't avoid occasional allocations since Regex can't operate on chunks yet
689 let fragment = sel.fragment(text);
691 let sel_start = sel.from();
692 let start_byte = text.char_to_byte(sel_start);
694 for mat in regex.find_iter(&fragment) {
695 // TODO: retain range direction
697 let start = text.byte_to_char(start_byte + mat.start());
698 let end = text.byte_to_char(start_byte + mat.end());
700 let range = Range::new(start, end);
701 // Make sure the match is not right outside of the selection.
702 // These invalid matches can come from using RegEx anchors like `^`, `$`
703 if range != Range::point(sel.to()) {
709 // TODO: figure out a new primary index
710 if !result.is_empty() {
711 return Some(Selection::new(result, 0));
717// TODO: support to split on capture #N instead of whole match
718pub fn split_on_matches(
720 selection: &Selection,
721 regex: &crate::regex::Regex,
723 let mut result = SmallVec::with_capacity(selection.len());
725 for sel in selection {
726 // Special case: zero-width selection.
727 if sel.from() == sel.to() {
732 // TODO: can't avoid occasional allocations since Regex can't operate on chunks yet
733 let fragment = sel.fragment(text);
735 let sel_start = sel.from();
736 let sel_end = sel.to();
738 let start_byte = text.char_to_byte(sel_start);
740 let mut start = sel_start;
742 for mat in regex.find_iter(&fragment) {
743 // TODO: retain range direction
744 let end = text.byte_to_char(start_byte + mat.start());
745 result.push(Range::new(start, end));
746 start = text.byte_to_char(start_byte + mat.end());
750 result.push(Range::new(start, sel_end));
754 // TODO: figure out a new primary index
755 Selection::new(result, 0)
765 fn test_new_empty() {
766 let _ = Selection::new(smallvec![], 0);
770 fn test_create_normalizes_and_merges() {
771 let sel = Selection::new(
788 .map(|range| format!("{}/{}", range.anchor, range.head))
789 .collect::<Vec<String>>()
792 assert_eq!(res, "0/6,6/7,7/8,9/13,13/14");
794 // it correctly calculates a new primary index
795 let sel = Selection::new(
796 smallvec![Range::new(0, 2), Range::new(1, 5), Range::new(4, 7)],
803 .map(|range| format!("{}/{}", range.anchor, range.head))
804 .collect::<Vec<String>>()
807 assert_eq!(res, "0/7");
808 assert_eq!(sel.primary_index, 0);
812 fn test_create_merges_adjacent_points() {
813 let sel = Selection::new(
827 .map(|range| format!("{}/{}", range.anchor, range.head))
828 .collect::<Vec<String>>()
831 assert_eq!(res, "8/10,10/12,12/12");
836 let range = Range::new(10, 12);
838 assert!(!range.contains(9));
839 assert!(range.contains(10));
840 assert!(range.contains(11));
841 assert!(!range.contains(12));
842 assert!(!range.contains(13));
844 let range = Range::new(9, 6);
845 assert!(!range.contains(9));
846 assert!(range.contains(7));
847 assert!(range.contains(6));
852 fn overlaps(a: (usize, usize), b: (usize, usize)) -> bool {
853 Range::new(a.0, a.1).overlaps(&Range::new(b.0, b.1))
856 // Two non-zero-width ranges, no overlap.
857 assert!(!overlaps((0, 3), (3, 6)));
858 assert!(!overlaps((0, 3), (6, 3)));
859 assert!(!overlaps((3, 0), (3, 6)));
860 assert!(!overlaps((3, 0), (6, 3)));
861 assert!(!overlaps((3, 6), (0, 3)));
862 assert!(!overlaps((3, 6), (3, 0)));
863 assert!(!overlaps((6, 3), (0, 3)));
864 assert!(!overlaps((6, 3), (3, 0)));
866 // Two non-zero-width ranges, overlap.
867 assert!(overlaps((0, 4), (3, 6)));
868 assert!(overlaps((0, 4), (6, 3)));
869 assert!(overlaps((4, 0), (3, 6)));
870 assert!(overlaps((4, 0), (6, 3)));
871 assert!(overlaps((3, 6), (0, 4)));
872 assert!(overlaps((3, 6), (4, 0)));
873 assert!(overlaps((6, 3), (0, 4)));
874 assert!(overlaps((6, 3), (4, 0)));
876 // Zero-width and non-zero-width range, no overlap.
877 assert!(!overlaps((0, 3), (3, 3)));
878 assert!(!overlaps((3, 0), (3, 3)));
879 assert!(!overlaps((3, 3), (0, 3)));
880 assert!(!overlaps((3, 3), (3, 0)));
882 // Zero-width and non-zero-width range, overlap.
883 assert!(overlaps((1, 4), (1, 1)));
884 assert!(overlaps((4, 1), (1, 1)));
885 assert!(overlaps((1, 1), (1, 4)));
886 assert!(overlaps((1, 1), (4, 1)));
888 assert!(overlaps((1, 4), (3, 3)));
889 assert!(overlaps((4, 1), (3, 3)));
890 assert!(overlaps((3, 3), (1, 4)));
891 assert!(overlaps((3, 3), (4, 1)));
893 // Two zero-width ranges, no overlap.
894 assert!(!overlaps((0, 0), (1, 1)));
895 assert!(!overlaps((1, 1), (0, 0)));
897 // Two zero-width ranges, overlap.
898 assert!(overlaps((1, 1), (1, 1)));
902 fn test_grapheme_aligned() {
903 let r = Rope::from_str("\r\nHi\r\n");
907 assert_eq!(Range::new(0, 0).grapheme_aligned(s), Range::new(0, 0));
908 assert_eq!(Range::new(1, 1).grapheme_aligned(s), Range::new(0, 0));
909 assert_eq!(Range::new(2, 2).grapheme_aligned(s), Range::new(2, 2));
910 assert_eq!(Range::new(3, 3).grapheme_aligned(s), Range::new(3, 3));
911 assert_eq!(Range::new(4, 4).grapheme_aligned(s), Range::new(4, 4));
912 assert_eq!(Range::new(5, 5).grapheme_aligned(s), Range::new(4, 4));
913 assert_eq!(Range::new(6, 6).grapheme_aligned(s), Range::new(6, 6));
916 assert_eq!(Range::new(0, 1).grapheme_aligned(s), Range::new(0, 2));
917 assert_eq!(Range::new(1, 2).grapheme_aligned(s), Range::new(0, 2));
918 assert_eq!(Range::new(2, 3).grapheme_aligned(s), Range::new(2, 3));
919 assert_eq!(Range::new(3, 4).grapheme_aligned(s), Range::new(3, 4));
920 assert_eq!(Range::new(4, 5).grapheme_aligned(s), Range::new(4, 6));
921 assert_eq!(Range::new(5, 6).grapheme_aligned(s), Range::new(4, 6));
923 assert_eq!(Range::new(0, 2).grapheme_aligned(s), Range::new(0, 2));
924 assert_eq!(Range::new(1, 3).grapheme_aligned(s), Range::new(0, 3));
925 assert_eq!(Range::new(2, 4).grapheme_aligned(s), Range::new(2, 4));
926 assert_eq!(Range::new(3, 5).grapheme_aligned(s), Range::new(3, 6));
927 assert_eq!(Range::new(4, 6).grapheme_aligned(s), Range::new(4, 6));
930 assert_eq!(Range::new(1, 0).grapheme_aligned(s), Range::new(2, 0));
931 assert_eq!(Range::new(2, 1).grapheme_aligned(s), Range::new(2, 0));
932 assert_eq!(Range::new(3, 2).grapheme_aligned(s), Range::new(3, 2));
933 assert_eq!(Range::new(4, 3).grapheme_aligned(s), Range::new(4, 3));
934 assert_eq!(Range::new(5, 4).grapheme_aligned(s), Range::new(6, 4));
935 assert_eq!(Range::new(6, 5).grapheme_aligned(s), Range::new(6, 4));
937 assert_eq!(Range::new(2, 0).grapheme_aligned(s), Range::new(2, 0));
938 assert_eq!(Range::new(3, 1).grapheme_aligned(s), Range::new(3, 0));
939 assert_eq!(Range::new(4, 2).grapheme_aligned(s), Range::new(4, 2));
940 assert_eq!(Range::new(5, 3).grapheme_aligned(s), Range::new(6, 3));
941 assert_eq!(Range::new(6, 4).grapheme_aligned(s), Range::new(6, 4));
945 fn test_min_width_1() {
946 let r = Rope::from_str("\r\nHi\r\n");
950 assert_eq!(Range::new(0, 0).min_width_1(s), Range::new(0, 2));
951 assert_eq!(Range::new(1, 1).min_width_1(s), Range::new(1, 2));
952 assert_eq!(Range::new(2, 2).min_width_1(s), Range::new(2, 3));
953 assert_eq!(Range::new(3, 3).min_width_1(s), Range::new(3, 4));
954 assert_eq!(Range::new(4, 4).min_width_1(s), Range::new(4, 6));
955 assert_eq!(Range::new(5, 5).min_width_1(s), Range::new(5, 6));
956 assert_eq!(Range::new(6, 6).min_width_1(s), Range::new(6, 6));
959 assert_eq!(Range::new(0, 1).min_width_1(s), Range::new(0, 1));
960 assert_eq!(Range::new(1, 2).min_width_1(s), Range::new(1, 2));
961 assert_eq!(Range::new(2, 3).min_width_1(s), Range::new(2, 3));
962 assert_eq!(Range::new(3, 4).min_width_1(s), Range::new(3, 4));
963 assert_eq!(Range::new(4, 5).min_width_1(s), Range::new(4, 5));
964 assert_eq!(Range::new(5, 6).min_width_1(s), Range::new(5, 6));
967 assert_eq!(Range::new(1, 0).min_width_1(s), Range::new(1, 0));
968 assert_eq!(Range::new(2, 1).min_width_1(s), Range::new(2, 1));
969 assert_eq!(Range::new(3, 2).min_width_1(s), Range::new(3, 2));
970 assert_eq!(Range::new(4, 3).min_width_1(s), Range::new(4, 3));
971 assert_eq!(Range::new(5, 4).min_width_1(s), Range::new(5, 4));
972 assert_eq!(Range::new(6, 5).min_width_1(s), Range::new(6, 5));
976 fn test_select_on_matches() {
977 use crate::regex::{Regex, RegexBuilder};
979 let r = Rope::from_str("Nobody expects the Spanish inquisition");
982 let selection = Selection::single(0, r.len_chars());
984 select_on_matches(s, &selection, &Regex::new(r"[A-Z][a-z]*").unwrap()),
986 smallvec![Range::new(0, 6), Range::new(19, 26)],
991 let r = Rope::from_str("This\nString\n\ncontains multiple\nlines");
994 let start_of_line = RegexBuilder::new(r"^").multi_line(true).build().unwrap();
995 let end_of_line = RegexBuilder::new(r"$").multi_line(true).build().unwrap();
997 // line without ending
999 select_on_matches(s, &Selection::single(0, 4), &start_of_line),
1000 Some(Selection::single(0, 0))
1003 select_on_matches(s, &Selection::single(0, 4), &end_of_line),
1008 select_on_matches(s, &Selection::single(0, 5), &start_of_line),
1009 Some(Selection::single(0, 0))
1012 select_on_matches(s, &Selection::single(0, 5), &end_of_line),
1013 Some(Selection::single(4, 4))
1015 // line with start of next line
1017 select_on_matches(s, &Selection::single(0, 6), &start_of_line),
1018 Some(Selection::new(
1019 smallvec![Range::point(0), Range::point(5)],
1024 select_on_matches(s, &Selection::single(0, 6), &end_of_line),
1025 Some(Selection::single(4, 4))
1032 &Selection::single(0, s.len_chars()),
1033 &RegexBuilder::new(r"^[a-z ]*$")
1038 Some(Selection::new(
1039 smallvec![Range::point(12), Range::new(13, 30), Range::new(31, 36)],
1046 fn test_line_range() {
1047 let r = Rope::from_str("\r\nHi\r\nthere!");
1048 let s = r.slice(..);
1050 // Zero-width ranges.
1051 assert_eq!(Range::new(0, 0).line_range(s), (0, 0));
1052 assert_eq!(Range::new(1, 1).line_range(s), (0, 0));
1053 assert_eq!(Range::new(2, 2).line_range(s), (1, 1));
1054 assert_eq!(Range::new(3, 3).line_range(s), (1, 1));
1057 assert_eq!(Range::new(0, 1).line_range(s), (0, 0));
1058 assert_eq!(Range::new(0, 2).line_range(s), (0, 0));
1059 assert_eq!(Range::new(0, 3).line_range(s), (0, 1));
1060 assert_eq!(Range::new(1, 2).line_range(s), (0, 0));
1061 assert_eq!(Range::new(2, 3).line_range(s), (1, 1));
1062 assert_eq!(Range::new(3, 8).line_range(s), (1, 2));
1063 assert_eq!(Range::new(0, 12).line_range(s), (0, 2));
1066 assert_eq!(Range::new(1, 0).line_range(s), (0, 0));
1067 assert_eq!(Range::new(2, 0).line_range(s), (0, 0));
1068 assert_eq!(Range::new(3, 0).line_range(s), (0, 1));
1069 assert_eq!(Range::new(2, 1).line_range(s), (0, 0));
1070 assert_eq!(Range::new(3, 2).line_range(s), (1, 1));
1071 assert_eq!(Range::new(8, 3).line_range(s), (1, 2));
1072 assert_eq!(Range::new(12, 0).line_range(s), (0, 2));
1077 let r = Rope::from_str("\r\nHi\r\nthere!");
1078 let s = r.slice(..);
1080 // Zero-width ranges.
1081 assert_eq!(Range::new(0, 0).cursor(s), 0);
1082 assert_eq!(Range::new(2, 2).cursor(s), 2);
1083 assert_eq!(Range::new(3, 3).cursor(s), 3);
1086 assert_eq!(Range::new(0, 2).cursor(s), 0);
1087 assert_eq!(Range::new(0, 3).cursor(s), 2);
1088 assert_eq!(Range::new(3, 6).cursor(s), 4);
1091 assert_eq!(Range::new(2, 0).cursor(s), 0);
1092 assert_eq!(Range::new(6, 2).cursor(s), 2);
1093 assert_eq!(Range::new(6, 3).cursor(s), 3);
1097 fn test_put_cursor() {
1098 let r = Rope::from_str("\r\nHi\r\nthere!");
1099 let s = r.slice(..);
1101 // Zero-width ranges.
1102 assert_eq!(Range::new(0, 0).put_cursor(s, 0, true), Range::new(0, 2));
1103 assert_eq!(Range::new(0, 0).put_cursor(s, 2, true), Range::new(0, 3));
1104 assert_eq!(Range::new(2, 3).put_cursor(s, 4, true), Range::new(2, 6));
1105 assert_eq!(Range::new(2, 8).put_cursor(s, 4, true), Range::new(2, 6));
1106 assert_eq!(Range::new(8, 8).put_cursor(s, 4, true), Range::new(9, 4));
1109 assert_eq!(Range::new(3, 6).put_cursor(s, 0, true), Range::new(4, 0));
1110 assert_eq!(Range::new(3, 6).put_cursor(s, 2, true), Range::new(4, 2));
1111 assert_eq!(Range::new(3, 6).put_cursor(s, 3, true), Range::new(3, 4));
1112 assert_eq!(Range::new(3, 6).put_cursor(s, 4, true), Range::new(3, 6));
1113 assert_eq!(Range::new(3, 6).put_cursor(s, 6, true), Range::new(3, 7));
1114 assert_eq!(Range::new(3, 6).put_cursor(s, 8, true), Range::new(3, 9));
1117 assert_eq!(Range::new(6, 3).put_cursor(s, 0, true), Range::new(6, 0));
1118 assert_eq!(Range::new(6, 3).put_cursor(s, 2, true), Range::new(6, 2));
1119 assert_eq!(Range::new(6, 3).put_cursor(s, 3, true), Range::new(6, 3));
1120 assert_eq!(Range::new(6, 3).put_cursor(s, 4, true), Range::new(6, 4));
1121 assert_eq!(Range::new(6, 3).put_cursor(s, 6, true), Range::new(4, 7));
1122 assert_eq!(Range::new(6, 3).put_cursor(s, 8, true), Range::new(4, 9));
1126 fn test_split_on_matches() {
1127 use crate::regex::Regex;
1129 let text = Rope::from(" abcd efg wrs xyz 123 456");
1131 let selection = Selection::new(smallvec![Range::new(0, 9), Range::new(11, 20),], 0);
1133 let result = split_on_matches(text.slice(..), &selection, &Regex::new(r"\s+").unwrap());
1138 // TODO: rather than this behavior, maybe we want it
1139 // to be based on which side is the anchor?
1141 // We get a leading zero-width range when there's
1142 // a leading match because ranges are inclusive on
1143 // the left. Imagine, for example, if the entire
1144 // selection range were matched: you'd still want
1145 // at least one range to remain after the split.
1151 // In contrast to the comment above, there is no
1152 // _trailing_ zero-width range despite the trailing
1153 // match, because ranges are exclusive on the right.
1158 result.fragments(text.slice(..)).collect::<Vec<_>>(),
1159 &["", "abcd", "efg", "rs", "xyz"]
1164 fn test_merge_consecutive_ranges() {
1165 let selection = Selection::new(
1176 let result = selection.merge_consecutive_ranges();
1180 &[Range::new(0, 10), Range::new(15, 20), Range::new(25, 30)]
1182 assert_eq!(result.primary_index, 2);
1184 let selection = Selection::new(smallvec![Range::new(0, 1)], 0);
1185 let result = selection.merge_consecutive_ranges();
1187 assert_eq!(result.ranges(), &[Range::new(0, 1)]);
1188 assert_eq!(result.primary_index, 0);
1190 let selection = Selection::new(
1202 let result = selection.merge_consecutive_ranges();
1204 assert_eq!(result.ranges(), &[Range::new(0, 15), Range::new(18, 25)]);
1205 assert_eq!(result.primary_index, 0);
1209 fn test_selection_contains() {
1210 fn contains(a: Vec<(usize, usize)>, b: Vec<(usize, usize)>) -> bool {
1211 let sela = Selection::new(a.iter().map(|a| Range::new(a.0, a.1)).collect(), 0);
1212 let selb = Selection::new(b.iter().map(|b| Range::new(b.0, b.1)).collect(), 0);
1213 sela.contains(&selb)
1217 assert!(contains(vec!((1, 1)), vec!((1, 1))));
1219 // larger set contains smaller
1220 assert!(contains(vec!((1, 1), (2, 2), (3, 3)), vec!((2, 2))));
1223 assert!(contains(vec!((1, 1), (2, 2)), vec!((1, 1), (2, 2))));
1225 // smaller set can't contain bigger
1226 assert!(!contains(vec!((1, 1)), vec!((1, 1), (2, 2))));
1229 vec!((1, 1), (2, 4), (5, 6), (7, 9), (10, 13)),
1230 vec!((3, 4), (7, 9))
1232 assert!(!contains(vec!((1, 1), (5, 6)), vec!((1, 6))));
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list