How to source init.lua without restarting neovim

Viewed 2667

Is there a clean way to reload a neovim init.lua config and all its modules (using the require() function) without restarting neovim?

I've read on another post that :luafile $MYVIMRC was supposed to accomplish just that but it doesn't reload those cached files unfortunately. I'm hoping to setup a keymap like I used to have in my previous init.vim config. Something along the lines of:

local opts = { noremap = true, silent = true }

vim.api.nvim_set_keymap("n", "<leader><CR>", ":luafile $MYVIMRC<CR>", opts)

I'm on nvim v0.8.0.

5 Answers

Try to run this command :

:luafile %

Thanks!

A:

You can use :luafile <filename> for this. See :h :luafile for more information.

If found an answer from creativenull on this reddit thread that seems to work well. I ended up creating a small module called reload.lua:

function _G.ReloadConfig()
  for name,_ in pairs(package.loaded) do
    if name:match('^user') and not name:match('nvim-tree') then
      package.loaded[name] = nil
    end
  end

  dofile(vim.env.MYVIMRC)
  vim.notify("Nvim configuration reloaded!", vim.log.levels.INFO)
end

That gets imported in init.lua:

require 'user.reload'

And for which I added a keymap:

vim.api.nvim_set_keymap("n", "<leader><CR>", "<cmd>lua ReloadConfig()<CR>", { noremap = true, silent = false })

Note 1: in the example above your lua files need to be contained in a user folder: ~/.config/nvim/lua/user/. That's also where reload.lua lives.

Note 2: I think it's possible to use the not name:match('exclude-me') regex syntax to exclude problematic modules.

I am not sure yet. I am using mapping :w | so % to source current file sourcing file keymap

--update -- this works in only config file

like this hope this help

This solution works for me on Neovim v0.7.2.

-- Add modules here
local modules = {
  "user.options",
  "user.keymaps",
}

-- Refresh module cache
for k, v in pairs(modules) do
  package.loaded[v] = nil
  require(v)
end

You can then config your keymap to refresh $MYVIMRC as follows:

vim.api.nvim_set_keymap("n", "<leader><CR>", ":luafile $MYVIMRC<CR>", opts)
Related