aboutsummaryrefslogtreecommitdiff
path: root/lua/muwiki/links/url_handlers.lua
blob: f84715a48958ec687d00e480517e3e37abc99588 (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
local config = require('muwiki.config')
local paths = require('muwiki.paths')
local files = require('muwiki.files')
local fs = require('muwiki.fs')

local M = {}

function M.handle_web_link(url)
  if not config.options.use_external_handlers then
    return
  end
  files.open_external(url)
end

local function resolve_file_url(url)
  local path = paths.strip_file_protocol(url)
  local resolved_path

  local path_type = paths.get_path_type(path)

  if path_type == 'absolute' then
    resolved_path = path
  elseif path_type == 'home' then
    resolved_path = vim.fs.normalize(path)
  else
    local current_dir = vim.fs.dirname(vim.api.nvim_buf_get_name(0))
    resolved_path = paths.resolve_relative(path, current_dir)
  end

  return 'file://' .. vim.fs.normalize(resolved_path)
end

function M.handle_file_url(url)
  if not config.options.use_external_handlers then
    return
  end

  local absolute_url = resolve_file_url(url)
  files.open_external(absolute_url)
end

function M.handle_file_link(target, wiki_root)
  local ok, file_path = pcall(files.resolve, target, wiki_root)
  if not ok then
    vim.notify(string.format('Cannot resolve path: %s', target), vim.log.levels.ERROR)
    return
  end

  if not fs.file_exists(file_path) then
    vim.notify(string.format('File not found: %s', file_path), vim.log.levels.ERROR)
    return
  end

  local ext = file_path:match('%.([^%.]+)$') or ''
  if not files.is_text_file(ext) then
    if not config.options.use_external_handlers then
      return
    end
    files.open_external(file_path)
    return
  end

  files.open_in_buffer(file_path)
end

function M.handle_wiki_link(target, wiki_root)
  local file_path = files.resolve(target, wiki_root)
  files.open_wiki_file(file_path)
end

return M