80 lines
2.0 KiB
Lua
80 lines
2.0 KiB
Lua
local M = {}
|
|
|
|
M.config = {
|
|
notes_dir = vim.fn.expand('~/.nvimwiki')
|
|
}
|
|
|
|
function M.setup(opts)
|
|
M.config = vim.tbl_extend('force', M.config, opts or {})
|
|
end
|
|
|
|
function M.follow_link()
|
|
local line = vim.api.nvim_get_current_line()
|
|
local wiki_link = line:match('%[%[([^%]]+)%]%]')
|
|
local md_link = line:match('%[.-%]%(([^%)])%)')
|
|
|
|
local link = wiki_link or md_link
|
|
|
|
if not link then return end
|
|
|
|
if not link:match('%.md$') then link = link .. '.md' end
|
|
|
|
if not link:match('^/') and not link:match('^%.') then
|
|
local current_dir = vim.fn.expand('%:p:h')
|
|
local relative_path = current_dir .. '/' .. link
|
|
|
|
-- if file exists, edit it in the buffer
|
|
if vim.fn.filereadable(realative_path) then
|
|
vim.cmd('edit' .. relative_path)
|
|
return
|
|
end
|
|
|
|
-- need to create file
|
|
|
|
target_path = M.config.notes_dir .. '/' .. link
|
|
else
|
|
target_path = link
|
|
end
|
|
|
|
local parent_dir = vim.fn.fnamemodify(target_path, ':h')
|
|
if vim.fn.isdirectory(parent_dir) == 0 then
|
|
vim.fn.mkdir(parent_dir, 'p')
|
|
end
|
|
|
|
vim.cmd('edit' .. link)
|
|
end
|
|
|
|
function M.smart_link()
|
|
local line = vim.api.nvim_get_current_line()
|
|
local col = vim.api.nvim_win_get_cursor(0)[2]
|
|
|
|
local before = line:sub(1, col + 1)
|
|
local after = line:sub(col + 1)
|
|
|
|
local in_wiki_link = before:match('%[%[[^%]]*$') and after:match('^[^%]]*%]%]')
|
|
local in_md_link = before:match('%([^%)]*$') and after:match('^[^%)]*%)')
|
|
|
|
if in_wiki_link or in_md_link then
|
|
M.follow_link()
|
|
else
|
|
local word = vim.fn.expand('<cWORD>')
|
|
|
|
word = word:match('[%w_/%-]+')
|
|
|
|
if word and word ~= '' then
|
|
vim.cmd('normal! ciW[[' .. word .. ']]')
|
|
vim.cmd('normal! F[')
|
|
M.follow_link()
|
|
end
|
|
|
|
end
|
|
end
|
|
|
|
|
|
function M.setup_keymaps()
|
|
vim.keymap.set('n', '<CR>', M.smart_link, { buffer = true, desc = "follow link"})
|
|
vim.keymap.set('n', '<BS>', '<C-o>', { buffer = true, desc = "go back"})
|
|
end
|
|
|
|
return M
|