Debian Codegraph @

helix-core/src/match_brackets.rs

raw symbols SCIP
1 use std::iter;
2
3 use crate::tree_sitter::Node;
4 use ropey::RopeSlice;
5
6 use crate::movement::Direction::{self, Backward, Forward};
7 use crate::Syntax;
8
9 const MAX_PLAINTEXT_SCAN: usize = 10000;
10 const MATCH_LIMIT: usize = 16;
11
12 pub const BRACKETS: [(char, char); 9] = [
13 ('(', ')'),
14 ('{', '}'),
15 ('[', ']'),
16 ('<', '>'),
17 ('‘', '’'),
18 ('“', '”'),
19 ('«', '»'),
20 ('「', '」'),
21 ('(', ')'),
22 ];
23
24 // The difference between BRACKETS and PAIRS is that we can find matching
25 // BRACKETS in a plain text file, but we can't do the same for PAIRs.
26 // PAIRS also contains all BRACKETS.
27 pub const PAIRS: [(char, char); BRACKETS.len() + 4] = {
28 let mut pairs = [(' ', ' '); BRACKETS.len() + 4];
29 let mut idx = 0;
30 while idx < BRACKETS.len() {
31 pairs[idx] = BRACKETS[idx];
32 idx += 1;
33 }
34 pairs[idx] = ('"', '"');
35 pairs[idx + 1] = ('\'', '\'');
36 pairs[idx + 2] = ('`', '`');
37 // Rust closure parameters use `|...|` delimiters. Tree-sitter exposes
38 // them as a `closure_parameters` node whose first and last children are
39 // both `|`, so the tree-sitter path in `find_pair` matches them
40 // correctly without any false positives for bitwise-OR operators.
41 pairs[idx + 3] = ('|', '|');
42 pairs
43 };
44
45 /// Returns the position of the matching bracket under cursor.
46 ///
47 /// If the cursor is on the opening bracket, the position of
48 /// the closing bracket is returned. If the cursor on the closing
49 /// bracket, the position of the opening bracket is returned.
50 ///
51 /// If the cursor is not on a bracket, `None` is returned.
52 ///
53 /// If no matching bracket is found, `None` is returned.
54 #[must_use]
55 pub fn find_matching_bracket(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
56 if pos >= doc.len_chars() || !is_valid_pair(doc.char(pos)) {
57 return None;
58 }
59 find_pair(syntax, doc, pos, false)
60 }
61
62 // Returns the position of the bracket that is closing the current scope.
63 //
64 // If the cursor is on an opening or closing bracket, the function
65 // behaves equivalent to [`find_matching_bracket`].
66 //
67 // If the cursor position is within a scope, the function searches
68 // for the surrounding scope that is surrounded by brackets and
69 // returns the position of the closing bracket for that scope.
70 //
71 // If no surrounding scope is found, the function returns `None`.
72 #[must_use]
73 pub fn find_matching_bracket_fuzzy(syntax: &Syntax, doc: RopeSlice, pos: usize) -> Option<usize> {
74 find_pair(syntax, doc, pos, true)
75 }
76
77 fn find_pair(
78 syntax: &Syntax,
79 doc: RopeSlice,
80 pos_: usize,
81 traverse_parents: bool,
82 ) -> Option<usize> {
83 let pos = doc.char_to_byte(pos_) as u32;
84
85 let root = syntax.tree_for_byte_range(pos, pos).root_node();
86 let mut node = root.descendant_for_byte_range(pos, pos)?;
87
88 loop {
89 if node.is_named() && node.child_count() >= 2 {
90 let open = node.child(0).unwrap();
91 let close = node.child(node.child_count() - 1).unwrap();
92
93 if let (Some((start_pos, open)), Some((end_pos, close))) =
94 (as_char(doc, &open), as_char(doc, &close))
95 {
96 if PAIRS.contains(&(open, close)) && start_pos <= pos_ && pos_ <= end_pos {
97 if end_pos == pos_ {
98 return Some(start_pos);
99 }
100
101 // We return the end char if the cursor is either on the start char
102 // or at some arbitrary position between start and end char.
103 if traverse_parents || start_pos == pos_ {
104 return Some(end_pos);
105 }
106 }
107 }
108 }
109 // this node itselt wasn't a pair but maybe its siblings are
110
111 if let Some((start_char, end_char)) = as_close_pair(doc, &node) {
112 if let Some(pair_start) =
113 find_pair_end(doc, node.prev_sibling(), start_char, end_char, Backward)
114 {
115 return Some(pair_start);
116 }
117 }
118 if let Some((start_char, end_char)) = as_open_pair(doc, &node) {
119 if let Some(pair_end) =
120 find_pair_end(doc, node.next_sibling(), start_char, end_char, Forward)
121 {
122 return Some(pair_end);
123 }
124 }
125
126 if traverse_parents {
127 for sibling in
128 iter::successors(node.next_sibling(), |node| node.next_sibling()).take(MATCH_LIMIT)
129 {
130 let Some((start_char, end_char)) = as_close_pair(doc, &sibling) else {
131 continue;
132 };
133 if find_pair_end(doc, sibling.prev_sibling(), start_char, end_char, Backward)
134 .is_some()
135 {
136 return doc.try_byte_to_char(sibling.start_byte() as usize).ok();
137 }
138 }
139 } else if node.is_named() {
140 break;
141 }
142
143 let Some(parent) = node.parent() else {
144 break;
145 };
146 node = parent;
147 }
148 let node = root.named_descendant_for_byte_range(pos, pos + 1)?;
149 if node.child_count() != 0 {
150 return None;
151 }
152 let node_start = doc.byte_to_char(node.start_byte() as usize);
153 let node_text = doc.byte_slice(node.start_byte() as usize..node.end_byte() as usize);
154 find_matching_bracket_plaintext(node_text, pos_ - node_start).map(|pos| pos + node_start)
155 }
156
157 /// Returns the position of the matching bracket under cursor.
158 /// This function works on plain text and ignores tree-sitter grammar.
159 /// The search is limited to `MAX_PLAINTEXT_SCAN` characters
160 ///
161 /// If the cursor is on the opening bracket, the position of
162 /// the closing bracket is returned. If the cursor on the closing
163 /// bracket, the position of the opening bracket is returned.
164 ///
165 /// If the cursor is not on a bracket, `None` is returned.
166 ///
167 /// If no matching bracket is found, `None` is returned.
168 #[must_use]
169 pub fn find_matching_bracket_plaintext(doc: RopeSlice, cursor_pos: usize) -> Option<usize> {
170 let bracket = doc.get_char(cursor_pos)?;
171 let matching_bracket = {
172 let pair = get_pair(bracket);
173 if pair.0 == bracket {
174 pair.1
175 } else {
176 pair.0
177 }
178 };
179 // Don't do anything when the cursor is not on top of a bracket.
180 if !is_valid_bracket(bracket) {
181 return None;
182 }
183
184 // Determine the direction of the matching.
185 let is_fwd = is_open_bracket(bracket);
186 let chars_iter = if is_fwd {
187 doc.chars_at(cursor_pos + 1)
188 } else {
189 doc.chars_at(cursor_pos).reversed()
190 };
191
192 let mut open_cnt = 1;
193
194 for (i, candidate) in chars_iter.take(MAX_PLAINTEXT_SCAN).enumerate() {
195 if candidate == bracket {
196 open_cnt += 1;
197 } else if candidate == matching_bracket {
198 // Return when all pending brackets have been closed.
199 if open_cnt == 1 {
200 return Some(if is_fwd {
201 cursor_pos + i + 1
202 } else {
203 cursor_pos - i - 1
204 });
205 }
206 open_cnt -= 1;
207 }
208 }
209
210 None
211 }
212
213 /// Returns the open and closing chars pair. If not found in
214 /// [`BRACKETS`] returns (ch, ch).
215 ///
216 /// ```
217 /// use helix_core::match_brackets::get_pair;
218 ///
219 /// assert_eq!(get_pair('['), ('[', ']'));
220 /// assert_eq!(get_pair('}'), ('{', '}'));
221 /// assert_eq!(get_pair('"'), ('"', '"'));
222 /// ```
223 pub fn get_pair(ch: char) -> (char, char) {
224 PAIRS
225 .iter()
226 .find(|(open, close)| *open == ch || *close == ch)
227 .copied()
228 .unwrap_or((ch, ch))
229 }
230
231 pub fn is_open_bracket(ch: char) -> bool {
232 BRACKETS.iter().any(|(l, _)| *l == ch)
233 }
234
235 pub fn is_close_bracket(ch: char) -> bool {
236 BRACKETS.iter().any(|(_, r)| *r == ch)
237 }
238
239 pub fn is_valid_bracket(ch: char) -> bool {
240 BRACKETS.iter().any(|(l, r)| *l == ch || *r == ch)
241 }
242
243 pub fn is_open_pair(ch: char) -> bool {
244 PAIRS.iter().any(|(l, _)| *l == ch)
245 }
246
247 pub fn is_close_pair(ch: char) -> bool {
248 PAIRS.iter().any(|(_, r)| *r == ch)
249 }
250
251 pub fn is_valid_pair(ch: char) -> bool {
252 PAIRS.iter().any(|(l, r)| *l == ch || *r == ch)
253 }
254
255 /// Tests if this node is a pair close char and returns the expected open char
256 /// and close char contained in this node
257 fn as_close_pair(doc: RopeSlice, node: &Node) -> Option<(char, char)> {
258 let close = as_char(doc, node)?.1;
259 PAIRS
260 .iter()
261 .find_map(|&(open, close_)| (close_ == close).then_some((close, open)))
262 }
263
264 /// Checks if `node` or its siblings (at most MATCH_LIMIT nodes) is the specified closing char
265 ///
266 /// # Returns
267 ///
268 /// The position of the found node or `None` otherwise
269 fn find_pair_end(
270 doc: RopeSlice,
271 node: Option<Node>,
272 start_char: char,
273 end_char: char,
274 direction: Direction,
275 ) -> Option<usize> {
276 let advance = match direction {
277 Forward => Node::next_sibling,
278 Backward => Node::prev_sibling,
279 };
280 let mut depth = 0;
281 iter::successors(node, advance)
282 .take(MATCH_LIMIT)
283 .find_map(|node| {
284 let (pos, c) = as_char(doc, &node)?;
285 if c == end_char {
286 if depth == 0 {
287 return Some(pos);
288 }
289 depth -= 1;
290 } else if c == start_char {
291 depth += 1;
292 }
293 None
294 })
295 }
296
297 /// Tests if this node is a pair open char and returns the expected close char
298 /// and open char contained in this node
299 fn as_open_pair(doc: RopeSlice, node: &Node) -> Option<(char, char)> {
300 let open = as_char(doc, node)?.1;
301 PAIRS
302 .iter()
303 .find_map(|&(open_, close)| (open_ == open).then_some((open, close)))
304 }
305
306 /// If node is a single char return it (and its char position)
307 fn as_char(doc: RopeSlice, node: &Node) -> Option<(usize, char)> {
308 // TODO: multi char/non ASCII pairs
309 if node.byte_range().len() != 1 {
310 return None;
311 }
312 let pos = doc.try_byte_to_char(node.start_byte() as usize).ok()?;
313 Some((pos, doc.char(pos)))
314 }
315
316 #[cfg(test)]
317 mod tests {
318 use super::*;
319
320 #[test]
321 fn find_matching_bracket_empty_file() {
322 let actual = find_matching_bracket_plaintext("".into(), 0);
323 assert_eq!(actual, None);
324 }
325
326 #[test]
327 fn test_find_matching_bracket_current_line_plaintext() {
328 let assert = |input: &str, pos, expected| {
329 let input = RopeSlice::from(input);
330 let actual = find_matching_bracket_plaintext(input, pos);
331 assert_eq!(expected, actual.unwrap());
332
333 let actual = find_matching_bracket_plaintext(input, expected);
334 assert_eq!(pos, actual.unwrap(), "expected symmetrical behaviour");
335 };
336
337 assert("(hello)", 0, 6);
338 assert("((hello))", 0, 8);
339 assert("((hello))", 1, 7);
340 assert("(((hello)))", 2, 8);
341
342 assert("key: ${value}", 6, 12);
343 assert("key: ${value} # (some comment)", 16, 29);
344
345 assert("(paren (paren {bracket}))", 0, 24);
346 assert("(paren (paren {bracket}))", 7, 23);
347 assert("(paren (paren {bracket}))", 14, 22);
348
349 assert("(prev line\n ) (middle) ( \n next line)", 0, 12);
350 assert("(prev line\n ) (middle) ( \n next line)", 14, 21);
351 assert("(prev line\n ) (middle) ( \n next line)", 23, 36);
352 }
353 }