Skip to content

Instantly share code, notes, and snippets.

@VonHeikemen
Last active March 27, 2022 16:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VonHeikemen/dd2190709302de7ee9943f1b9dfb1933 to your computer and use it in GitHub Desktop.
Save VonHeikemen/dd2190709302de7ee9943f1b9dfb1933 to your computer and use it in GitHub Desktop.
Allows you to use lua functions with `vim.api.nvim_set_keymap` (for neovim 0.6.1 or lower)
local M = {}
local module_name = 'map_utils'
local fn_store = {}
local function register_fn(fn)
table.insert(fn_store, fn)
return #fn_store
end
function M.apply_function(id)
fn_store[id]()
end
function M.apply_expr(id)
return vim.api.nvim_replace_termcodes(fn_store[id](), true, true, true)
end
function M.lua_fn(fn)
return string.format(
"<cmd>lua require('%s').apply_function(%s)<CR>",
module_name,
register_fn(fn)
)
end
function M.lua_expr(fn)
return string.format(
"v:lua.require'%s'.apply_expr(%s)",
module_name,
register_fn(fn)
)
end
return M
@VonHeikemen
Copy link
Author

VonHeikemen commented Dec 29, 2021

Assuming you save this in ~/.config/nvim/lua/map_utils.lua, this a basic usage example.

local utils = require('map_utils')
local lua_fn = utils.lua_fn
local lua_expr = utils.lua_expr
local key = vim.api.nvim_set_keymap

local noremap = {noremap = true}
local noremap_expr = {noremap = true, expr = true}
local expr = {expr = true}

-- Hello world!
key('n', '<Space><Space>', lua_fn(function()
  vim.notify('Hello!')
end), noremap)

-- "Smart tab"
key('i', '<Tab>', lua_expr(function()
  if vim.fn.pumvisible() == 1 then
    return '<C-n>'
  else
    return '<Tab>'
  end
end), noremap_expr)

-- Go to next selection in snippet (select mode)
key('s', '<C-w>', lua_expr(function()
  if require('luasnip').jumpable(1) then
    return '<Plug>luasnip-jump-next'
  end
end), expr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment