diff options
author | Blaž Hrastnik | 2021-03-15 08:09:18 +0000 |
---|---|---|
committer | Blaž Hrastnik | 2021-03-15 08:09:18 +0000 |
commit | dd91090a1ae931a604c51b9c6d7d8c9b46761af4 (patch) | |
tree | 3a399be8dba630a20c84a960e8aeb421c025dbac /helix-core | |
parent | 872d77075302a3f5b526045e07e0a5564d170e1b (diff) |
Implement keep_selections (filter selections on regex).
Diffstat (limited to 'helix-core')
-rw-r--r-- | helix-core/src/selection.rs | 35 |
1 files changed, 27 insertions, 8 deletions
diff --git a/helix-core/src/selection.rs b/helix-core/src/selection.rs index ee925cbc..c34dff31 100644 --- a/helix-core/src/selection.rs +++ b/helix-core/src/selection.rs @@ -273,14 +273,33 @@ impl Selection { // TODO: checkSelection -> check if valid for doc length +pub fn keep_matches( + text: RopeSlice, + selection: &Selection, + regex: &crate::regex::Regex, +) -> Option<Selection> { + let result: SmallVec<_> = selection + .ranges() + .iter() + .filter(|range| regex.is_match(&range.fragment(text))) + .copied() + .collect(); + + // TODO: figure out a new primary index + if !result.is_empty() { + return Some(Selection::new(result, 0)); + } + None +} + pub fn select_on_matches( text: RopeSlice, - selections: &Selection, + selection: &Selection, regex: &crate::regex::Regex, ) -> Option<Selection> { - let mut result = SmallVec::with_capacity(selections.ranges().len()); + let mut result = SmallVec::with_capacity(selection.ranges().len()); - for sel in selections.ranges() { + for sel in selection.ranges() { // TODO: can't avoid occasional allocations since Regex can't operate on chunks yet let fragment = sel.fragment(text); @@ -309,12 +328,12 @@ pub fn select_on_matches( // TODO: support to split on capture #N instead of whole match pub fn split_on_matches( text: RopeSlice, - selections: &Selection, + selection: &Selection, regex: &crate::regex::Regex, ) -> Selection { - let mut result = SmallVec::with_capacity(selections.ranges().len()); + let mut result = SmallVec::with_capacity(selection.ranges().len()); - for sel in selections.ranges() { + for sel in selection.ranges() { // TODO: can't avoid occasional allocations since Regex can't operate on chunks yet let fragment = sel.fragment(text); @@ -417,9 +436,9 @@ mod test { let text = Rope::from("abcd efg wrs xyz 123 456"); - let selections = Selection::new(smallvec![Range::new(0, 8), Range::new(10, 19),], 0); + let selection = Selection::new(smallvec![Range::new(0, 8), Range::new(10, 19),], 0); - let result = split_on_matches(text.slice(..), &selections, &Regex::new(r"\s+").unwrap()); + let result = split_on_matches(text.slice(..), &selection, &Regex::new(r"\s+").unwrap()); assert_eq!( result.ranges(), |