aboutsummaryrefslogtreecommitdiff
path: root/lua/muwiki/links/detection.lua
diff options
context:
space:
mode:
Diffstat (limited to 'lua/muwiki/links/detection.lua')
-rw-r--r--lua/muwiki/links/detection.lua58
1 files changed, 58 insertions, 0 deletions
diff --git a/lua/muwiki/links/detection.lua b/lua/muwiki/links/detection.lua
new file mode 100644
index 0000000..356e0ba
--- /dev/null
+++ b/lua/muwiki/links/detection.lua
@@ -0,0 +1,58 @@
+local M = {}
+
+local function get_link_type(target)
+ if target:match('^https?://') then
+ return 'web'
+ end
+ if target:match('^file://') then
+ return 'file'
+ end
+ return 'wiki'
+end
+
+function M.get_link()
+ local cursor = vim.api.nvim_win_get_cursor(0)
+
+ local ok, node = pcall(vim.treesitter.get_node, {
+ bufnr = 0,
+ pos = { cursor[1] - 1, cursor[2] },
+ lang = 'markdown',
+ ignore_injections = false,
+ })
+
+ if not ok or not node then
+ return nil
+ end
+
+ local link_node = node
+ while link_node and link_node:type() ~= 'inline_link' do
+ link_node = link_node:parent()
+ end
+
+ if not link_node then
+ return nil
+ end
+
+ local text_node, dest_node
+ for child in link_node:iter_children() do
+ local t = child:type()
+ if t == 'link_text' then
+ text_node = child
+ elseif t == 'link_destination' then
+ dest_node = child
+ end
+ end
+
+ if not text_node or not dest_node then
+ return nil
+ end
+
+ local destination = vim.treesitter.get_node_text(dest_node, 0)
+ return {
+ text = vim.treesitter.get_node_text(text_node, 0),
+ target = destination,
+ type = get_link_type(destination),
+ }
+end
+
+return M