I have a callback/generator which produces output, possibly after a delay. I'd like to send these outputs to the terminal buffer as they're produced. Here's a mockup:
local term_buf = vim.api.nvim_create_buf(false, true)
local term_chan = vim.api.nvim_open_term(term_buf, {})
vim.api.nvim_open_win(term_buf, false, { split = "right" })
local outputs = { "First", "Second", "Third", }
local generate_result = function()
os.execute("sleep 1")
return table.remove(outputs, 1)
end
while true do
local result = generate_result()
if not result then
break
end
vim.api.nvim_chan_send(term_chan, result .. "\n")
end
If you run the above you'll find that, instead of opening the terminal and updating once per second, Neovim becomes blocked for three seconds until the terminal opens and all results appear at once.
The closest I've gotten to having this run in 'real time' is to replace the final while loop with a recursive function that only schedule()s the next send after the previous one has been sent. This only works intermittently though, and still blocks Neovim while generate_result() is running:
-- I've tried this instead of the above `while` loop
local function send_next()
local result = generate_result()
if not result then
return
end
vim.api.nvim_chan_send(term_chan, result .. "\n")
vim.schedule(send_next)
end
vim.schedule(send_next)