aboutsummaryrefslogtreecommitdiff
path: root/lua/muwiki/links/open.lua
blob: 5afec53758b1b80a659056cde5161abef21b2661 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
local config = require('muwiki.config')
local links = require('muwiki.links.detection')
local files = require('muwiki.files')
local handlers = require('muwiki.handlers')
local url_handlers = require('muwiki.links.url_handlers')

local M = {}

local function get_wiki_root_or_notify()
  local wiki_root = config.get_wiki_root_for_buffer(0)
  if not wiki_root then
    vim.notify('Not in a wiki buffer', vim.log.levels.ERROR)
    return nil
  end
  return wiki_root
end

function M.open_link()
  local link = links.get_link()
  if not link then
    vim.notify('No link found under cursor', vim.log.levels.WARN)
    return
  end

  if link.type == 'web' then
    url_handlers.handle_web_link(link.target)
    return
  end

  local wiki_root = get_wiki_root_or_notify()
  if not wiki_root then
    return
  end

  if link.type == 'file' then
    if vim.startswith(link.target, 'file://') then
      url_handlers.handle_file_url(link.target)
    else
      url_handlers.handle_file_link(link.target, wiki_root)
    end
    return
  end

  url_handlers.handle_wiki_link(link.target, wiki_root)
end

function M.open_link_with()
  local link = links.get_link()
  if not link then
    vim.notify('No link found under cursor', vim.log.levels.WARN)
    return
  end

  if link.type == 'wiki' then
    vim.notify('Menu not available for wiki links', vim.log.levels.WARN)
    return
  end

  local url = link.target
  if link.type == 'file' then
    local wiki_root = get_wiki_root_or_notify()
    if not wiki_root then
      return
    end
    url = files.resolve(url, wiki_root)
  end

  local matching_handlers = handlers.get_matching(url)

  if #matching_handlers == 0 then
    vim.notify('No handlers available for this URL', vim.log.levels.WARN)
    return
  end

  if #matching_handlers == 1 then
    handlers.execute(matching_handlers[1], url)
    return
  end

  local handler_names = {}
  for _, handler in ipairs(matching_handlers) do
    table.insert(handler_names, handler.name)
  end

  vim.ui.select(handler_names, {
    prompt = 'Open with:',
  }, function(choice, idx)
    if choice and idx then
      handlers.execute(matching_handlers[idx], url)
    end
  end)
end

return M