maverik
maverik

Reputation: 5606

Vim: replacing text within function body

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.

Upvotes: 7

Views: 6825

Answers (3)

Troy1684
Troy1684

Reputation: 11

I've always used [[ to jump to the beginning of the function, then use % to jump to the end of the function. I used mt and mb to mark the top and bottom of the function, respectively. Then to search and replace within the marked top and bottom, :'t,'bs/pattern/newpattern/g. This has always worked for me. I'm sure you can create a macro for this.

The visual select (vi}) is much easier and faster. It is aware of the cursor position. So, if the cursor is inside a fucntion sub block, then vi} selects all lines in that block. If you want to select the entire function, one needs to place the cursor outside of the sub blocks then do vi}. This is great for function blocks that fits in the current window. For functions that spans beyond the current window, the selection is lost once scroll up.

I really like the visual select of the vi} because it's so much easier and faster, but I have to resort the old school method on occasion.

Upvotes: 1

Xavier T.
Xavier T.

Reputation: 42278

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.

Upvotes: 19

MrB
MrB

Reputation: 96

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.

Upvotes: 8

Related Questions