Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reload my Neovim config written in lua with a shortcut?

Tags:

config

lua

neovim

I want to reload my neovim configuration files with just a couple of keystrokes instead of having to restart the app. I was able to do this when using an init.vim with the following command:

nnoremap <leader>sv <cmd>source $MYVIMRC<CR>

$MYVIMRC points correctly to my config entry point.

The problem is that I switched to using lua, and now I can't do the same. I have read the docs and tried variants of the following without success:

util.nnoremap("<leader>sv", "<cmd>luafile $MYVIMRC<CR>")

Finally, I found a solution doing this:

function load(name)
    local path = vim.fn.stdpath('config') .. '/lua/' .. name .. '.lua'
    dofile(path)
end

load('plugins')
load('config/mapping')
load('lsp/init')

Which is buggy and feels wrong.

Is there any way to do this? I read the example in vimpeccable, but I want to see the other available options since I would rather not install another plugin.

I know that plenary includes a function to reload modules, but I don't understand how to use it. A complete example of that would be good too since I already use plenary in my config.

like image 662
alexfertel Avatar asked Jul 16 '21 21:07

alexfertel


People also ask

How do I run Lua in Neovim?

Lua modules are found inside a lua/ folder in your 'runtimepath' (for most users, this will mean ~/. config/nvim/lua on *nix systems and ~/AppData/Local/nvim/lua on Windows). You can require() files in this folder as Lua modules.

Is Neovim written in Lua?

These modules rely on LuaJIT, rather than the standard Lua. Neovim uses LuaJIT, so this is not a problem when it comes to your plugin. However, if you want to test out these modules outside of the plugin environment, you need to install, and use LuaJIT to do so. Install SQLite 3 and the development package for it.

Is Lua better than Vimscript?

Lua is more ergonomic for writing programs/plugins, but vimscript is more ergonomic for interactive use (and maybe config files, more below). especially when you're doing thousands of commands of varying complexity every day.


1 Answers

I am a new Neovim user, so I guess my solution may not work for some edge cases.

This function flushes the module of current buffer:

local cfg = vim.fn.stdpath('config')
Flush = function()
    local s = vim.api.nvim_buf_get_name(0)
    if string.match(s, '^' .. cfg .. '*') == nil then
        return
    end
    s = string.sub(s, 6 + string.len(cfg), -5)
    local val = string.gsub(s, '%/', '.')
    package.loaded[val] = nil
end

You can call it whenever you write to a buffer with this autocommand:

autocmd BufWrite *.lua,*vim call v:lua.Flush()

This way, after you execute :source $MYVIMRC it will also reload changed Lua modules.

like image 179
Meiram Shunshalin Avatar answered Sep 30 '22 08:09

Meiram Shunshalin