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)
Either use writefile()
:
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!
'fileformats'
setting Vim opens these asunix
, and lines ending CRLF will just have a CR visible in the buffer. The mixed endings will therefore be preserved when you write out the file with LF endings. (And if'fileformats'
doesn't containunix
, then LF endings seem to be converted to CRLF on opening.) The bad news is I don't think there's any way of finding out what the buffer's'fileformat'
is without switching to it so you can't really use yourwritefile()
solution anyway. :(getbufvar(...,'&fileformat')
work?