Skip to content

Commit

Permalink
refactor(commands): move util function to toolbox
Browse files Browse the repository at this point in the history
  • Loading branch information
Hinell committed Oct 19, 2023
1 parent 6ea46c2 commit 1553841
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 21 deletions.
22 changes: 1 addition & 21 deletions lua/legendary/data/command.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
25 changes: 25 additions & 0 deletions lua/legendary/toolbox.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 1553841

Please sign in to comment.