summary refs log tree commit diff
path: root/.vim/lua/internal/zk.lua
blob: 4631e131581f854d693dd9a1b1fadb4292f8fb8f (plain) (blame)
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
if not vim.env.ZK_NOTEBOOK_DIR then
  vim.notify('Missing ZK_NOTEBOOK_DIR!', vim.log.levels.WARN)
  return
end

local api = require('zk.api')
local util = require('zk.util')

local function insert_new_note()
  -- TODO: catch error an delete note
  api.new(nil, nil, function(err1, res1)
    if not res1 then
      error(err1)
    end

    -- update index to include the new note
    api.index(nil, nil, nil)

    local path = res1.path
    local filename = vim.fs.basename(path)
    local location = util.get_lsp_location_from_caret()

    api.link(filename, location, nil, {}, function(err2, res2)
      if not res2 then
        error(err2)
      end

      -- open split
      local buf = vim.api.nvim_create_buf(true, false)
      vim.api.nvim_buf_set_name(buf, filename)
      vim.api.nvim_buf_call(buf, function()
        vim.cmd.edit(path)
      end)
      local win = vim.api.nvim_open_win(buf, false, {
        split = 'below',
        win = 0,
      })
      -- move to split
      vim.api.nvim_set_current_win(win)
      vim.api.nvim_win_set_cursor(win, { -1, 0 })
    end)
  end)
end

local function on_attach()
  if not vim.env.ZK_NOTEBOOK_DIR then
    vim.notify('Missing ZK_NOTEBOOK_DIR!', vim.log.levels.WARN)
    return
  end

  -- enable virtual_text diagnostics to show link titles
  vim.diagnostic.config({ virtual_text = true })

  local opts = { remap = true, silent = false, buffer = true }

  -- -- list zettelkasten
  -- vim.keymap.set('n', '-', ':call feedkeys(";zz")<cr>', opts)

  -- follow links
  -- TODO: should this also work on outgoing links?
  vim.keymap.set('n', '<cr>', '<cmd>lua vim.lsp.buf.definition()<cr>', opts)

  -- insert ref to new note and open note in split
  vim.keymap.set({ 'n', 'i' }, ';zi', insert_new_note, opts)
end

-- setup binds to run when entering zettel buffers
vim.api.nvim_create_autocmd({ 'BufEnter' }, {
  pattern = vim.env.ZK_NOTEBOOK_DIR .. '/*.md',
  callback = on_attach,
  group = vim.api.nvim_create_augroup('zk-on-attach', { clear = true }),
  once = true,
})