From cf9b88f9bda6d9ab3a32754b86be705c62662021 Mon Sep 17 00:00:00 2001 From: Skyler Hawthorne Date: Sun, 7 Apr 2024 14:15:29 -0400 Subject: [PATCH] add Range::{from_node,into_byte_range} --- helix-core/src/selection.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/helix-core/src/selection.rs b/helix-core/src/selection.rs index 579499de5e4a..6526128722bb 100644 --- a/helix-core/src/selection.rs +++ b/helix-core/src/selection.rs @@ -14,6 +14,7 @@ use crate::{ use helix_stdx::rope::{self, RopeSliceExt}; use smallvec::{smallvec, SmallVec}; use std::borrow::Cow; +use tree_sitter::Node; /// A single selection range. /// @@ -73,6 +74,12 @@ impl Range { Self::new(head, head) } + pub fn from_node(node: Node, text: RopeSlice, direction: Direction) -> Self { + let from = text.byte_to_char(node.start_byte()); + let to = text.byte_to_char(node.end_byte()); + Range::new(from, to).with_direction(direction) + } + /// Start of the range. #[inline] #[must_use] @@ -376,6 +383,12 @@ impl Range { let second = graphemes.next(); first.is_some() && second.is_none() } + + /// Converts this char range into an in order byte range, discarding + /// direction. + pub fn into_byte_range(&self, text: RopeSlice) -> (usize, usize) { + (text.char_to_byte(self.from()), text.char_to_byte(self.to())) + } } impl From<(usize, usize)> for Range { @@ -783,7 +796,9 @@ pub fn split_on_newline(text: RopeSlice, selection: &Selection) -> Selection { let mut start = sel_start; for line in sel.slice(text).lines() { - let Some(line_ending) = get_line_ending(&line) else { break }; + let Some(line_ending) = get_line_ending(&line) else { + break; + }; let line_end = start + line.len_chars(); // TODO: retain range direction result.push(Range::new(start, line_end - line_ending.len_chars()));