---@class lazy ---@field load function ---@field command_ids table ---@field auto_ids table ---@field keybind_ids table local lazy = {} --- create a new instance of lazy ---@return lazy function lazy:new() local o = {} setmetatable(o, self) o.command_ids = {} o.auto_ids = {} o.keybind_ids = {} self.__index = self return o end --- set the loading function ---@param load function the loading function function lazy:set_load(load) self.load = load end --- get the configured load function ---@return function load function function lazy:get_load() return self.load end --- create a usercommand which will trigger the plugin to load ---@param name string the name of the command ---@param opts vim.api.keyset.user_command? options function lazy:cmd(name, opts) opts = opts or {} vim.api.nvim_create_user_command(name, opts['callback'] or function() self:cleanup() end, opts) table.insert(self.command_ids, name) end --- user an auto command which will trigger the plugin to load ---@param event string the event to trigger on ---@param opts vim.api.keyset.create_autocmd? options function lazy:auto(event, opts) opts = opts or {} opts['once'] = opts['once'] or true opts['callback'] = opts['callback'] or function() self:cleanup() end -- create the auto command and save it table.insert(self.auto_ids, vim.api.nvim_create_autocmd(event, opts)) end --- create a keybind which will trigger the plugin to load ---@param mode string the mode to trigger in ---@param bind string the binding to use ---@param opts vim.keymap.set.Opts? options function lazy:keymap(mode, bind, opts) opts = opts or {} -- move the rerun arg to a seperate variable because keymap.set doesn't like -- options it doesn't know of local rerun = opts['rerun'] or true opts['rerun'] = nil vim.keymap.set(mode, bind, opts['callback'] or function() -- register keymap unload self:cleanup() -- call the keymap after the user has mapped it if rerun then local keys = vim.api.nvim_replace_termcodes(bind, true, false, true) vim.api.nvim_input(keys) end end, opts) table.insert(self.keybind_ids, { ['mode'] = mode, ['bind'] = bind }) end --- cleanup all the callbacks, and load the plugin function lazy:cleanup() -- cleanup user commands for _, command_id in pairs(self.command_ids) do vim.api.nvim_del_user_command(command_id) end -- cleanup auto commands for _, auto_id in pairs(self.auto_ids) do vim.api.nvim_del_autocmd(auto_id) end -- cleanup keymaps for _, keybind_id in pairs(self.keybind_ids) do vim.keymap.del(keybind_id.mode, keybind_id.bind, {}) end -- load the plugin self:load() end return lazy