Skip to content

Instantly share code, notes, and snippets.

@runiq
Created January 15, 2021 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runiq/1c01fdb1b45a8f060d6b29d6c7a93e74 to your computer and use it in GitHub Desktop.
Save runiq/1c01fdb1b45a8f060d6b29d6c7a93e74 to your computer and use it in GitHub Desktop.
Neovim: "native" Lua callbacks in mappings
local M = {}
M._cbs = {}
--- Saves a Lua function as a callback and returns a string that can be used to
--- run that function.
---
---@param fn Callback
---@return string
function M.lua_callback(fn)
assert(type(fn) == 'function', tb('fn must be a function'))
local callback_number = #M._cbs + 1
M._cbs[callback_number] = fn
return ("require'my.utils'._cbs[%d]()"):format(callback_number)
end
--- Saves a Lua function as a callback and returns a string that can be used to
--- run that function from Vim.
---
---@param fn Callback
---@return string
function M.lua_callback_cmd(fn)
return "lua "..M.lua_callback(fn)
end
--- Wrapper around vim.api.nvim_set_map() that can take native Lua functions.
function M.map(mode, lhs, rhs, opts)
if type(rhs) == 'function' then
rhs = '<cmd>' .. M.lua_callback_cmd(rhs) .. '<cr>'
end
return api.set_keymap(mode, lhs, rhs, opts)
end
--- Wrapper around vim.api.nvim_buf_set_map() that can take native Lua functions.
function M.bmap(buffer, mode, lhs, rhs, opts)
if type(rhs) == 'function' then
rhs = '<cmd>' .. M.lua_callback_cmd(rhs) .. '<cr>'
end
api.buf_set_keymap(buffer, mode, lhs, rhs, opts)
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment