Hubro
Hubro

Reputation: 59403

How do I prevent changing buffer when using the :bufdo command?

This command replaces some text in all my buffers:

:bufdo %s/some_text/other_text/ge | update

When running this command, the buffer of the current window is changed to the last buffer affected by :bufdo, as explained in :help :bufdo:

The last buffer (or where an error occurred) becomes
the current buffer.

I know it's possible to prevent the buffer from being changed, but I don't remember how.

Upvotes: 6

Views: 858

Answers (3)

WW00WW
WW00WW

Reputation: 437

" Like bufdo but restore the current buffer.
function! BufDo(command)
  let currBuff=bufnr("%")
  execute 'bufdo ' . a:command
  execute 'buffer ' . currBuff
endfunction
com! -nargs=+ -complete=command Bufdo call BufDo(<q-args>)

Reference: https://vim.fandom.com/wiki/Run_a_command_in_multiple_buffers#

Upvotes: 3

Ben
Ben

Reputation: 8905

You can save off the current buffer before running the command, then jump to it after:

:let buf=bufnr('%') | exec 'bufdo some_command' | exec 'b' buf

Upvotes: 10

Ingo Karkat
Ingo Karkat

Reputation: 172698

My ArgsAndMore plugin has a :Bufdo alternative to :bufdo that returns to the original buffer (and similar variants for :argdo etc.)

Upvotes: 2

Related Questions