Vim: replacing text inside function body

I have very useful plugins for finding and replacing text through files (see EasyGrep vim script - this is very useful for programmers). I can even replace text only in the current buffer - using plugins or :%s ... But what if I just want to replace the text inside 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 the c flag to confirm, but I believe there is a faster way to do this.

Thanks.

+4
source share
3 answers

You can mark the function with V. Then, when you enter the command in :, it will be automatically prefixed and will only be executed in the marked area.

There is probably a command to go to the beginning of the function and the end of the function, so you can execute the begin-function, V, end-function function, replace it very quickly. However, I do not know these teams.

+4
source

You can apply substitution to the entire file using % or selection.

To create a selection :

Go to Visual mode Linewise, for example, using Shift+v select several lines and enter :

Your invitation will look like this:: :'<,'> this means: current selection

Type s/foo/bar/g and replace foo with the line in the currently selected line.

the best way to select the contents of a function is to go inside the function with the cursor and type: vi} it will select everything between { and } .

See :help text-objects for more selection tips.

+13
source

I always used [[to go to the beginning of the function, and then use% to go 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 in the marked upper and lower lines : 't,' bs / pattern / newpattern / g . It always worked for me. I am sure you can create a macro for this.

Visual selection (vi}) is much simpler and faster. He knows the position of the cursor. So, if the cursor is inside the fucntion subunit, then vi} selects all the rows in this block. If you want to select the entire function, you need to place the cursor outside the sub-blocks, and then vi}. This is great for function blocks that fit into the current window. For functions that are outside the current window, the selection is lost after scrolling up.

I really like the vi vi visual choice because it is much simpler and faster, but sometimes I have to resort to the old school method.

+1
source

Source: https://habr.com/ru/post/1345849/


All Articles