Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: replacing text within function body

Tags:

replace

vim

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.

like image 242
maverik Avatar asked Mar 30 '11 09:03

maverik


People also ask

How do you replace words in Vim?

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.

What command is used to replace a string with another string in vi editor?

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/.

How do I delete a function in Vim?

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 } .


2 Answers

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.

like image 188
Xavier T. Avatar answered Oct 06 '22 20:10

Xavier T.


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.

like image 21
MrB Avatar answered Oct 06 '22 20:10

MrB