summaryrefslogtreecommitdiff
path: root/lua/nvim-treesitter/utils.lua
diff options
context:
space:
mode:
authorStephan Seitz <stephan.seitz@fau.de>2020-05-01 16:25:06 +0200
committerStephan Seitz <stephan.seitz@fau.de>2020-05-03 10:51:15 +0200
commitd0b84dd89fb1cb4fc637cd3deec427745ba3145b (patch)
treea2920ca37e02ce22f3a46d6e876cb3feb9486d96 /lua/nvim-treesitter/utils.lua
parent0207836eb2aaa876d52ffddd1ec89ec347c67996 (diff)
Add 'nvim-treesitter/node-movement'
Diffstat (limited to 'lua/nvim-treesitter/utils.lua')
-rw-r--r--lua/nvim-treesitter/utils.lua59
1 files changed, 59 insertions, 0 deletions
diff --git a/lua/nvim-treesitter/utils.lua b/lua/nvim-treesitter/utils.lua
index 391863f0..9d591eab 100644
--- a/lua/nvim-treesitter/utils.lua
+++ b/lua/nvim-treesitter/utils.lua
@@ -93,4 +93,63 @@ function M.smallest_containing_scope(node, bufnr)
return current or root
end
+--- Get next node with same parent
+-- @param node node
+-- @param allow_switch_parents allow switching parents if last node
+-- @param allow_next_parent allow next parent if last node and next parent without children
+function M.get_next_node(node, allow_switch_parents, allow_next_parent)
+ local destination_node
+ local parent = node:parent()
+
+ if parent then
+ local found_pos = 0
+ for i = 0,parent:named_child_count()-1,1 do
+ if parent:named_child(i) == node then
+ found_pos = i
+ break
+ end
+ end
+ if parent:named_child_count() > found_pos + 1 then
+ destination_node = parent:named_child(found_pos + 1)
+ elseif allow_switch_parents then
+ local next_node = M.get_next_node(node:parent())
+ if next_node and next_node:named_child_count() > 0 then
+ destination_node = next_node:named_child(0)
+ elseif next_node and allow_next_parent then
+ destination_node = next_node
+ end
+ end
+ end
+ return destination_node
+end
+
+--- Get previous node with same parent
+-- @param node node
+-- @param allow_switch_parents allow switching parents if first node
+-- @param allow_previous_parent allow previous parent if first node and previous parent without children
+function M.get_previous_node(node, allow_switch_parents, allow_previous_parent)
+ local destination_node
+ local parent = node:parent()
+ if parent then
+ local found_pos = 0
+ for i = 0,parent:named_child_count()-1,1 do
+ if parent:named_child(i) == node then
+ found_pos = i
+ break
+ end
+ end
+ if 0 < found_pos then
+ destination_node = parent:named_child(found_pos - 1)
+ elseif allow_switch_parents then
+ local previous_node = M.get_previous_node(node:parent())
+ if previous_node and previous_node:named_child_count() > 0 then
+ destination_node = previous_node:named_child(previous_node:named_child_count() - 1)
+ elseif previous_node and allow_previous_parent then
+ destination_node = previous_node
+ end
+ end
+ end
+ return destination_node
+end
+
return M