on master help sign in
Implement m / match_brackets (using tree sitter).
commit73c92a0bc1499f02092a7425c45d4992f4e573a1 authorBlaž Hrastnik <blaz@mxxn.io> dateMon 22 Mar 2021, 17:58 (6 years ago) parentbd607b4
5 files changed+53−1
helix-core/src/auto_pairs.rs+2 helix-core/src/lib.rs+1 helix-core/src/match_brackets.rs+34 helix-term/src/commands.rs+13−1 helix-term/src/keymap.rs+3
helix-core/src/auto_pairs.rs+2
@@ -1,6 +1,8 @@
11use crate::{Range, Rope, Selection, Tendril, Transaction};
22use smallvec::SmallVec;
33
4+// Heavily based on https://github.com/codemirror/closebrackets/
5+
46const PAIRS: &[(char, char)] = &[
57 ('(', ')'),
68 ('{', '}'),
helix-core/src/lib.rs+1
@@ -6,6 +6,7 @@ pub mod graphemes;
66mod history;
77pub mod indent;
88pub mod macros;
9+pub mod match_brackets;
910pub mod movement;
1011pub mod object;
1112mod position;
helix-core/src/match_brackets.rsnew file+34
@@ -0,0 +1,34 @@
1+use crate::{Range, Rope, Selection, Syntax};
2+
3+// const PAIRS: &[(char, char)] = &[('(', ')'), ('{', '}'), ('[', ']')];
4+// limit matching pairs to only ( ) { } [ ] < >
5+
6+pub fn find(syntax: &Syntax, doc: &Rope, pos: usize) -> Option<usize> {
7+ let tree = syntax.root_layer.tree.as_ref().unwrap();
8+
9+ let byte_pos = doc.char_to_byte(pos);
10+
11+ // most naive implementation: find the innermost syntax node, if we're at the edge of a node,
12+ // return the other edge.
13+
14+ let mut node = match tree
15+ .root_node()
16+ .named_descendant_for_byte_range(byte_pos, byte_pos)
17+ {
18+ Some(node) => node,
19+ None => return None,
20+ };
21+
22+ let start_byte = node.start_byte();
23+ let end_byte = node.end_byte() - 1; // it's end exclusive
24+
25+ if start_byte == byte_pos {
26+ return Some(doc.byte_to_char(end_byte));
27+ }
28+
29+ if end_byte == byte_pos {
30+ return Some(doc.byte_to_char(start_byte));
31+ }
32+
33+ None
34+}
helix-term/src/commands.rs+13−1
@@ -1,5 +1,5 @@
11use helix_core::{
2− comment, coords_at_pos, graphemes,
2+ comment, coords_at_pos, graphemes, match_brackets,
33 movement::{self, Direction},
44 object, pos_at_coords,
55 regex::{self, Regex},
@@ -1592,3 +1592,15 @@ pub fn expand_selection(cx: &mut Context) {
15921592 doc.set_selection(selection);
15931593 }
15941594}
1595+
1596+pub fn match_brackets(cx: &mut Context) {
1597+ let mut doc = cx.doc();
1598+
1599+ if let Some(syntax) = doc.syntax() {
1600+ let pos = doc.selection().cursor();
1601+ if let Some(pos) = match_brackets::find(syntax, doc.text(), pos) {
1602+ let selection = Selection::point(pos);
1603+ doc.set_selection(selection);
1604+ };
1605+ }
1606+}
helix-term/src/keymap.rs+3
@@ -182,6 +182,9 @@ pub fn default() -> Keymaps {
182182 // or select mode X?
183183 // extend_to_whole_line, crop_to_whole_line
184184
185+
186+ key!('m') => commands::match_brackets,
187+ // TODO: refactor into
185188 // key!('m') => commands::select_to_matching,
186189 // key!('M') => commands::back_select_to_matching,
187190 // select mode extend equivalents