From 1553841b5320e0c139af404ff3ec944a43419f9c Mon Sep 17 00:00:00 2001 From: Hinell Date: Fri, 20 Oct 2023 01:49:01 +0300 Subject: [PATCH] refactor(commands): move util function to toolbox --- lua/legendary/data/command.lua | 22 +--------------------- lua/legendary/toolbox.lua | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/lua/legendary/data/command.lua b/lua/legendary/data/command.lua index 4b73bc46..f568d6e9 100644 --- a/lua/legendary/data/command.lua +++ b/lua/legendary/data/command.lua @@ -40,26 +40,6 @@ local function exec(impl, args) end end -local function parse_modemap(map) - return function(args) - local mode = vim.fn.mode() - local impl = map[mode] - if not impl then - if Toolbox.is_visual_mode(mode) then - impl = impl or map.v or map.x or map.s - elseif mode == 'i' then - impl = impl or map.l - elseif mode == 'c' then - impl = impl or map.l - end - end - - if impl then - exec(impl, args) - end - end -end - ---Parse a new command table ---@param tbl table ---@param builtin boolean Whether the item is a builtin, defaults to false @@ -98,7 +78,7 @@ function Command:parse(tbl, builtin) -- luacheck: no unused l = { tbl[2].i, { 'string', 'function' }, true }, }) - instance.implementation = parse_modemap(instance.implementation) + instance.implementation = Toolbox.map_cur_mode_into_impl(instance.implementation, exec) end instance:parse_filters(tbl.filters) diff --git a/lua/legendary/toolbox.lua b/lua/legendary/toolbox.lua index 79bf65bf..9853170f 100644 --- a/lua/legendary/toolbox.lua +++ b/lua/legendary/toolbox.lua @@ -185,4 +185,29 @@ function M.table_from_vimscript(vimscript_str, description) return input end +--- Takes instance specific mode implementation and executes callback +--- with a instance implementation per current nvim mode +--- @param instanceModeMap table +--- @param callback function +--- @return function +function M.map_cur_mode_into_impl(instanceModeMap, callback) + return function(args) + local mode = vim.fn.mode() + local impl = instanceModeMap[mode] + if not impl then + if Toolbox.is_visual_mode(mode) then + impl = impl or instanceModeMap.v or instanceModeMap.x or instanceModeMap.s + elseif mode == 'i' then + impl = impl or instanceModeMap.l + elseif mode == 'c' then + impl = impl or instanceModeMap.l + end + end + + if impl then + callback(impl, args) + end + end +end + return M