Skip to content

Instantly share code, notes, and snippets.

@cultab
Last active April 10, 2022 13:10
Show Gist options
  • Save cultab/3c364ce879c050cf56040c40d22ceafb to your computer and use it in GitHub Desktop.
Save cultab/3c364ce879c050cf56040c40d22ceafb to your computer and use it in GitHub Desktop.
Cursed neovim keymapping DSL
local M = {}
local wk = require "which-key"
-- Map a key to a lua function or vimscript snippet also add a description.
--
-- map keycode:string lua function OR vimscript:string description:string ()
--
-- Example:
-- ```lua
-- map 'gD'vim.lsp.buf.declaration "Goto declaration [LSP]" ()
-- ```
--
-- An optional third argument determines the mode the key is bound in.
--
-- Example, let's map <leader>= to vim.lsp.buf.range_formatting in visual mode:
-- ```lua
-- map '<leader>=' vim.lsp.buf.range_formatting "Format range" 'v' ()
-- ```
--
-- After mapping all your keys you need to call
-- ```lua
-- map:register()
-- ```
_G.map = setmetatable({ mappings = {}, parsed = {}, key = {} }, {
-- enable syntax like: map "<leader>a" vim.lsp.buf.rename "some desc" ()
-- if mode is missing, assume normal mode
-- if mapping is missing, name the group
__call = function (self, key)
-- local closure = function (mapping_args)
-- self.mappings[key] = mapping_args
-- end
vim.notify("got key:" .. key)
self.key = key
return self.parse
end,
__index = {
parse = function (arg)
if arg == nil then
vim.notify("put in")
table.insert(_G.map.parsed, arg)
_G.map.mappings[_G.map.key] = { unpack(_G.map.parsed, 1, #_G.map.parsed)}
_G.map.parsed = {}
_G.map.key = {}
return
else
vim.notify("got arg:" .. arg)
table.insert(_G.map.parsed, arg)
return _G.map.parse
end
end,
register = function (self)
print(vim.inspect(self))
for key, mapping_args in pairs(self.mappings) do
local mapping = mapping_args[1]
local description = mapping_args[2]
local mode = mapping_args[3]
if mode == nil then
mode = "n"
end
if mapping ~= nil then
if #mode == 1 then
wk.register({
[key] = { mapping, description }
}, { mode = mode })
elseif #mode == 0 then
wk.register({
[key] = { mapping, description }
}, { mode = "n" })
else
for i = 1, #mode do
wk.register({
[key] = { mapping, description }
}, { mode = mode:sub(i, i) })
end
end
else
if #mode == 1 then
wk.register({
[key] = { name = description }
}, { mode = mode })
elseif #mode == 0 then
wk.register({
[key] = { name = description }
}, { mode = "n" })
else
for i = 1, #mode do
wk.register({
[key] = { name = description }
}, { mode = mode:sub(i, i) })
end
end
end
end
end
}
})
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment