I'm using nvim for Flutter development. From time to time, if I save a file with compilation errors, then the emulator still hotloads it and my PC hangs.
I use a custom key mapping to save my files. I'd like that to call a function which checks that (pseudo code)
if lua vim.lsp.diagnostic.get_count() > 0 echo an error, else do the save
With Neovim LSP diagnostics, you could use this function to get count of diagnostics of each type (error, warning, info, hint) :
get_diag_count = function()
local diagnostics = vim.diagnostic.get(0)
local count = { 0, 0, 0, 0 }
for _, diagnostic in ipairs(diagnostics) do
if vim.startswith(vim.diagnostic.get_namespace(diagnostic.namespace).name, 'vim.lsp') then
count[diagnostic.severity] = count[diagnostic.severity] + 1
end
end
error_count = count[vim.diagnostic.severity.ERROR]
warning_count = count[vim.diagnostic.severity.WARN]
info_count = count[vim.diagnostic.severity.INFO]
hint_count = count[vim.diagnostic.severity.HINT]
return error_count, warning_count, info_count, hint_count
end
Related
I want to create a mapping in my neovim lua setup such that when I have a visual selection and hit <leader>ps, a telescope search is initiated with the selected text.
Here is what I have for the moment:
local builtin = require('telescope.builtin')
local function get_visual_selection()
local s_start = vim.fn.getpos("'<")
local s_end = vim.fn.getpos("'>")
local n_lines = math.abs(s_end[2] - s_start[2]) + 1
local lines = vim.api.nvim_buf_get_lines(0, s_start[2] - 1, s_end[2], false)
lines[1] = string.sub(lines[1], s_start[3], -1)
if n_lines == 1 then
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3] - s_start[3] + 1)
else
lines[n_lines] = string.sub(lines[n_lines], 1, s_end[3])
end
return table.concat(lines, '\n')
end
vim.keymap.set('n', '<leader>ps', function() -- works fine
builtin.grep_string({ search = vim.fn.input("Grep > ") });
end)
vim.keymap.set('v', '<leader>ps', function() -- gets the same first value for sel everytime!
local sel = get_visual_selection();
builtin.grep_string({ search = vim.fn.input("Grep > " .. sel) });
end)
This code works on the first time; but then the first text retrieved from selection never changes! I get the first text I selected over and over. I don't understand what is causing that. It seems the function gets hit by some sort of caching mechanism from lua...?
I finally used a different and simpler way of doing this exact thing using a remap, yank and paste; I still don't know what's wrong in my question's lua script though.
Here is the working lua map:
vim.keymap.set('v', '<leader>ps', 'y<leader>ps<C-r>*', { remap = true });
I'm trying to migrate some old vimscript to lua. I have a bunch of settings for 'prose' and now have these in .config/nvim/plugin/functions.lua as:
function prose()
vim.o.fdo:append('search')
vim.bo.virtualedit = block
-- more commands
end
Then in prose.lua:
local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
group = "textedit",
pattern = {"*.adoc", "*.md", "*.tex"},
callback = "prose",
})
vim.api.nvim_create_user_command(
'Prose',
"call prose()",
{nargs = 0, desc = 'Apply prose settings'}
)````
But either the autocommand on opening an .adoc file or running :Prose on the command line will return:
````E117: Unknown function: prose````
How can I make my 'prose' function available?
First, your functions.lua file must be in .config/nvim/lua/ directory.
For your autocommand, modify callback to require functions.lua and function prose:
callback = require('functions').prose()
For your user command:
vim.api.nvim_create_user_command('Prose', function()
require('functions').prose()
end,
{nargs = 0, desc = 'Apply prose settings'}
)
Commenting on Icheylus's reply.
By assigning the callback like this
callback = require('functions').prose()
You are trying to assign the output of the function to the callback. This would work if your function returned a function, but your function returns nothing.
Thus a simple tweak is to just remove the ()
callback = require('functions').prose
Or you could even create your function if it is really simple right in the callback of the autocommand.
local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
group = "textedit",
pattern = {"*.adoc", "*.md", "*.tex"},
callback = function()
vim.o.fdo:append('search')
vim.bo.virtualedit = block
-- more commands
end,
})
I'm new to Lua and was following the tutorial on https://wowwiki.fandom.com/wiki/AddOn_tutorial but i just cant get it to work; i have copied the code but i get the error message "attempt to call a global 'functionname' (a nil value)" on both the SetMapToCurrentZone() and the GetPlayerMapPosition("player") functions.
This is the entire Lua file;
local zone = nil
local TimeSinceLastUpdate = 0
local function UpdateCoordinates(self, elapsed)
if zone ~= GetRealZoneText() then
zone = GetRealZoneText()
SetMapToCurrentZone()
end
TimeSinceLastUpdate = TimeSinceLastUpdate + elapsed
if TimeSinceLastUpdate > .5 then
TimeSinceLastUpdate = 0
local posX, posY = GetPlayerMapPosition("player");
local x = math.floor(posX * 10000)/100
local y = math.floor(posY*10000)/100
eCoordinatesFontString:SetText("|c98FB98ff("..x..", "..y..")")
end
end
function eCoordinates_OnLoad(self, event,...)
self:RegisterEvent("ADDON_LOADED")
end
function eCoordinates_OnEvent(self, event, ...)
if event == "ADDON_LOADED" and ... == "eCoordinates" then
self:UnregisterEvent("ADDON_LOADED")
eCoordinates:SetSize(100, 50)
eCoordinates:SetPoint("TOP", "Minimap", "BOTTOM", 5, -5)
eCoordinates:SetScript("OnUpdate", UpdateCoordinates)
local coordsFont = eCoordinates:CreateFontString("eCoordinatesFontString", "ARTWORK", "GameFontNormal")
coordsFont:SetPoint("CENTER", "eCoordinates", "CENTER", 0, 0)
coordsFont:Show()
eCoordinates:Show()
end
end
How do i fix it?
These functions have been renamed and moved to a wrapper object in 8.0, to C_Map.GetBestMapForUnit (requiring "player" as parameter to yield the same result) and C_Map.GetPlayerMapPosition respectively.
You can probably expect more functions that are called later to throw the same error, their lines just couldn't be reached before. I can check the whole code example when I'm at a desktop again, but you may simply look up these functions on Wowpedia, especially other map-related functions.
I suggest using Wowpedia over Wowwiki, it's a personal preference/impression, the former seems to receive more constant updates.
(The two seem to be merging again now, after splitting 10 years ago)
My code are as follow:
local ffi = require "ffi"
local ffi_C = ffi.C
local ffi_typeof = ffi.typeof
local ffi_new = ffi.new
local ffi_string = ffi.string
local NULL = ngx.null
local tostring = tostring
ffi.cdef[[
char * strtok(char * str, const char * delimiters);
]]
local p_char_type = ffi_typeof("char[?]")
function split(src, c)
local result = {}
local pch = ffi_new(p_char_type, 1)
local psrc = ffi_new(p_char_type, #src)
local pc = ffi_new(p_char_type, #c)
ffi.copy(psrc, src)
ffi.copy(pc, c)
pch = ffi_C.strtok(psrc, pc)
while pch do
table.insert(result, ffi_string(pch))
pch = ffi_C.strtok(NULL, pc)
ngx.log(ngx.ERR, "pch ok")
end
ngx.log(ngx.ERR, "split ok")
return result
end
When I run my nginx, there are something wrong happened!
After return by the while loop, the nginx worker process crashed with signal 11.
The last ngx.log can not run.
How can I deal with it?
local psrc = ffi_new(p_char_type, #src)
ffi.copy(psrc, src)
ffi.copy when given a string source also copies a null terminator, but your array is too small to hold it, resulting an overflow.
Also, instead of using strtok, consider using Lua patterns. They are safer, easier to use, and don't depend on the FFI.
Platform: (where Lua and LuaSocket are ported)
An embedded system using ARM 7 development board running 3rd party RTOS with TCP/IP stack.
What works:
Using Lua standard library such as "io" calls, print, assert, etc
sending UDP packets by using the udp = assert(socket.udp) method, assert(udp:send(something))
Problem:
When executing an example smtp lua script:
local smtp = require("socket.smtp")
from = "myEmail"
rcpt = {"<someOne's Email>"}
mesgt = { heasers = {someHeader}, body = "Hello World" }
r, e = smtp.send {
from = from,
rcpt = rcpt,
source = smtp.message(mesgt),
server = "someServer",
port = 25,
}
-- an error returns after execution:
-- lua\socket\smtp.lua:115: attempt to call field 'try' (a nil value)
-- Corresponding code in smtp.lua around line 115:
function open(server, port, create)
local tp = socket.try(tp.connect(server or SERVER, port or PORT,
TIMEOUT, create))
local s = base.setmetatable({tp = tp}, metat)
-- make sure tp is closed if we get an exception
s.try = socket.newtry(function()
s:close()
end)
return s
end
// Where try = newtry() in socket.lua and the corresponding C code is the same
// from the one provided with the library for UNIX:
static int global_newtry(lua_State *L) {
lua_settop(L, 1);
if (lua_isnil(L, 1)) lua_pushcfunction(L, do_nothing);
lua_pushcclosure(L, finalize, 1);
return 1;
}
Well, since the error says that "try is nil", then my best guess is that the C lib is not correctly, or not completely, linked to your Lua. This could be the result of a faulty installation, a missing lib, or something of that sort.