|
1 | 1 | local J = { |
2 | 2 | comment = '{/*%s*/}', |
| 3 | + valid = { 'jsx_element', 'jsx_fragment', 'jsx_text', '<', '>' }, |
3 | 4 | } |
4 | 5 |
|
5 | | -local query = [[ |
6 | | - (parenthesized_expression |
7 | | - [(jsx_fragment) (jsx_element)] @jsx) |
8 | | -
|
9 | | - (return_statement |
10 | | - [(jsx_fragment) (jsx_element)] @jsx) |
11 | | -]] |
12 | | - |
13 | | -local function is_jsx(lang) |
| 6 | +local function is_jsx_tree(lang) |
14 | 7 | -- Name of the treesitter parsers that supports jsx syntax |
15 | 8 | return lang == 'tsx' or lang == 'javascript' |
16 | 9 | end |
17 | 10 |
|
| 11 | +local function is_jsx_node(node) |
| 12 | + if not node then |
| 13 | + return false |
| 14 | + end |
| 15 | + return vim.tbl_contains(J.valid, node:type()) |
| 16 | +end |
| 17 | + |
18 | 18 | local function capture(child, range) |
19 | 19 | local lang = child:lang() |
20 | 20 |
|
21 | | - if not is_jsx(lang) then |
| 21 | + local rng = { |
| 22 | + range.srow - 1, |
| 23 | + range.scol, |
| 24 | + range.erow - 1, |
| 25 | + range.ecol, |
| 26 | + } |
| 27 | + |
| 28 | + if not (is_jsx_tree(lang) and child:contains(rng)) then |
22 | 29 | return |
23 | 30 | end |
24 | 31 |
|
25 | | - local Q = vim.treesitter.query.parse_query(lang, query) |
26 | | - |
27 | 32 | for _, tree in ipairs(child:trees()) do |
28 | | - for _, node in Q:iter_captures(tree:root(), child:source()) do |
29 | | - local srow, _, erow = node:range() |
30 | | - -- Why subtracting 2? |
31 | | - -- 1. Lua indexes starts from 1 |
32 | | - -- 2. Removing the `return` keyword from the range |
33 | | - if srow <= range.srow - 2 and erow >= range.erow then |
| 33 | + local root = tree:root() |
| 34 | + local node = root:descendant_for_range(unpack(rng)) |
| 35 | + local srow, _, erow = node:range() |
| 36 | + if srow <= range.srow - 1 and erow >= range.erow - 1 then |
| 37 | + local nxt, prev = node:next_sibling(), node:prev_sibling() |
| 38 | + if is_jsx_node(prev) or is_jsx_node(node) or is_jsx_node(nxt) then |
34 | 39 | return J.comment |
35 | 40 | end |
36 | 41 | end |
|
0 commit comments