Search and replace in all open buffers
From Vim Tips Wiki
Tip 382 Previous Next created December 4, 2002 · complexity basic · author Sean · version 6.0
Useful for doing simple refactoring i.e. changing a method or variable name. Prompts for a word and then replaces all instances of <cword> in open buffers with the word.
" Search for <cword> and replace with input() in all open buffers
fun! Replace()
let s:word = input("Replace " . expand('<cword>') . " with:")
:exe 'bufdo! %s/' . expand('<cword>') . '/' . s:word . '/ge'
:unlet! s:word
endfun
map \r :call Replace()<CR>
[edit] Comments
Two things you need to be careful about here:
1. To actually succeed in changing between files after they have had changes made requires that the 'autowrite' option be turned on, otherwise Vim will fail with an error message that "changes made have not been saved", and stop the 'bufdo' operation.
2. The other is that bufdo operates on all the currently loaded buffers (those that may not currently be open in a window, but not those that are 'unloaded', see help for more detail). So for instance, you open up a new C file, and you have a template that gets read into it, that template is in your buffer list, and will be subject to your search and replace function.
