Lua command that writes to buffer at cursor

I want to create a lua command where you give it a lua function, and it executes the function and then writes the function’s output to the current buffer at the current cursor position

I’ve tried something like this

function please_redirect_my_output()
  print('hello world') -- some output to redirect
end

function redirect_f(f)
  vim.fn.execute('redir @">')
  f()
  vim.fn.execute('redir END')
end

and then I do lua redirect_f(please_redirect_my_output) but that doesn’t work. what am I missing? what don’t I understand about redir and execute?

1 Like

You are setting the unnamed register, but you are not doing anything with it.

You would need to output it to the buffer using vim.api.nvim_buf_set_text or vim.api.nvim_buf_set_lines if you don’t care about cols. You can retrieve the register with vim.fn.getreg.

There is also :put.