How can I pipe from shell to a scratch buffer (without file)?

Assume we have the following lua function to create a non-file backed buffer:

M.makeScratch = function(scratchpath)
  local uri = vim.uri_from_fname(scratchpath)
  local bufnr = vim.uri_to_bufnr(uri)
  vim.bo[bufnr].bufhidden = ""
  vim.bo[bufnr].buflisted = true
  vim.bo[bufnr].buftype = "nofile"
  vim.bo[bufnr].readonly = false
  vim.bo[bufnr].swapfile = false
end

Now assume there is shell opened and the uri + buffer number is known (can be found via scratch path).
How can I pipe a command output to the created scratch buffer (not backed by a file)?

1 Like

I don’t have a complete answer, but I’d use the client-server feature of Neovim to pass the --listen option to the Neovim instance that creates a buffer, then run a command to pipe stdin to the server.

You can do it with setlocal and noswapfile.

Here is an example of me trying to get the git tree into a buffer without it wanting me to save the darn thing:

vim.api.nvim_create_user_command(
    'GitTree',
    function(_)
        vim.cmd('ene | r !git ls-tree -r --name-only HEAD | tree --fromfile')
        vim.cmd(':1')
        vim.cmd('setlocal buftype=nofile bufhidden=hide noswapfile')
    end,
    { nargs = 0, bang = false, desc = 'Show unignored git files in the current directory' }
)