Skip to content

Commit

Permalink
2st draft
Browse files Browse the repository at this point in the history
  • Loading branch information
numToStr committed Apr 3, 2022
1 parent cd53cfd commit 14cd8b5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
2 changes: 2 additions & 0 deletions a.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const Yoo = () => {
<section>
<p>hello</p>
<p
he="llo"
wor="ld"
attr={{
...window,
hello: () => {
Expand Down
41 changes: 23 additions & 18 deletions lua/Comment/jsx.lua
Original file line number Diff line number Diff line change
@@ -1,36 +1,41 @@
local J = {
comment = '{/*%s*/}',
valid = { 'jsx_element', 'jsx_fragment', 'jsx_text', '<', '>' },
}

local query = [[
(parenthesized_expression
[(jsx_fragment) (jsx_element)] @jsx)
(return_statement
[(jsx_fragment) (jsx_element)] @jsx)
]]

local function is_jsx(lang)
local function is_jsx_tree(lang)
-- Name of the treesitter parsers that supports jsx syntax
return lang == 'tsx' or lang == 'javascript'
end

local function is_jsx_node(node)
if not node then
return false
end
return vim.tbl_contains(J.valid, node:type())
end

local function capture(child, range)
local lang = child:lang()

if not is_jsx(lang) then
local rng = {
range.srow - 1,
range.scol,
range.erow - 1,
range.ecol,
}

if not (is_jsx_tree(lang) and child:contains(rng)) then
return
end

local Q = vim.treesitter.query.parse_query(lang, query)

for _, tree in ipairs(child:trees()) do
for _, node in Q:iter_captures(tree:root(), child:source()) do
local srow, _, erow = node:range()
-- Why subtracting 2?
-- 1. Lua indexes starts from 1
-- 2. Removing the `return` keyword from the range
if srow <= range.srow - 2 and erow >= range.erow then
local root = tree:root()
local node = root:descendant_for_range(unpack(rng))
local srow, _, erow = node:range()
if srow <= range.srow - 1 and erow >= range.erow - 1 then
local nxt, prev = node:next_sibling(), node:prev_sibling()
if is_jsx_node(prev) or is_jsx_node(node) or is_jsx_node(nxt) then
return J.comment
end
end
Expand Down

0 comments on commit 14cd8b5

Please sign in to comment.