Reputation: 902
I am writing a function in vimscript
that needs to save all changed, listed buffers that start with current working directory. This operation needs to happen in the background, without changing the current active buffer or a cursor position, if possible.
function! SaveChangedBuffers()
for buf in getbufinfo({'buflisted':1})
if but.changed && buf.name =~ getcwd()
echo buf.name
"write buf.name <-- how to do this correctly?
endif
endfor
endfunction
I wasn't able to find a function in vimscript
that actually saves the buffer. I know I can supply a filename to :write
or use a few other options. But I want to make sure I am actually writing all the buffers in a "vim native way" so I don't overwrite or disrupt any other operations or files.
What is the "vim native" way to write a list of buffers to disk from vimscript
?
Upvotes: 4
Views: 1029
Reputation: 902
Looks like I was able to achieve my stated goal with the following:
function! SaveChangedBuffers()
set lazyredraw
let cur_buffer = bufnr('%')
for buf in getbufinfo({'buflisted':1})
if buf.changed && buf.name =~ getcwd()
execute 'buffer' . buf.bufnr
update
" echo buf.name
endif
endfor
execute 'buffer' . cur_buffer
set nolazyredraw
endfunction
lazyredraw
turns off screen changes while script is running. On slower terminal connections you might not even need that. I then remember the current buffer with bufnr('%')
and restore it at the end of the script from the variable.
The loop just changes into each buffer that fits the criteria and performs :update
(which could also be :write
, because I know my buffer has been changed).
And to complete the full vim experience one can map it to an Ex command (Wc
stands for "write changed"):
command! Wc execute SaveChangedBuffers()
Upvotes: 3