Reputation: 10939
How can I save the changes to a modified Vim buffer without switching to that buffer? I am trying to write a function that saves and closes all the buffers in a project.
Upvotes: 0
Views: 285
Reputation: 561
You can't write a buffer without having it in the foreground. However, if you save the buffer number of the foreground buffer, you can restore the foreground buffer after writing the hidden buffer. The screen shouldn't even flicker:
let c=bufnr()|let b=bufnr($MYVIMRC)|if b!=-1|exe "b" b|w|exe "b" c|endif
May fail if :set hidden isn't enabled.
From my .vimrc:
nnoremap <Leader>r :call WriteBufIfOpen($MYVIMRC) \| source $MYVIMRC<CR>
func! WriteBufIfOpen(file)
let c = bufnr('')
let b = bufnr(a:file)
if (b != -1)
exe b."bufdo w"
exe "b" c
endif
endfunc
Upvotes: 0
Reputation: 172500
Apart from the :wqall
command, there's no command that writes a buffer other than the current one.
So you do have to switch to the buffer in order to write it. You could use :noautocmd
to avoid the associated events (but that may have adverse side effects!).
The only alternative would be to use low-level functions like getbufline()
and writefile()
, but then you would have to deal with encoding conversions, fileformat, etc. on your own.
Upvotes: 2
Reputation: 196456
You can use the argument list, see :help argument-list
.
Supposing you are working with three files foo
, bar
, baz
, and want to only write foo
and baz
:
:args foo baz
:argdo w
You'll obviously need additional logic to determine which buffers to put in the arglist in the first place but it sounds like you already have that.
Upvotes: 1
Reputation: 191729
You can use :wqa[ll]
to write and close all changed buffers. :wa
will write without closing.
Upvotes: 2