dotfiles/config/nvim/lua/util/init.lua
2025-07-01 19:52:17 +02:00

86 lines
2 KiB
Lua

local M = {}
---Check whether file/directory exists.
---@param path string: file or directory path.
---@return string|boolean: type if path exists, false otherwise.
M.exists = function(path)
---@diagnostic disable-next-line: undefined-field
local stat = vim.uv.fs_stat(path)
return (stat and stat.type) or false
end
---Preserve register contents over function call.
---@param reg string: register to save, must be a valid register name.
---@param func function: function that may freely clobber the register.
---@return any: return value of calling `func`.
M.preserve_register = function(reg, func)
local saved = vim.fn.getreg(reg)
local result = func()
vim.fn.setreg(reg, saved)
return result
end
---Get selected text.
---@return string: selected text, or word under cursor if not in visual mode.
M.get_selected_text = function()
if vim.fn.mode() ~= "v" then return vim.fn.expand("<cword>") end
return M.preserve_register("v", function()
vim.cmd([[noautocmd sil norm "vy]])
return vim.fn.getreg("v")
end)
end
M.keymap_decorator = function(opts)
opts = opts or {}
local decorate_key = function(key)
return vim.tbl_extend("force", key, {
(opts.lhs_prefix or "") .. key[1], -- lhs
key[2], -- rhs
desc = (opts.desc_prefix or "") .. key.desc .. (opts.desc_suffix or ""),
})
end
return function(keys)
if keys and type(keys[1]) == "table" then
return vim.iter(keys):map(decorate_key):totable()
else
return decorate_key(keys)
end
end
end
-- M.test = function()
-- local key = {
-- "a",
-- "<cmd>DoA<cr>",
-- desc = "this does A",
-- mode = "v",
-- }
-- local keys = {
-- {
-- "a",
-- "<cmd>DoA<cr>",
-- desc = "this does A",
-- mode = "v",
-- },
-- {
-- "b",
-- "<cmd>DoB<cr>",
-- desc = "this does B",
-- mode = "n",
-- },
-- }
-- local do_it = M.keymap_decorator {
-- lhs_prefix = "<leader>!",
-- desc_prefix = "OK: ",
-- }
-- P(do_it(key))
-- P(do_it(keys))
-- end
return M