Skip to main content

continuity_text/
select.rs

1//! Selection helpers over a `ropey::Rope`.
2
3use ropey::Rope;
4
5use crate::{Position, Range, Selection, SelectionKind};
6
7/// Select the word around `position`, falling back to a caret when no word
8/// byte touches the position.
9pub fn word_at(rope: &Rope, position: Position) -> Selection {
10    let text = rope.to_string();
11    let byte = position.to_byte_offset(rope).unwrap_or(0).min(text.len());
12    let Some((start, end)) = word_bounds(&text, byte) else {
13        return Selection::caret_at(position);
14    };
15    selection_from_bytes(rope, start, end, SelectionKind::Caret)
16}
17
18/// Select the whole source line containing `position`, excluding the line
19/// ending.
20pub fn line_at(rope: &Rope, position: Position) -> Selection {
21    let line = (position.line as usize).min(rope.len_lines().saturating_sub(1));
22    let start = rope.line_to_byte(line);
23    let end = line_content_end(rope, line);
24    selection_from_bytes(rope, start, end, SelectionKind::LineWise)
25}
26
27/// Select the paragraph around `position`. Paragraphs are separated by blank
28/// lines.
29pub fn paragraph_at(rope: &Rope, position: Position) -> Selection {
30    if rope.len_bytes() == 0 {
31        return Selection::caret_at(Position::ZERO);
32    }
33    let mut line = (position.line as usize).min(rope.len_lines().saturating_sub(1));
34    if is_blank_line(rope, line) && line > 0 {
35        line -= 1;
36    }
37    let mut start_line = line;
38    while start_line > 0 && !is_blank_line(rope, start_line - 1) {
39        start_line -= 1;
40    }
41    let mut end_line = line;
42    while end_line + 1 < rope.len_lines() && !is_blank_line(rope, end_line + 1) {
43        end_line += 1;
44    }
45    selection_from_bytes(
46        rope,
47        rope.line_to_byte(start_line),
48        line_content_end(rope, end_line),
49        SelectionKind::Caret,
50    )
51}
52
53/// Expand a selection by prose-oriented scopes: word, sentence, paragraph,
54/// then document.
55pub fn expand_smart(rope: &Rope, selection: Selection) -> Selection {
56    let current = selection.ordered_range();
57    let head = selection.head;
58    for candidate in [
59        word_at(rope, head),
60        sentence_at(rope, head),
61        paragraph_at(rope, head),
62        document(rope),
63    ] {
64        if contains_range(candidate.ordered_range(), current)
65            && candidate.ordered_range() != current
66        {
67            return candidate;
68        }
69    }
70    document(rope)
71}
72
73/// Select the whole document.
74pub fn document(rope: &Rope) -> Selection {
75    let end = Position::from_byte_offset(rope, rope.len_bytes()).unwrap_or(Position::ZERO);
76    Selection::new(Position::ZERO, end, SelectionKind::Caret)
77}
78
79fn sentence_at(rope: &Rope, position: Position) -> Selection {
80    let text = rope.to_string();
81    if text.is_empty() {
82        return Selection::caret_at(Position::ZERO);
83    }
84    let byte = position.to_byte_offset(rope).unwrap_or(0).min(text.len());
85    let mut start = 0;
86    for (idx, ch) in text[..byte].char_indices().rev() {
87        if matches!(ch, '.' | '!' | '?') {
88            start = idx + ch.len_utf8();
89            break;
90        }
91    }
92    while start < text.len() && text[start..].starts_with(char::is_whitespace) {
93        start += text[start..].chars().next().map_or(0, char::len_utf8);
94    }
95    let mut end = text.len();
96    for (offset, ch) in text[byte..].char_indices() {
97        if matches!(ch, '.' | '!' | '?') {
98            end = byte + offset + ch.len_utf8();
99            break;
100        }
101    }
102    selection_from_bytes(rope, start, end, SelectionKind::Caret)
103}
104
105fn word_bounds(text: &str, byte: usize) -> Option<(usize, usize)> {
106    if text.is_empty() {
107        return None;
108    }
109    let mut probe = byte.min(text.len());
110    if probe == text.len() && probe > 0 {
111        probe = previous_boundary(text, probe);
112    }
113    if !is_word_byte(text, probe) && probe > 0 {
114        let prev = previous_boundary(text, probe);
115        if is_word_byte(text, prev) {
116            probe = prev;
117        }
118    }
119    if !is_word_byte(text, probe) {
120        return None;
121    }
122    let mut start = probe;
123    while start > 0 {
124        let prev = previous_boundary(text, start);
125        if !is_word_byte(text, prev) {
126            break;
127        }
128        start = prev;
129    }
130    let mut end = next_boundary(text, probe);
131    while end < text.len() && is_word_byte(text, end) {
132        end = next_boundary(text, end);
133    }
134    Some((start, end))
135}
136
137fn is_word_byte(text: &str, byte: usize) -> bool {
138    text.get(byte..)
139        .and_then(|s| s.chars().next())
140        .is_some_and(|ch| ch.is_alphanumeric() || ch == '_')
141}
142
143fn previous_boundary(text: &str, byte: usize) -> usize {
144    text[..byte].char_indices().last().map_or(0, |(idx, _)| idx)
145}
146
147fn next_boundary(text: &str, byte: usize) -> usize {
148    text[byte..]
149        .chars()
150        .next()
151        .map_or(text.len(), |ch| byte + ch.len_utf8())
152}
153
154fn selection_from_bytes(rope: &Rope, start: usize, end: usize, kind: SelectionKind) -> Selection {
155    let anchor = Position::from_byte_offset(rope, start).unwrap_or(Position::ZERO);
156    let head = Position::from_byte_offset(rope, end).unwrap_or(anchor);
157    Selection::new(anchor, head, kind)
158}
159
160fn line_content_end(rope: &Rope, line: usize) -> usize {
161    let start = rope.line_to_byte(line);
162    let next = if line + 1 < rope.len_lines() {
163        rope.line_to_byte(line + 1)
164    } else {
165        rope.len_bytes()
166    };
167    let mut end = next;
168    let slice = rope.byte_slice(start..next).to_string();
169    if slice.ends_with('\n') {
170        end = end.saturating_sub(1);
171        if slice.ends_with("\r\n") {
172            end = end.saturating_sub(1);
173        }
174    }
175    end
176}
177
178fn is_blank_line(rope: &Rope, line: usize) -> bool {
179    let start = rope.line_to_byte(line);
180    let end = line_content_end(rope, line);
181    rope.byte_slice(start..end).to_string().trim().is_empty()
182}
183
184fn contains_range(outer: Range, inner: Range) -> bool {
185    outer.start <= inner.start && outer.end >= inner.end
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn word_selects_identifier() {
194        let rope = Rope::from_str("hello world");
195        let sel = word_at(&rope, Position::new(0, 7));
196        assert_eq!(sel.anchor, Position::new(0, 6));
197        assert_eq!(sel.head, Position::new(0, 11));
198    }
199
200    #[test]
201    fn paragraph_spans_until_blank_lines() {
202        let rope = Rope::from_str("a\nb\n\nc\n");
203        let sel = paragraph_at(&rope, Position::new(1, 0));
204        assert_eq!(sel.anchor, Position::ZERO);
205        assert_eq!(sel.head, Position::new(1, 1));
206    }
207}