Validate lua code in luapopup before hiding popup

main
Ensar Sarajčić 2022-05-07 12:33:53 +02:00
parent ced575da82
commit 3ffc8dd1be
2 changed files with 25 additions and 3 deletions

View File

@ -7,6 +7,16 @@ function M.eval_lua_buffer(bufnr)
return M.eval_lua_code(table.concat(buffer_content, "\n"))
end
function M.is_valid_lua_code(code_string)
local res = loadstring(code_string)
return type(res) == "function", res
end
function M.is_valid_lua_code_buffer(bufnr)
local buffer_content = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
return M.is_valid_lua_code(table.concat(buffer_content, "\n"))
end
function M.eval_lua_code(code_string)
-- Taken from https://github.com/bfredl/nvim-luadev/blob/master/lua/luadev.lua
local block = coroutine.create(loadstring(code_string))

View File

@ -19,6 +19,13 @@ local eval_functions = {
[popup_type.lua] = lua_utils.eval_lua_buffer,
[popup_type.fennel] = lua_utils.eval_fennel_buffer,
}
local validate_functions = {
[popup_type.lua] = lua_utils.is_valid_lua_code_buffer,
[popup_type.fennel] = function(_)
-- No validation for fennel
return true
end,
}
local function get_last_win(type)
if type == popup_type.lua then
@ -80,9 +87,14 @@ local function popup_and_run(type)
-- map keys
win:map("n", "<CR>", function(_)
hidden = true
win:hide()
run()
local valid, message = validate_functions[type](win.bufnr)
if not valid then
vim.notify("Parsing code failed: \n" .. vim.inspect(message), vim.log.levels.ERROR)
else
hidden = true
win:hide()
run()
end
end, { noremap = true })
win:map("n", "<Esc>", function(_)
cancel()