summaryrefslogtreecommitdiff
path: root/helix-core/src/match_brackets.rs
blob: 2d2eb4a9008c1728b3e2d6c1cbb750569f56c698 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use crate::{Range, Rope, Selection, Syntax};

const PAIRS: &[(char, char)] = &[('(', ')'), ('{', '}'), ('[', ']'), ('<', '>')];
// limit matching pairs to only ( ) { } [ ] < >

#[must_use]
pub fn find(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<usize> {
    let tree = syntax.tree();

    let byte_pos = doc.char_to_byte(pos);

    // most naive implementation: find the innermost syntax node, if we're at the edge of a node,
    // return the other edge.

    let mut node = match tree
        .root_node()
        .named_descendant_for_byte_range(byte_pos, byte_pos)
    {
        Some(node) => node,
        None => return None,
    };

    if node.is_error() {
        return None;
    }

    let start_byte = node.start_byte();
    let end_byte = node.end_byte() - 1; // it's end exclusive

    if PAIRS.contains(&(doc.char(start_byte), doc.char(end_byte))) {
        if start_byte == byte_pos {
            return Some(doc.byte_to_char(end_byte));
        }

        if end_byte == byte_pos {
            return Some(doc.byte_to_char(start_byte));
        }
    }

    None
}