Search code examples
luaneovim

How to bind a luafunction to keypress in vim


I want to execute a imported function on a button click, but I get an error that its undefined.

local LazyComp = require('plugins/LazyComp/LazyComp')
vim.api.nvim_set_keymap('n', '<Tab>', "LazyComp.getFile()<cr>", {expr = true, noremap = true})

Solution

  • You need to provide a vim script expression in that mapping. Not a Lua function call. There's no way to get that local variable called from nvim through a string.

    I'm no expert in nvim's Lua API but 1 minute of websearch gave me this solution:

    vim.api.nvim_set_keymap('n', '<TAB>', "<cmd>lua require('plugins/LazyComp/LazyComp').getFile()<CR>")
    

    Alternatively you need to make your module available globally.

    _G.LazyComp = require('plugins/LazyComp/LazyComp')
    

    Then you should be able to access the global environemt through v:lua

    vim.api.nvim_set_keymap('n', '<TAB>', "v:lua.LazyComp.getFile()<CR>")
    

    Both untested.