Debian Codegraph @

helix-core/src/surround.rs

raw symbols SCIP
1 use std::fmt::Display;
2
3 use crate::{
4 graphemes::next_grapheme_boundary,
5 match_brackets::{
6 self, find_matching_bracket, find_matching_bracket_fuzzy, get_pair, is_close_bracket,
7 is_open_bracket,
8 },
9 movement::Direction,
10 search, Range, Selection, Syntax,
11 };
12 use ropey::RopeSlice;
13
14 #[derive(Debug, PartialEq, Eq)]
15 pub enum Error {
16 PairNotFound,
17 CursorOverlap,
18 RangeExceedsText,
19 CursorOnAmbiguousPair,
20 }
21
22 impl Display for Error {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 f.write_str(match *self {
25 Error::PairNotFound => "Surround pair not found around all cursors",
26 Error::CursorOverlap => "Cursors overlap for a single surround pair range",
27 Error::RangeExceedsText => "Cursor range exceeds text length",
28 Error::CursorOnAmbiguousPair => "Cursor on ambiguous surround pair",
29 })
30 }
31 }
32
33 type Result<T> = std::result::Result<T, Error>;
34
35 /// Finds the position of surround pairs of any [`crate::match_brackets::PAIRS`]
36 /// using tree-sitter when possible.
37 ///
38 /// # Returns
39 ///
40 /// Tuple `(anchor, head)`, meaning it is not always ordered.
41 pub fn find_nth_closest_pairs_pos(
42 syntax: Option<&Syntax>,
43 text: RopeSlice,
44 range: Range,
45 skip: usize,
46 ) -> Result<(usize, usize)> {
47 match syntax {
48 Some(syntax) => find_nth_closest_pairs_ts(syntax, text, range, skip),
49 None => find_nth_closest_pairs_plain(text, range, skip),
50 }
51 }
52
53 fn find_nth_closest_pairs_ts(
54 syntax: &Syntax,
55 text: RopeSlice,
56 range: Range,
57 mut skip: usize,
58 ) -> Result<(usize, usize)> {
59 let mut opening = range.from();
60 // We want to expand the selection if we are already on the found pair,
61 // otherwise we would need to subtract "-1" from "range.to()".
62 let mut closing = range.to();
63
64 while skip > 0 {
65 closing = find_matching_bracket_fuzzy(syntax, text, closing).ok_or(Error::PairNotFound)?;
66 opening = find_matching_bracket(syntax, text, closing).ok_or(Error::PairNotFound)?;
67 // If we're already on a closing bracket "find_matching_bracket_fuzzy" will return
68 // the position of the opening bracket.
69 if closing < opening {
70 (opening, closing) = (closing, opening);
71 }
72
73 // In case found brackets are partially inside current selection.
74 if range.from() < opening || closing < range.to() - 1 {
75 closing = next_grapheme_boundary(text, closing);
76 } else {
77 skip -= 1;
78 if skip != 0 {
79 closing = next_grapheme_boundary(text, closing);
80 }
81 }
82 }
83
84 // Keep the original direction.
85 if let Direction::Forward = range.direction() {
86 Ok((opening, closing))
87 } else {
88 Ok((closing, opening))
89 }
90 }
91
92 fn find_nth_closest_pairs_plain(
93 text: RopeSlice,
94 range: Range,
95 mut skip: usize,
96 ) -> Result<(usize, usize)> {
97 let mut stack = Vec::with_capacity(2);
98 let pos = range.from();
99 let mut close_pos = pos.saturating_sub(1);
100
101 for ch in text.chars_at(pos) {
102 close_pos += 1;
103
104 if is_open_bracket(ch) {
105 // Track open pairs encountered so that we can step over
106 // the corresponding close pairs that will come up further
107 // down the loop. We want to find a lone close pair whose
108 // open pair is before the cursor position.
109 stack.push(ch);
110 continue;
111 }
112
113 if !is_close_bracket(ch) {
114 // We don't care if this character isn't a brace pair item,
115 // so short circuit here.
116 continue;
117 }
118
119 let (open, close) = get_pair(ch);
120
121 if stack.last() == Some(&open) {
122 // If we are encountering the closing pair for an opener
123 // we just found while traversing, then its inside the
124 // selection and should be skipped over.
125 stack.pop();
126 continue;
127 }
128
129 match find_nth_open_pair(text, open, close, close_pos, 1) {
130 // Before we accept this pair, we want to ensure that the
131 // pair encloses the range rather than just the cursor.
132 Some(open_pos)
133 if open_pos <= pos.saturating_add(1)
134 && close_pos >= range.to().saturating_sub(1) =>
135 {
136 // Since we have special conditions for when to
137 // accept, we can't just pass the skip parameter on
138 // through to the find_nth_*_pair methods, so we
139 // track skips manually here.
140 if skip > 1 {
141 skip -= 1;
142 continue;
143 }
144
145 return match range.direction() {
146 Direction::Forward => Ok((open_pos, close_pos)),
147 Direction::Backward => Ok((close_pos, open_pos)),
148 };
149 }
150 _ => continue,
151 }
152 }
153
154 Err(Error::PairNotFound)
155 }
156
157 /// Find the position of surround pairs of `ch` which can be either a closing
158 /// or opening pair. `n` will skip n - 1 pairs (eg. n=2 will discard (only)
159 /// the first pair found and keep looking)
160 pub fn find_nth_pairs_pos(
161 syntax: Option<&Syntax>,
162 text: RopeSlice,
163 ch: char,
164 range: Range,
165 n: usize,
166 ) -> Result<(usize, usize)> {
167 if text.len_chars() < 2 {
168 return Err(Error::PairNotFound);
169 }
170 if range.to() >= text.len_chars() {
171 return Err(Error::RangeExceedsText);
172 }
173
174 let (open, close) = get_pair(ch);
175 let pos = range.cursor(text);
176
177 let (open, close) = if open == close {
178 if Some(open) == text.get_char(pos) {
179 // Cursor is directly on match character for which the opening and closing pairs are the same. For instance: ", ', `
180 //
181 // This is potentially ambiguous, because there's no way to know which side of the char we should be searching on.
182 syntax
183 .map_or_else(
184 || match_brackets::find_matching_bracket_plaintext(text.slice(..), pos),
185 |syntax| {
186 match_brackets::find_matching_bracket_fuzzy(syntax, text.slice(..), pos)
187 },
188 )
189 .map(|matching_pair_pos| {
190 if matching_pair_pos > pos {
191 (Some(pos), Some(matching_pair_pos))
192 } else {
193 (Some(matching_pair_pos), Some(pos))
194 }
195 })
196 .ok_or(Error::CursorOnAmbiguousPair)?
197 } else {
198 (
199 search::find_nth_char(n, text, open, pos, Direction::Backward),
200 search::find_nth_char(n, text, close, pos, Direction::Forward),
201 )
202 }
203 } else {
204 (
205 find_nth_open_pair(text, open, close, pos, n),
206 find_nth_close_pair(text, open, close, pos, n),
207 )
208 };
209
210 // preserve original direction
211 match range.direction() {
212 Direction::Forward => Option::zip(open, close).ok_or(Error::PairNotFound),
213 Direction::Backward => Option::zip(close, open).ok_or(Error::PairNotFound),
214 }
215 }
216
217 fn find_nth_open_pair(
218 text: RopeSlice,
219 open: char,
220 close: char,
221 mut pos: usize,
222 n: usize,
223 ) -> Option<usize> {
224 if pos >= text.len_chars() {
225 return None;
226 }
227
228 let mut chars = text.chars_at(pos + 1);
229
230 // Adjusts pos for the first iteration, and handles the case of the
231 // cursor being *on* the close character which will get falsely stepped over
232 // if not skipped here
233 if chars.prev()? == open {
234 return Some(pos);
235 }
236
237 for _ in 0..n {
238 let mut step_over: usize = 0;
239
240 loop {
241 let c = chars.prev()?;
242 pos = pos.saturating_sub(1);
243
244 // ignore other surround pairs that are enclosed *within* our search scope
245 if c == close {
246 step_over += 1;
247 } else if c == open {
248 if step_over == 0 {
249 break;
250 }
251
252 step_over = step_over.saturating_sub(1);
253 }
254 }
255 }
256
257 Some(pos)
258 }
259
260 fn find_nth_close_pair(
261 text: RopeSlice,
262 open: char,
263 close: char,
264 mut pos: usize,
265 n: usize,
266 ) -> Option<usize> {
267 if pos >= text.len_chars() {
268 return None;
269 }
270
271 let mut chars = text.chars_at(pos);
272
273 if chars.next()? == close {
274 return Some(pos);
275 }
276
277 for _ in 0..n {
278 let mut step_over: usize = 0;
279
280 loop {
281 let c = chars.next()?;
282 pos += 1;
283
284 if c == open {
285 step_over += 1;
286 } else if c == close {
287 if step_over == 0 {
288 break;
289 }
290
291 step_over = step_over.saturating_sub(1);
292 }
293 }
294 }
295
296 Some(pos)
297 }
298
299 /// Find position of surround characters around every cursor. Returns None
300 /// if any positions overlap. Note that the positions are in a flat Vec.
301 /// Use get_surround_pos().chunks(2) to get matching pairs of surround positions.
302 /// `ch` can be either closing or opening pair. If `ch` is None, surround pairs
303 /// are automatically detected around each cursor (note that this may result
304 /// in them selecting different surround characters for each selection).
305 pub fn get_surround_pos(
306 syntax: Option<&Syntax>,
307 text: RopeSlice,
308 selection: &Selection,
309 ch: Option<char>,
310 skip: usize,
311 ) -> Result<Vec<usize>> {
312 let mut change_pos = Vec::new();
313
314 for &range in selection {
315 let (open_pos, close_pos) = {
316 let range_raw = match ch {
317 Some(ch) => find_nth_pairs_pos(syntax, text, ch, range, skip)?,
318 None => find_nth_closest_pairs_pos(syntax, text, range, skip)?,
319 };
320 let range = Range::new(range_raw.0, range_raw.1);
321 (range.from(), range.to())
322 };
323 if change_pos.contains(&open_pos) || change_pos.contains(&close_pos) {
324 return Err(Error::CursorOverlap);
325 }
326 // ensure the positions are always paired in the forward direction
327 change_pos.extend_from_slice(&[open_pos.min(close_pos), close_pos.max(open_pos)]);
328 }
329 Ok(change_pos)
330 }
331
332 #[cfg(test)]
333 mod test {
334 use super::*;
335 use crate::Range;
336
337 use ropey::Rope;
338 use smallvec::SmallVec;
339
340 #[test]
341 fn test_get_surround_pos() {
342 #[rustfmt::skip]
343 let (doc, selection, expectations) =
344 rope_with_selections_and_expectations(
345 "(some) (chars)\n(newline)",
346 "_ ^ _ _ ^ _\n_ ^ _"
347 );
348
349 assert_eq!(
350 get_surround_pos(None, doc.slice(..), &selection, Some('('), 1).unwrap(),
351 expectations
352 );
353 }
354
355 #[test]
356 fn test_get_surround_pos_bail_different_surround_chars() {
357 #[rustfmt::skip]
358 let (doc, selection, _) =
359 rope_with_selections_and_expectations(
360 "[some]\n(chars)xx\n(newline)",
361 " ^ \n ^ \n "
362 );
363
364 assert_eq!(
365 get_surround_pos(None, doc.slice(..), &selection, Some('('), 1),
366 Err(Error::PairNotFound)
367 );
368 }
369
370 #[test]
371 fn test_get_surround_pos_bail_overlapping_surround_chars() {
372 #[rustfmt::skip]
373 let (doc, selection, _) =
374 rope_with_selections_and_expectations(
375 "[some]\n(chars)xx\n(newline)",
376 " \n ^ \n ^ "
377 );
378
379 assert_eq!(
380 get_surround_pos(None, doc.slice(..), &selection, Some('('), 1),
381 Err(Error::PairNotFound) // overlapping surround chars
382 );
383 }
384
385 #[test]
386 fn test_get_surround_pos_bail_cursor_overlap() {
387 #[rustfmt::skip]
388 let (doc, selection, _) =
389 rope_with_selections_and_expectations(
390 "[some]\n(chars)xx\n(newline)",
391 " ^^ \n \n "
392 );
393
394 assert_eq!(
395 get_surround_pos(None, doc.slice(..), &selection, Some('['), 1),
396 Err(Error::CursorOverlap)
397 );
398 }
399
400 #[test]
401 fn test_find_nth_pairs_pos_quote_success() {
402 #[rustfmt::skip]
403 let (doc, selection, expectations) =
404 rope_with_selections_and_expectations(
405 "some 'quoted text' on this 'line'\n'and this one'",
406 " _ ^ _ \n "
407 );
408
409 assert_eq!(2, expectations.len());
410 assert_eq!(
411 find_nth_pairs_pos(None, doc.slice(..), '\'', selection.primary(), 1)
412 .expect("find should succeed"),
413 (expectations[0], expectations[1])
414 )
415 }
416
417 #[test]
418 fn test_find_nth_pairs_pos_nested_quote_success() {
419 #[rustfmt::skip]
420 let (doc, selection, expectations) =
421 rope_with_selections_and_expectations(
422 "some 'nested 'quoted' text' on this 'line'\n'and this one'",
423 " _ ^ _ \n "
424 );
425
426 assert_eq!(2, expectations.len());
427 assert_eq!(
428 find_nth_pairs_pos(None, doc.slice(..), '\'', selection.primary(), 2)
429 .expect("find should succeed"),
430 (expectations[0], expectations[1])
431 )
432 }
433
434 #[test]
435 fn test_find_nth_pairs_pos_inside_quote_ambiguous() {
436 #[rustfmt::skip]
437 let (doc, selection, _) =
438 rope_with_selections_and_expectations(
439 "some 'nested 'quoted' text' on this 'line'\n'and this one'",
440 " ^ \n "
441 );
442
443 assert_eq!(
444 find_nth_pairs_pos(None, doc.slice(..), '\'', selection.primary(), 1),
445 Err(Error::CursorOnAmbiguousPair)
446 )
447 }
448
449 #[test]
450 fn test_find_nth_closest_pairs_pos_index_range_panic() {
451 #[rustfmt::skip]
452 let (doc, selection, _) =
453 rope_with_selections_and_expectations(
454 "(a)c)",
455 "^^^^^"
456 );
457
458 assert_eq!(
459 find_nth_closest_pairs_pos(None, doc.slice(..), selection.primary(), 1),
460 Err(Error::PairNotFound)
461 )
462 }
463
464 // Create a Rope and a matching Selection using a specification language.
465 // ^ is a single-point selection.
466 // _ is an expected index. These are returned as a Vec<usize> for use in assertions.
467 fn rope_with_selections_and_expectations(
468 text: &str,
469 spec: &str,
470 ) -> (Rope, Selection, Vec<usize>) {
471 if text.len() != spec.len() {
472 panic!("specification must match text length -- are newlines aligned?");
473 }
474
475 let rope = Rope::from(text);
476
477 let selections: SmallVec<[Range; 1]> = spec
478 .match_indices('^')
479 .map(|(i, _)| Range::point(i))
480 .collect();
481
482 let expectations: Vec<usize> = spec.match_indices('_').map(|(i, _)| i).collect();
483
484 (rope, Selection::new(selections, 0), expectations)
485 }
486 }