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
|
local M = {}
function M.create_link()
local files = require('muwiki.files')
local config = require('muwiki.config')
local mode = vim.fn.mode()
if mode ~= 'v' and mode ~= 'V' then
vim.notify('Must be in visual mode to create a link', vim.log.levels.WARN)
return
end
local start_pos = vim.fn.getpos('v')
local end_pos = vim.fn.getpos('.')
local region = vim.fn.getregion(start_pos, end_pos, { type = mode })
if not region or #region == 0 then
vim.notify('No text selected', vim.log.levels.WARN)
return
end
if #region > 1 then
vim.notify('Multi-line selection not supported', vim.log.levels.WARN)
return
end
local selected_text = region[1]
local normalized = files.normalize_filename(selected_text)
local link_target = normalized .. '.md'
local link_text = string.format('[%s](%s)', selected_text, link_target)
local start_row = start_pos[2]
local start_col = start_pos[3]
local end_row = end_pos[2]
local end_col = end_pos[3]
if start_row > end_row or (start_row == end_row and start_col > end_col) then
start_row, end_row = end_row, start_row
start_col, end_col = end_col, start_col
end
start_row = start_row - 1
start_col = start_col - 1
end_row = end_row - 1
if mode == 'V' then
start_col = 0
local line = vim.api.nvim_buf_get_lines(0, end_row, end_row + 1, false)[1]
end_col = #line
end
vim.api.nvim_buf_set_text(0, start_row, start_col, end_row, end_col, { link_text })
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes('<Esc>', true, false, true), 'n', false)
local wiki_root = config.wiki_root(0)
if not wiki_root then
vim.notify('Not in a wiki buffer', vim.log.levels.ERROR)
return
end
local target_path = files.resolve(link_target, wiki_root)
files.open_wiki_file(target_path)
end
return M
|