I would like to write a buffer which isn't the current buffer to a temp file. I have found two ways to do this:
(assuming buffer 42 is the one to be written)
call writefile(getbufline(42, 1, '$'), tmpfile)
Or switch to the target buffer, use
:write, and switch back again:
let current = bufnr('') noautocmd buffer 42 " ... code to store &modified, '[, and '] ... execute 'noautocmd keepalt silent write!' tmpfile " ... code to restore &modified, '[, and '] ... execute 'noautocmd buffer' current
The problem with
writefile() is that it assumes your line endings are NL. If they are CRNL you have to insert the CRs yourself. Either way, you have to assume that all the lines have the same ending – which they really should, but you never know...
The problem with the second is that when you switch away from the current buffer, unknown side-effects might happen. For example, if the current buffer is a neovim terminal buffer, neovim will close it when you leave it.
Is there a better approach than either of these? Is there a better way to implement either of these?
Many thanks in advance!