sponsor Vim development Vim logo Vim Book Ad

basic Tip #70: running a command on all buffers

 tip karma   Rating 59/21, Viewed by 3930 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   May 30, 2001 12:09      complexity:   basic
author:   Scott Johnston      as of Vim:   5.7

From Peter Bismuti on the vim list:

How to global search and replace in all buffers with one command?
You need the AllBuffers command:

:call AllBuffers("%s/string1/string2/g")

"put this in a file and source it
function AllBuffers(cmnd)
  let cmnd = a:cmnd
  let i = 1
  while (i <= bufnr("$"))
    if bufexists(i)
      execute "buffer" i
      execute cmnd
    endif
    let i = i+1
  endwhile
endfun

":call AllBuffers("%s/foo/bar/ge|update")

Thanks Peter!

 rate this tip  Life Changing Helpful Unfulfilling 

<< dot makes life easier | Transfer text between two gvim sessions using clipboard >>

Additional Notes

[email protected], June 4, 2001 19:07
I like this one better as you know exactly what is getting changed and it doesn't require writing any buffers, it just modifies them.

" execute a command for all buffers ther are shown in windows
fun! AllWindows(cmnd)
    let cmnd = a:cmnd
    let origw = winnr()
    let i = 1
    while (i <= bufnr("$"))
        if bufexists(i)
            let w = bufwinnr(i)
            if w != -1
                echo "=== window: " . w . " file: " . bufname(i)
                execute "normal \<c-w>" . w . "w"
                execute cmnd
            endif
        endif
        let i = i+1
    endwhile
    execute "normal \<c-w>" . origw . "w"
endfun
[email protected], June 4, 2001 22:43


From Janakiraman .S:    


Addiing those quotes is pretty boring. That is easy to fix. Just make a
command like
command! -nargs=+ -complete=command AllBuf call AllBuffers(<q-args>)

You could then replace across multiple files with
:AllBuf %s/foo/bar/ge
[email protected], January 9, 2002 6:33
What about the |argdo| and |bufdo| and |windo| commands?

Gergely Kontra
[email protected], September 13, 2002 13:47
bufdo works for me.  Perhaps it's a new feature.
[email protected], February 24, 2004 21:00
bufdo disables syntax highlighting when moving between the buffers and hence is very fast.

If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to [email protected] after searching the archive. Help Bram help Uganda.
   
Sponsored by Web Concept Group Inc. SourceForge.net Logo