sponsor Vim development Vim logo Vim Book Ad

basic Tip #382: Search and replace in all open buffers

 tip karma   Rating 13/4, Viewed by 2122 

created:   December 4, 2002 16:56      complexity:   basic
author:   Sean      as of Vim:   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>

Thanks to Jurgen Kraemer for showing me how to use the :exe command :)

Sean

 rate this tip  Life Changing Helpful Unfulfilling 

<<Running the win32-version of Vim from cygwin | a Map to jump to a subroutine/function from where it is called >>

Additional Notes

pottsdl at netzero.net, December 5, 2002 7:41
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.

Great tip, just wanted to help out with any disclaimers....
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 Logo