Debian Codegraph @

helix-core/src/textobject.rs

raw symbols SCIP
1 use std::fmt::Display;
2
3 use ropey::RopeSlice;
4
5 use crate::chars::{categorize_char, char_is_whitespace, CharCategory};
6 use crate::graphemes::{next_grapheme_boundary, prev_grapheme_boundary};
7 use crate::line_ending::rope_is_line_ending;
8 use crate::movement::Direction;
9 use crate::syntax;
10 use crate::Range;
11 use crate::{surround, Syntax};
12
13 fn find_word_boundary(slice: RopeSlice, mut pos: usize, direction: Direction, long: bool) -> usize {
14 use CharCategory::{Eol, Whitespace};
15
16 let iter = match direction {
17 Direction::Forward => slice.chars_at(pos),
18 Direction::Backward => {
19 let mut iter = slice.chars_at(pos);
20 iter.reverse();
21 iter
22 }
23 };
24
25 let mut prev_category = match direction {
26 Direction::Forward if pos == 0 => Whitespace,
27 Direction::Forward => categorize_char(slice.char(pos - 1)),
28 Direction::Backward if pos == slice.len_chars() => Whitespace,
29 Direction::Backward => categorize_char(slice.char(pos)),
30 };
31
32 for ch in iter {
33 match categorize_char(ch) {
34 Eol | Whitespace => return pos,
35 category => {
36 if !long && category != prev_category && pos != 0 && pos != slice.len_chars() {
37 return pos;
38 } else {
39 match direction {
40 Direction::Forward => pos += 1,
41 Direction::Backward => pos = pos.saturating_sub(1),
42 }
43 prev_category = category;
44 }
45 }
46 }
47 }
48
49 pos
50 }
51
52 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
53 pub enum TextObject {
54 Around,
55 Inside,
56 /// Used for moving between objects.
57 Movement,
58 }
59
60 impl Display for TextObject {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 f.write_str(match self {
63 Self::Around => "around",
64 Self::Inside => "inside",
65 Self::Movement => "movement",
66 })
67 }
68 }
69
70 // count doesn't do anything yet
71 pub fn textobject_word(
72 slice: RopeSlice,
73 range: Range,
74 textobject: TextObject,
75 _count: usize,
76 long: bool,
77 ) -> Range {
78 let pos = range.cursor(slice);
79
80 let word_start = find_word_boundary(slice, pos, Direction::Backward, long);
81 let word_end = match slice.get_char(pos).map(categorize_char) {
82 None | Some(CharCategory::Whitespace | CharCategory::Eol) => pos,
83 _ => find_word_boundary(slice, pos + 1, Direction::Forward, long),
84 };
85
86 // Special case.
87 if word_start == word_end {
88 return Range::new(word_start, word_end);
89 }
90
91 match textobject {
92 TextObject::Inside => Range::new(word_start, word_end),
93 TextObject::Around => {
94 let whitespace_count_right = slice
95 .chars_at(word_end)
96 .take_while(|c| char_is_whitespace(*c))
97 .count();
98
99 if whitespace_count_right > 0 {
100 Range::new(word_start, word_end + whitespace_count_right)
101 } else {
102 let whitespace_count_left = {
103 let mut iter = slice.chars_at(word_start);
104 iter.reverse();
105 iter.take_while(|c| char_is_whitespace(*c)).count()
106 };
107 Range::new(word_start - whitespace_count_left, word_end)
108 }
109 }
110 TextObject::Movement => unreachable!(),
111 }
112 }
113
114 pub fn textobject_paragraph(
115 slice: RopeSlice,
116 range: Range,
117 textobject: TextObject,
118 count: usize,
119 ) -> Range {
120 let mut line = range.cursor_line(slice);
121 let prev_line_empty = rope_is_line_ending(slice.line(line.saturating_sub(1)));
122 let curr_line_empty = rope_is_line_ending(slice.line(line));
123 let next_line_empty =
124 line + 1 >= slice.len_lines() || rope_is_line_ending(slice.line(line + 1));
125 let last_char =
126 prev_grapheme_boundary(slice, slice.line_to_char(line + 1)) == range.cursor(slice);
127 let prev_empty_to_line = prev_line_empty && !curr_line_empty;
128 let curr_empty_to_line = curr_line_empty && !next_line_empty;
129
130 // skip character before paragraph boundary
131 let mut line_back = line; // line but backwards
132 if prev_empty_to_line || curr_empty_to_line {
133 line_back += 1;
134 }
135 // do not include current paragraph on paragraph end (include next)
136 if !(curr_empty_to_line && last_char) {
137 let mut lines = slice.lines_at(line_back);
138 lines.reverse();
139 let mut lines = lines.map(rope_is_line_ending).peekable();
140 while lines.next_if(|&e| e).is_some() {
141 line_back -= 1;
142 }
143 while lines.next_if(|&e| !e).is_some() {
144 line_back -= 1;
145 }
146 }
147
148 // skip character after paragraph boundary
149 if curr_empty_to_line && last_char {
150 line += 1;
151 }
152 let mut lines = slice.lines_at(line).map(rope_is_line_ending).peekable();
153 let mut count_done = 0; // count how many non-whitespace paragraphs done
154 for _ in 0..count {
155 let mut done = false;
156 while lines.next_if(|&e| !e).is_some() {
157 line += 1;
158 done = true;
159 }
160 while lines.next_if(|&e| e).is_some() {
161 line += 1;
162 }
163 count_done += done as usize;
164 }
165
166 // search one paragraph backwards for last paragraph
167 // makes `map` at the end of the paragraph with trailing newlines useful
168 let last_paragraph = count_done != count && lines.peek().is_none();
169 if last_paragraph {
170 let mut lines = slice.lines_at(line_back);
171 lines.reverse();
172 let mut lines = lines.map(rope_is_line_ending).peekable();
173 while lines.next_if(|&e| e).is_some() {
174 line_back -= 1;
175 }
176 while lines.next_if(|&e| !e).is_some() {
177 line_back -= 1;
178 }
179 }
180
181 // handle last whitespaces part separately depending on textobject
182 match textobject {
183 TextObject::Around => {}
184 TextObject::Inside => {
185 // remove last whitespace paragraph
186 let mut lines = slice.lines_at(line);
187 lines.reverse();
188 let mut lines = lines.map(rope_is_line_ending).peekable();
189 while lines.next_if(|&e| e).is_some() {
190 line -= 1;
191 }
192 }
193 TextObject::Movement => unreachable!(),
194 }
195
196 let anchor = slice.line_to_char(line_back);
197 let head = slice.line_to_char(line);
198 Range::new(anchor, head)
199 }
200
201 pub fn textobject_pair_surround(
202 syntax: Option<&Syntax>,
203 slice: RopeSlice,
204 range: Range,
205 textobject: TextObject,
206 ch: char,
207 count: usize,
208 ) -> Range {
209 textobject_pair_surround_impl(syntax, slice, range, textobject, Some(ch), count)
210 }
211
212 pub fn textobject_pair_surround_closest(
213 syntax: Option<&Syntax>,
214 slice: RopeSlice,
215 range: Range,
216 textobject: TextObject,
217 count: usize,
218 ) -> Range {
219 textobject_pair_surround_impl(syntax, slice, range, textobject, None, count)
220 }
221
222 fn textobject_pair_surround_impl(
223 syntax: Option<&Syntax>,
224 slice: RopeSlice,
225 range: Range,
226 textobject: TextObject,
227 ch: Option<char>,
228 count: usize,
229 ) -> Range {
230 let pair_pos = match ch {
231 Some(ch) => surround::find_nth_pairs_pos(syntax, slice, ch, range, count),
232 None => surround::find_nth_closest_pairs_pos(syntax, slice, range, count),
233 };
234 pair_pos
235 .map(|(anchor, head)| match textobject {
236 TextObject::Inside => {
237 if anchor < head {
238 Range::new(next_grapheme_boundary(slice, anchor), head)
239 } else {
240 Range::new(anchor, next_grapheme_boundary(slice, head))
241 }
242 }
243 TextObject::Around => {
244 if anchor < head {
245 Range::new(anchor, next_grapheme_boundary(slice, head))
246 } else {
247 Range::new(next_grapheme_boundary(slice, anchor), head)
248 }
249 }
250 TextObject::Movement => unreachable!(),
251 })
252 .unwrap_or(range)
253 }
254
255 /// Transform the given range to select text objects based on tree-sitter.
256 /// `object_name` is a query capture base name like "function", "class", etc.
257 /// `slice_tree` is the tree-sitter node corresponding to given text slice.
258 pub fn textobject_treesitter(
259 slice: RopeSlice,
260 range: Range,
261 textobject: TextObject,
262 object_name: &str,
263 syntax: &Syntax,
264 loader: &syntax::Loader,
265 _count: usize,
266 ) -> Range {
267 let byte_pos = slice.char_to_byte(range.cursor(slice));
268 let layer = syntax.layer_for_byte_range(byte_pos as u32, byte_pos as u32);
269 let root = syntax
270 .tree_for_byte_range(byte_pos as u32, byte_pos as u32)
271 .root_node();
272 let textobject_query = loader.textobject_query(syntax.layer(layer).language);
273 let get_range = move || -> Option<Range> {
274 let capture_name = format!("{}.{}", object_name, textobject); // eg. function.inner
275 let node = textobject_query?
276 .capture_nodes(&capture_name, &root, slice)?
277 .filter(|node| node.byte_range().contains(&byte_pos))
278 .min_by_key(|node| node.byte_range().len())?;
279
280 let len = slice.len_bytes();
281 let start_byte = node.start_byte();
282 let end_byte = node.end_byte();
283 if start_byte >= len || end_byte >= len {
284 return None;
285 }
286
287 let start_char = slice.byte_to_char(start_byte);
288 let end_char = slice.byte_to_char(end_byte);
289
290 Some(Range::new(start_char, end_char))
291 };
292 get_range().unwrap_or(range)
293 }
294
295 #[cfg(test)]
296 mod test {
297 use super::TextObject::*;
298 use super::*;
299
300 use crate::Range;
301 use ropey::Rope;
302
303 #[test]
304 fn test_textobject_word() {
305 // (text, [(char position, textobject, final range), ...])
306 let tests = &[
307 (
308 "cursor at beginning of doc",
309 vec![(0, Inside, (0, 6)), (0, Around, (0, 7))],
310 ),
311 (
312 "cursor at middle of word",
313 vec![
314 (13, Inside, (10, 16)),
315 (10, Inside, (10, 16)),
316 (15, Inside, (10, 16)),
317 (13, Around, (10, 17)),
318 (10, Around, (10, 17)),
319 (15, Around, (10, 17)),
320 ],
321 ),
322 (
323 "cursor between word whitespace",
324 vec![(6, Inside, (6, 6)), (6, Around, (6, 6))],
325 ),
326 (
327 "cursor on word before newline\n",
328 vec![
329 (22, Inside, (22, 29)),
330 (28, Inside, (22, 29)),
331 (25, Inside, (22, 29)),
332 (22, Around, (21, 29)),
333 (28, Around, (21, 29)),
334 (25, Around, (21, 29)),
335 ],
336 ),
337 (
338 "cursor on newline\nnext line",
339 vec![(17, Inside, (17, 17)), (17, Around, (17, 17))],
340 ),
341 (
342 "cursor on word after newline\nnext line",
343 vec![
344 (29, Inside, (29, 33)),
345 (30, Inside, (29, 33)),
346 (32, Inside, (29, 33)),
347 (29, Around, (29, 34)),
348 (30, Around, (29, 34)),
349 (32, Around, (29, 34)),
350 ],
351 ),
352 (
353 "cursor on #$%:;* punctuation",
354 vec![
355 (13, Inside, (10, 16)),
356 (10, Inside, (10, 16)),
357 (15, Inside, (10, 16)),
358 (13, Around, (10, 17)),
359 (10, Around, (10, 17)),
360 (15, Around, (10, 17)),
361 ],
362 ),
363 (
364 "cursor on punc%^#$:;.tuation",
365 vec![
366 (14, Inside, (14, 21)),
367 (20, Inside, (14, 21)),
368 (17, Inside, (14, 21)),
369 (14, Around, (14, 21)),
370 (20, Around, (14, 21)),
371 (17, Around, (14, 21)),
372 ],
373 ),
374 (
375 "cursor in extra whitespace",
376 vec![
377 (9, Inside, (9, 9)),
378 (10, Inside, (10, 10)),
379 (11, Inside, (11, 11)),
380 (9, Around, (9, 9)),
381 (10, Around, (10, 10)),
382 (11, Around, (11, 11)),
383 ],
384 ),
385 (
386 "cursor on word with extra whitespace",
387 vec![(11, Inside, (10, 14)), (11, Around, (10, 17))],
388 ),
389 (
390 "cursor at end with extra whitespace",
391 vec![(28, Inside, (27, 37)), (28, Around, (24, 37))],
392 ),
393 (
394 "cursor at end of doc",
395 vec![(19, Inside, (17, 20)), (19, Around, (16, 20))],
396 ),
397 ];
398
399 for (sample, scenario) in tests {
400 let doc = Rope::from(*sample);
401 let slice = doc.slice(..);
402 for &case in scenario {
403 let (pos, objtype, expected_range) = case;
404 // cursor is a single width selection
405 let range = Range::new(pos, pos + 1);
406 let result = textobject_word(slice, range, objtype, 1, false);
407 assert_eq!(
408 result,
409 expected_range.into(),
410 "\nCase failed: {:?} - {:?}",
411 sample,
412 case
413 );
414 }
415 }
416 }
417
418 #[test]
419 fn test_textobject_paragraph_inside_single() {
420 let tests = [
421 ("#[|]#", "#[|]#"),
422 ("firs#[t|]#\n\nparagraph\n\n", "#[first\n|]#\nparagraph\n\n"),
423 (
424 "second\n\npa#[r|]#agraph\n\n",
425 "second\n\n#[paragraph\n|]#\n",
426 ),
427 ("#[f|]#irst char\n\n", "#[first char\n|]#\n"),
428 ("last char\n#[\n|]#", "#[last char\n|]#\n"),
429 (
430 "empty to line\n#[\n|]#paragraph boundary\n\n",
431 "empty to line\n\n#[paragraph boundary\n|]#\n",
432 ),
433 (
434 "line to empty\n\n#[p|]#aragraph boundary\n\n",
435 "line to empty\n\n#[paragraph boundary\n|]#\n",
436 ),
437 ];
438
439 for (before, expected) in tests {
440 let (s, selection) = crate::test::print(before);
441 let text = Rope::from(s.as_str());
442 let selection = selection
443 .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 1));
444 let actual = crate::test::plain(s.as_ref(), &selection);
445 assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
446 }
447 }
448
449 #[test]
450 fn test_textobject_paragraph_inside_double() {
451 let tests = [
452 (
453 "last two\n\n#[p|]#aragraph\n\nwithout whitespaces\n\n",
454 "last two\n\n#[paragraph\n\nwithout whitespaces\n|]#\n",
455 ),
456 (
457 "last two\n#[\n|]#paragraph\n\nwithout whitespaces\n\n",
458 "last two\n\n#[paragraph\n\nwithout whitespaces\n|]#\n",
459 ),
460 ];
461
462 for (before, expected) in tests {
463 let (s, selection) = crate::test::print(before);
464 let text = Rope::from(s.as_str());
465 let selection = selection
466 .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Inside, 2));
467 let actual = crate::test::plain(s.as_ref(), &selection);
468 assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
469 }
470 }
471
472 #[test]
473 fn test_textobject_paragraph_around_single() {
474 let tests = [
475 ("#[|]#", "#[|]#"),
476 ("firs#[t|]#\n\nparagraph\n\n", "#[first\n\n|]#paragraph\n\n"),
477 (
478 "second\n\npa#[r|]#agraph\n\n",
479 "second\n\n#[paragraph\n\n|]#",
480 ),
481 ("#[f|]#irst char\n\n", "#[first char\n\n|]#"),
482 ("last char\n#[\n|]#", "#[last char\n\n|]#"),
483 (
484 "empty to line\n#[\n|]#paragraph boundary\n\n",
485 "empty to line\n\n#[paragraph boundary\n\n|]#",
486 ),
487 (
488 "line to empty\n\n#[p|]#aragraph boundary\n\n",
489 "line to empty\n\n#[paragraph boundary\n\n|]#",
490 ),
491 ];
492
493 for (before, expected) in tests {
494 let (s, selection) = crate::test::print(before);
495 let text = Rope::from(s.as_str());
496 let selection = selection
497 .transform(|r| textobject_paragraph(text.slice(..), r, TextObject::Around, 1));
498 let actual = crate::test::plain(s.as_ref(), &selection);
499 assert_eq!(actual, expected, "\nbefore: `{:?}`", before);
500 }
501 }
502
503 #[test]
504 fn test_textobject_surround() {
505 // (text, [(cursor position, textobject, final range, surround char, count), ...])
506 let tests = &[
507 (
508 "simple (single) surround pairs",
509 vec![
510 (3, Inside, (3, 3), '(', 1),
511 (7, Inside, (8, 14), ')', 1),
512 (10, Inside, (8, 14), '(', 1),
513 (14, Inside, (8, 14), ')', 1),
514 (3, Around, (3, 3), '(', 1),
515 (7, Around, (7, 15), ')', 1),
516 (10, Around, (7, 15), '(', 1),
517 (14, Around, (7, 15), ')', 1),
518 ],
519 ),
520 (
521 "samexx 'single' surround pairs",
522 vec![
523 (3, Inside, (3, 3), '\'', 1),
524 (7, Inside, (7, 7), '\'', 1),
525 (10, Inside, (8, 14), '\'', 1),
526 (14, Inside, (14, 14), '\'', 1),
527 (3, Around, (3, 3), '\'', 1),
528 (7, Around, (7, 7), '\'', 1),
529 (10, Around, (7, 15), '\'', 1),
530 (14, Around, (14, 14), '\'', 1),
531 ],
532 ),
533 (
534 "(nested (surround (pairs)) 3 levels)",
535 vec![
536 (0, Inside, (1, 35), '(', 1),
537 (6, Inside, (1, 35), ')', 1),
538 (8, Inside, (9, 25), '(', 1),
539 (8, Inside, (9, 35), ')', 2),
540 (20, Inside, (9, 25), '(', 2),
541 (20, Inside, (1, 35), ')', 3),
542 (0, Around, (0, 36), '(', 1),
543 (6, Around, (0, 36), ')', 1),
544 (8, Around, (8, 26), '(', 1),
545 (8, Around, (8, 36), ')', 2),
546 (20, Around, (8, 26), '(', 2),
547 (20, Around, (0, 36), ')', 3),
548 ],
549 ),
550 (
551 "(mixed {surround [pair] same} line)",
552 vec![
553 (2, Inside, (1, 34), '(', 1),
554 (9, Inside, (8, 28), '{', 1),
555 (18, Inside, (18, 22), '[', 1),
556 (2, Around, (0, 35), '(', 1),
557 (9, Around, (7, 29), '{', 1),
558 (18, Around, (17, 23), '[', 1),
559 ],
560 ),
561 (
562 "(stepped (surround) pairs (should) skip)",
563 vec![(22, Inside, (1, 39), '(', 1), (22, Around, (0, 40), '(', 1)],
564 ),
565 (
566 "[surround pairs{\non different]\nlines}",
567 vec![
568 (7, Inside, (1, 29), '[', 1),
569 (15, Inside, (16, 36), '{', 1),
570 (7, Around, (0, 30), '[', 1),
571 (15, Around, (15, 37), '{', 1),
572 ],
573 ),
574 ];
575
576 for (sample, scenario) in tests {
577 let doc = Rope::from(*sample);
578 let slice = doc.slice(..);
579 for &case in scenario {
580 let (pos, objtype, expected_range, ch, count) = case;
581 let result =
582 textobject_pair_surround(None, slice, Range::point(pos), objtype, ch, count);
583 assert_eq!(
584 result,
585 expected_range.into(),
586 "\nCase failed: {:?} - {:?}",
587 sample,
588 case
589 );
590 }
591 }
592 }
593 }