-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Description
Hello, this is just an idea. So with Emacs, in the scratch buffer (technically any buffer), you can evaluate an expression and get the output below the current line. This is particularly useful with the scratch buffer, as it is most often used to quickly perform math or test something. You can achieve this in Neovim with the following snippet:
local function eval_and_insert(args)
local lines = vim.api.nvim_buf_get_lines(0, args.line1 - 1, args.line2, false)
local code = table.concat(lines, "\n")
local chunk, err = load("return " .. code)
if not chunk then
chunk, err = load(code)
end
if not chunk then
vim.notify("Lua Parse Error: " .. err, vim.log.levels.ERROR)
return
end
local ok, result = pcall(chunk)
if not ok then
vim.notify("Lua Exec Error: " .. result, vim.log.levels.ERROR)
return
end
local output = vim.split(vim.inspect(result), "\n")
vim.api.nvim_buf_set_lines(0, args.line2, args.line2, false, output)
end
vim.api.nvim_create_user_command('Eval', eval_and_insert, { range = true })
-- Example keybinding
vim.keymap.set({ "n", "v" }, "<leader>ex", ":Eval<cr>", { desc = "Evaluate Lua and print output" })The only issue is that if you attempt to evaluate multiple expressions simultaneously, it will throw an error.
You can, however, evaluate a function, and its return value is what is added.
Ex:
-- Eval this:
"Hello World"
-- Inserts this below it:
"Hello World"
-- Eval this:
(function(str)
return str
end)("Hello World")
-- Inserts this:
"Hello World"
-- Eval this:
function (str)
return str
end
-- Inserts this:
<function-1>
-- Eval
function stuff(str)
return str .. "!"
end
stuff("Hello world")
-- Inserts:
nil
-- Eval
function stuff(str)
return str .. "!"
end
return stuff("Hello world")
-- Inserts:
"Hello world!"
-- Eval:
x = 1
-- Result:
nil
-- Eval:
x
-- Result:
1
-- Eval (note if you use local, you have to use return, because load wraps the text inside of a function):
local x = 2
return x
-- Result:
2I think you get the idea at this point.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels