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('', true, false, true), 'n', false) local wiki_root = config.get_wiki_root_for_file(vim.api.nvim_buf_get_name(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