I have some very useful plugins to find and replace text through files (see EasyGrep
vim script - it's very helpful for programmers). I can even replace text only in the current buffer - by using plugins or :%s ...
. But what if I just want replace text within the current function body?
Consider the following example:
void f0()
{
int foo = 0;
// ...
}
// 99 other functions that uses foo as local variable.
void f100()
{
int foo = 0; // I want to replace foo with bar only in this function
// 1000 lines of code that uses foo goes below
// ...
}
Of course, I can use :%s ...
with c
flag for confirmation, but I believe there is a faster way to do this.
Thanks.
The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.
After running a search once, you can repeat it by using n in command mode, or N to reverse direction. When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/.
If your cursor is on the line with the function name, try d } . It will delete everything to the next block (i.e. your function body). Within the function body itself, d a p will delete the 'paragraph'. You can delete a curly brace block with d a } .
You can apply a substitution to the whole file using %
or on a selection.
To create a selection :
Go in Visual mode Linewise for example, with Shift+v
, select a few line and then type :
.
Your prompt will look like :
:'<,'>
it means : current selection
Type then s/foo/bar/g
and it will replace foo by bar in the current selected line.
The better way to select a function content is to go inside a function with your cursor and type :
vi}
it will select everything between {
and }
.
See :help text-objects
for more tips on selection.
You could mark the function with V. Then when you type a command in :, it'll automatically be prefixed by and only be executed in the marked area.
There's probably a command for jumping to beginning of function and end of function, so you could do begin-function, V, end-function, substitute very quickly. Don't know those commands though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With