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.
Try to run this command :
:luafile %
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.
You can use :luafile <filename> for this.
See :h :luafile for more information.
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
I'm pretty new to neovim and vim in general and I tried to use the localleader key (default: \) and nothing happened.
Then I tried to set the localleader key in the config (lua) in various ways I could find online, none of which worked.
However when I type :echo maplocalleader in neovim it shows the key I set.
Setting maplocalleader from within neovim also yielded the same result.
My question is, what might be preventing my localleader key from working?
After setting up neovim again from scratch and copying over my configs piece by piece, I found out that I had to put vim.g.maplocalleader = ";" at the very top of init.lua in order for it to work.
I think you need to unmap the key first.
Try something like this.
local opts = { noremap = true, silent = true }
local keymap = vim.api.nvim_set_keymap
--Remap '\\' as leader key
keymap('', '\\', '<Nop>', opts)
vim.g.mapleader = '\\'
vim.g.maplocalleader = '\\'
I decided to spring-clean and update my nvim config files/plugins, and thought I’d make proper use of the after/plug folder.
While setting up LSP (with mason, mason-lspconfig, and lspconfig), I wanted to move all the lsp language server settings out from after/plugin/lsp/init.lua to their own files (now in after/plugin/lsp/settings).
The problem is I don’t seem to be able to require them into the init.lua file.
Things I’ve tried to no avail:
require(‘after/plugin/lsp/settings/sumneko_lua.lua’)
require(vim.fn.stdpath("config") .. "/after/plugin/lsp/settings/sumneko_lua”)
require(vim.fn.expand('%:h').. ‘/settings/sumneko_lua’)
The attempt using expand works when I resource the file in nvim; but causes an error when starting nvim.
I understand that all the files in after/plugin are automagically sourced at startup. So if I had a file shared.lua:
local M = {}
function M.greet()
vim.notify("Hello!”)
end
return M
in the same folder as after/plugin/lsp/init.lua, how can I get access to the greet() function from init.lua?
Any pointers would be greatly appreciated.
It turned out to be quite a simple solution in the end: I simply updated the paths to be searched in init.lua
-- nvim/init.lua
-- Allow require to look in after/plugin folder
local home_dir = os.getenv("HOME”)
package.path = home_dir .. "/.config/nvim/after/plugin/?.lua;" .. package.path
And then I can require any file inside the after/plugin folder
e.g - require(‘lsp/settings/sumneko’) or require(‘lsp/shared’).greet()
I'm writing a tool to parse lua plugins created by other users. The only guarentee about the plugin is that it has a data.lua file in a known directory. Inside there users are free to do anything they wish. This particular plugin using require to load a file and that file loads another file. Both are relative paths but the second is relative to the location of the first file.
data.lua
foo/bar.lua
foo/baz.lua
data.lua:
require("foo.bar")
foo/bar.lua:
require("baz")
When I try to execute data.lua I get an error when foo/bar.lua tries to require "baz". None of the paths it tries are ./foo/.
Any idea how I can fix this? I could find any documentation specifically about this case, it seemed like I need to hard code /foo/ into the path but I don't know it ahead of time. This seems like something that should be automatic is there a setting I'm missing or am I running the wrong version of lua? I'm using NLua 4.0
Thanks
I tested this script using node-lua and it fixes the issue for me!
https://gist.github.com/hoelzro/1299679
Relavent code:
local oldrequire = require
function require(modname)
local regular_loader = package.loaders[2]
local loader = function(inner)
if string.match(modname, '(.*)%.') then
return regular_loader(string.match(modname, '(.*)%.') .. '.' .. inner)
end
end
table.insert(package.loaders, 1, loader)
local retval = oldrequire(modname)
table.remove(package.loaders, 1)
return retval
end
To get this to work with Lua 5.2 change all uses of package.loaders to package.searchers.
Also if you want to override the global require function you need this snippet as well:
_G.require = require
You can alter the search behavior of require by changing the package.path variable.
Resources on package.path:
https://www.lua.org/manual/5.3/manual.html#pdf-package.path
http://lua-users.org/wiki/PackagePath
Example adding foo folder to search locations:
package.path = package.path .. ';./foo/?.lua'
the ? character will be where the string passed to require is placed.
Alternatively you can add a default file to load, to the package.path:
package.path = package.path .. ';./nested_require.lua'
Then define the behavior you would like within this file. You can use the global variable _REQUIREDNAME to reference the value passed to the require function.
The documentation for this method can be found here at the bottom of the page: https://www.lua.org/pil/8.1.html
I need to call a LUA function, defined in another my .lua file; from another. So, what I want is the classic C/C++ include approach.
I tried with the following:
(file funcs.lua)
function myfunc(arg1, arg2)
..dosomething
end
and
(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
require "funcs"
myfunc(1, 2)
The require works good, but at execution I get this error:
attempt to call global 'myfunc' (a nil value)
How come?
Thanks in advance,
Thank you all for the comments; I'm running LUA under OpenResty/Nginx.
I solved by exporting directly the function(s), I don't know if this is the preferred method, but I noticed that is used by lots of newer LUA modules.
For example, I changed the code as follows:
file (funcs.lua)
local A = {}
function A.myfunc(arg1, arg2)
..dosomething
end
return A
(file main.lua)
package.path = package.path .. ";/path/to/libs/?.lua"
funcs = require "funcs"
funcs.myfunc(1, 2)
This works good and it's nice to have every function to be manually exported, in a sort of OOP-style.
If I have a file structure like this:
./main.lua
./mylib/mylib.lua
./mylib/mylib-utils.lua
./mylib/mylib-helpers.lua
./mylib/mylib-other-stuff.lua
From main.lua the file mylib.lua can be loaded with full path require('mylib.mylib'). But inside mylib.lua I would also like to load other necessary modules and I don't feel like always specifying the full path (e.g. mylib.mylib-utils). If I ever decide to move the folder I'm going to have a lot of search and replace. Is there a way to use just the relative part of the path?
UPD. I'm using Lua with Corona SDK, if that matters.
There is a way of deducing the "local path" of a file (more concretely, the string that was used to load the file).
If you are requiring a file inside lib.foo.bar, you might be doing something like this:
require 'lib.foo.bar'
Then you can get the path to the file as the first element (and only) ... variable, when you are outside all functions. In other words:
-- lib/foo/bar.lua
local pathOfThisFile = ... -- pathOfThisFile is now 'lib.foo.bar'
Now, to get the "folder" you need to remove the filename. Simplest way is using match:
local folderOfThisFile = (...):match("(.-)[^%.]+$") -- returns 'lib.foo.'
And there you have it. Now you can prepend that string to other file names and use that to require:
require(folderOfThisFile .. 'baz') -- require('lib.foo.baz')
require(folderOfThisFile .. 'bazinga') -- require('lib.foo.bazinga')
If you move bar.lua around, folderOfThisFile will get automatically updated.
You can do
package.path = './mylib/?.lua;' .. package.path
Or
local oldreq = require
local require = function(s) return oldreq('mylib.' .. s) end
Then
-- do all the requires
require('mylib-utils')
require('mylib-helpers')
require('mylib-other-stuff')
-- and optionally restore the old require, if you did it the second way
require = oldreq
I'm using the following snippet. It should work both for files loaded with require, and for files called via the command line. Then use requireRel instead of require for those you wish to be loaded with a relative path.
local requireRel
if arg and arg[0] then
package.path = arg[0]:match("(.-)[^\\/]+$") .. "?.lua;" .. package.path
requireRel = require
elseif ... then
local d = (...):match("(.-)[^%.]+$")
function requireRel(module) return require(d .. module) end
end
Under the Conky's Lua environment I've managed to include my common.lua (in the same directory) as require(".common"). Note the leading dot . character.
Try this:Here is my findings:
module1= require(".\\moduleName")
module2= dofile("..\\moduleName2.lua")
module3 =loadfile("..\\module3.lua")
To load from current directory. Append a double backslash with a prefix of a fullstop.
To specify a directory above use a prefix of two fullstops and repeat this pattern for any such directory.e.g
module4=require("..\\..\\module4")