Tip 70 Printable Monobook Previous Next
created May 30, 2001 · complexity basic · author Scott Johnston · version 5.7
How to global search and replace in all buffers with one command?
You need the AllBuffers command defined in this tip:
:call AllBuffers("%s/string1/string2/g")
" Example: :call AllBuffers("%s/foo/bar/ge|update")
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
Comments
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
Adding 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
What about the argdo and bufdo and windo commands?
bufdo disables syntax highlighting when moving between the buffers and hence is very fast.