Add utilities
After a refactoring of utilities, I added a function to get the first child node that matches the node name. Documentation is provided in neogen.utilities.nodes
This commit is contained in:
51
lua/neogen/utilities/extractors.lua
Normal file
51
lua/neogen/utilities/extractors.lua
Normal file
@@ -0,0 +1,51 @@
|
||||
local ts_utils = require("nvim-treesitter.ts_utils")
|
||||
|
||||
neogen.utilities.extractors = {
|
||||
--- Return a function to extract content of required children from a node
|
||||
--- @param _ any self
|
||||
--- @param name string the children we want to extract (if multiple childrens, separate each one with "|")
|
||||
--- @return function cb function taking a node and getting the content of each children we want from name
|
||||
extract_children_text = function(_, name)
|
||||
return function(node)
|
||||
local result = {}
|
||||
local split = vim.split(name, "|", true)
|
||||
|
||||
|
||||
for child in node:iter_children() do
|
||||
if vim.tbl_contains(split, child:type()) then
|
||||
table.insert(result, ts_utils.get_node_text(child)[1])
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
end,
|
||||
|
||||
--- Extract content from specified children from a tree
|
||||
--- the tree parameter can be a nested { [key] = value} with key being the
|
||||
--- * key: is which children we want to extract the values from (e.g first children is 1)
|
||||
--- * value: "extract" or { [key] = value }. If value is "extract", it will extract the key child node
|
||||
--- Example (extract the first child node from the first child node of the parent node):
|
||||
--- [1] = {
|
||||
--- [1] = "extract"
|
||||
--- }
|
||||
--- @param tree table see description
|
||||
--- @param name string the children we want to extract (if multiple children, separate each one with "|")
|
||||
extract_children_from = function(self, tree, name)
|
||||
return function(node)
|
||||
local result = {}
|
||||
|
||||
for i, subtree in pairs(tree) do
|
||||
local child_node = node:named_child(tonumber(i) - 1)
|
||||
|
||||
if subtree == "extract" then
|
||||
return self:extract_children_text(name)(child_node)
|
||||
else
|
||||
return self:extract_children_from(subtree, name)(child_node)
|
||||
end
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
end,
|
||||
}
|
||||
14
lua/neogen/utilities/nodes.lua
Normal file
14
lua/neogen/utilities/nodes.lua
Normal file
@@ -0,0 +1,14 @@
|
||||
neogen.utilities.nodes = {
|
||||
--- Get first child node that match the provided node name
|
||||
--- @param _ any
|
||||
--- @param parent userdata the parent's node
|
||||
--- @param node_name string the node type to search for
|
||||
--- @return userdata node the first encountered child node
|
||||
first_child_node = function (_, parent, node_name)
|
||||
for child in parent:iter_children() do
|
||||
if child:type() == node_name then
|
||||
return child
|
||||
end
|
||||
end
|
||||
end
|
||||
}
|
||||
Reference in New Issue
Block a user