Can't use or set localleader in neovim - lua

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 = '\\'

Related

How to source init.lua without restarting neovim

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)

Using io.tmpfile() with shell command, ran via io.popen, in Lua?

I'm using Lua in Scite on Windows, but hopefully this is a general Lua question.
Let's say I want to write a temporary string content to a temporary file in Lua - which I want to be eventually read by another program, - and I tried using io.tmpfile():
mytmpfile = assert( io.tmpfile() )
mytmpfile:write( MYTMPTEXT )
mytmpfile:seek("set", 0) -- back to start
print("mytmpfile" .. mytmpfile .. "<<<")
mytmpfile:close()
I like io.tmpfile() because it is noted in https://www.lua.org/pil/21.3.html :
The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends.
However, when I try to print mytmpfile, I get:
C:\Users\ME/sciteLuaFunctions.lua:956: attempt to concatenate a FILE* value (global 'mytmpfile')
>Lua: error occurred while processing command
I got the explanation for that here Re: path for io.tmpfile() ?:
how do I get the path used to generate the temp file created by io.tmpfile()
You can't. The whole point of tmpfile is to give you a file handle without
giving you the file name to avoid race conditions.
And indeed, on some OSes, the file has no name.
So, it will not be possible for me to use the filename of the tmpfile in a command line that should be ran by the OS, as in:
f = io.popen("python myprog.py " .. mytmpfile)
So my questions are:
Would it be somehow possible to specify this tmpfile file handle as the input argument for the externally ran program/script, say in io.popen - instead of using the (non-existing) tmpfile filename?
If above is not possible, what is the next best option (in terms of not having to maintain it, i.e. not having to remember to delete the file) for opening a temporary file in Lua?
You can get a temp filename with os.tmpname.
local n = os.tmpname()
local f = io.open(n, 'w+b')
f:write(....)
f:close()
os.remove(n)
If your purpose is sending some data to a python script, you can also use 'w' mode in popen.
--lua
local f = io.popen(prog, 'w')
f:write(....)
#python
import sys
data = sys.stdin.readline()

How to load host.conf file variables in lua script

I need to load configuration variables from .conf file in lua script, and use those variables to connect to a database. I have tried using:
require "host.conf"
loadfile("host.conf") - error with unexpected token '#'
os.execute("pathToConfFile/host.lua") - and I have created a lua host file with variables in bash shell
io.popen("host.conf") etc..
None of these solutions are valid.
Is there a way to use the existing host.conf file in lua, and avoid the unexpected token error?
Thank you for your suggestions.
local original = io .open('host.conf')
local hostconf = {} -- copy contents into Lua table
for line in original :lines() do
table .insert( hostconf, line )
end ; io .close( original )
print( hostconf[1] ) -- prints line 1
You haven't specified what format your host.conf comes in, but you'll likely want to parse it better than just throwing contents in a list. Perhaps splitting each line into head / tail, based upon a delimiter ( comma, space, whatever you have between variable & value )
Thank you to everyone who helped out. My question wasn't precise and I had more to learn before I have asked and sorry about that. This is what I used to solve the problem.
local open = io.open
local function read_file(path)
local file = open(path, "r")
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
local lines = {}
for line in io.lines(path) do
--print(line);
if(line:find(var)~=nil)then
local varStart=string.len(var)+2
local varEnd=string.len(line)
var=string.sub(line,varStart,varEnd)
print(var);
end
--repeat for every line
end
file:close()
return lines;
end
local fileContent = read_file("path");

Lua Nested Require Path

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

Setting EnableHipHopSyntax to True with HHVM

When I run my code, I get the following error:
Syntax only allowed with -v Eval.EnableHipHopSyntax=true in /var/web/site/myfile.php on line 26
myfile.php has a function at that line that has:
public static function set (
string $theme // <str> The theme to set as active.
, string $style = "default" // <str> The style that you want to set.
, string $layout = "default" // <str> The layout that you want to assign.
): string // RETURNS <str>
The bottom line, ): string" is the appropriate syntax for the hack language, but for some reason HHVM decided to brilliantly disable its own syntax by default.
I can't seem to find any documentation with HHVM that indicates how to set that config file. How can one go about this process?
Edit:
It turns out my HHVM conversion tool was not converting <?php to <?hh as I had instructed it to, due to having converted itself. In other words, it was attempting to convert <?hh to <?hh, which did me no good.
I had mistakenly assumed that HHVM was disabling it for <?hh tags, which was not the case.
This syntax is part of Hack, but you have a PHP file. If you change the opening tag from <?php to <?hh, it'll work.
Alternatively, you can add hhvm.enable_hip_hop_syntax = true to /etc/hhvm/php.ini.

Resources