aboutsummaryrefslogtreecommitdiff
path: root/lua/muwiki/config.lua
blob: 1e04d4acc9ddc97947744057947126adf7942625 (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
local M = {}

M.options = {
  dirs = nil,
  index_file = 'index.md',
  text_extensions = { 'md', 'txt' },
  use_external_handlers = false,
  external_handlers = {
    {
      name = 'xdg-open',
      cmd = 'xdg-open',
      pattern = '.*',
    },
  },
}

local function dir_exists(path)
  local stat = vim.uv.fs_stat(path)
  return stat and stat.type == 'directory'
end

function M.setup(opts)
  opts = opts or {}

  if opts.dirs then
    M.options.dirs = {}
    for _, dir in ipairs(opts.dirs) do
      local path = vim.fs.normalize(dir.path)
      if not vim.endswith(path, '/') then
        path = path .. '/'
      end
      table.insert(M.options.dirs, { name = dir.name, path = path })
    end
  end

  for key, value in pairs(opts) do
    if key == 'dirs' then
      -- handled above
    elseif M.options[key] ~= nil then
      M.options[key] = value
    end
  end

  for _, dir in ipairs(M.options.dirs or {}) do
    if not dir_exists(dir.path) then
      vim.notify('Wiki directory not found: ' .. dir.path, vim.log.levels.WARN)
    end
  end
end

-- Lookup wiki path by name (e.g., "default" -> "~/wiki/")
function M.wiki_path(name)
  if not M.options.dirs or #M.options.dirs == 0 then
    vim.notify('MuWiki: No dirs configured. See :help muwiki-configuration', vim.log.levels.ERROR)
    return nil
  end

  if name then
    for _, dir in ipairs(M.options.dirs) do
      if dir.name == name then
        return dir.path
      end
    end
    vim.notify(string.format('Wiki "%s" not found, using default', name), vim.log.levels.WARN)
  end

  return M.options.dirs[1].path
end

-- Find which wiki contains this buffer's file (cached per-buffer)
function M.wiki_root(bufnr)
  bufnr = bufnr or 0

  if vim.b[bufnr].muwiki_root ~= nil then
    return vim.b[bufnr].muwiki_root or nil
  end

  local filepath = vim.api.nvim_buf_get_name(bufnr)
  local normalized = vim.fs.normalize(filepath)

  for _, dir in ipairs(M.options.dirs or {}) do
    if vim.startswith(normalized, dir.path) then
      vim.b[bufnr].muwiki_root = dir.path
      return dir.path
    end
  end

  vim.b[bufnr].muwiki_root = false
  return nil
end

return M