That is because in lua once a module is required it is then cached for the entirety of the runtime, so sourcing just $MYVIMRC
isn’t enough to reload all the modules that are required inside your init.lua
.
What you need to do is set those loaded modules to nil
and then finally source your init.lua
, and on the next re-source it will re-require the file instead of the cached one.
I stole this code from plenary and simplified it for my use case but the concept is the same. You want to make sure all your lua files are scoped within a namespace, what this means is to have all your lua files inside lua/<namespace>
where (in my case I use my username: cnull) is the name of the directory, and then match all the modules that start with the namespace and set them to nil
. Below is the code along with a keymap and command you can set. Just replace the pattern in name:match()
from cnull
to your namespace.
function _G.ReloadConfig()
for name,_ in pairs(package.loaded) do
if name:match('^cnull') then
package.loaded[name] = nil
end
end
dofile(vim.env.MYVIMRC)
end
vim.api.nvim_set_keymap('n', '<Leader>vs', '<Cmd>lua ReloadConfig()<CR>', { silent = true, noremap = true })
vim.cmd('command! ReloadConfig lua ReloadConfig()')
If you want to use plenary to reload instead, then you just need to require it and give it the modulename aka your namespace/directory name.
require("plenary.reload").reload_module("cnull") -- replace with your own namespace