local core = require("core")
local command = require("core.command")

local function eval(str)
	local fn, err = load("return " .. str)
	if not fn then
		fn, err = load(str)
	end
	assert(fn, err)
	local results = { fn() }
	if #results == 0 then
		return ""
	end
	for i = 1, #results do
		results[i] = tostring(results[i])
	end
	return table.concat(results, ", ")
end

command.add({
	["eval:insert"] = {
		requires = { "doc", "edit" },
		perform = function()
		core.command_view:enter({
			caption = "Evaluate And Insert Result",
			submit = function(cmd)
				core.active_view.doc:text_input(eval(cmd))
			end,
		})
		end,
	},

	["eval:replace"] = {
		requires = { "doc", "edit" },
		perform = function()
			core.active_view.doc:replace(eval)
		end,
	},
})
