Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In VIM, how do I write all (:wa), but only for non-hidden buffers?

Tags:

vim

Sometimes I switch Git branches without closing VIM buffers for files that are unique to the current branch. Those buffers will be hidden, and I'll open new buffers in splits and start making changes for the new branch. Rather than :w individually on those new buffers, I'd like to :wa, but that writes to all buffers, including the old ones that are now hidden.

This is frustrating because it writes those old buffers to new files since they don't exist, dirtying my branch.

How do I :wa, but only for the non-hidden buffers that are actively open in my splits?

like image 319
DylanReile Avatar asked Oct 04 '18 22:10

DylanReile


2 Answers

Since the buffers you want to write are all displayed in windows you can:

:windo w

or the slightly smarter:

:windo update

See :help :windo and :help :update.

like image 136
romainl Avatar answered Nov 15 '22 09:11

romainl


There is no native command to do that, but creating your own is not very difficult. Buffers have attributes, and you are looking for the ones considered active, which have the hidden flag set to false.

You can get a list of buffers with getbufinfo(). This functions returns an array of dictionaries containing buffer information. Then it is a matter of iterating over these entries and if it does not represent a hidden buffer, perform the write (or :update).

As far as I know there is no native way to perform a command in a different buffer without switching to it. We are thus forced to switch to a different buffer to perform a command. This would mess up your current buffer, but can be solved by saving it before looping and restoring later.

The following function does that, and the accompanying custom command :Wa just calls it.

function! WriteActiveBuffers()
  " Save current buffer number
  let current = bufnr('%')
  for buffer in getbufinfo({'buflisted':1})
    if !buffer["hidden"]
      " Found an active buffer
      " Switch to it
      execute 'buffer' buffer["bufnr"]
      " Write if modified
      update
    endif
  endfor
  " Restore current buffer
  execute 'buffer' current
endfunction

command! Wa call WriteActiveBuffers()
like image 44
sidyll Avatar answered Nov 15 '22 08:11

sidyll