Sandeep
Sandeep

Reputation: 19502

vim - search and replace a function

I want to replace a function in the following way.

Old function :
old_func(a,b,c)

New function :
new_func(b,a,c)

How to replace old_func with new_func and also take care of arguments(in vim)?

Upvotes: 0

Views: 704

Answers (3)

anon
anon

Reputation:

Getting this done in a single pass would be difficult. If you always have the same arguments a and b, then you could probably write a regex (or macro, as was already suggested) for it, but I'm assuming that's not the case and you have different expressions in different places.

My solution would rely on my sideways.vim plugin. Basically, first replace old_func with new_func, then go around all usages and use the plugin to swap the two arguments.

For convenience, I'd also use another plugin of mine, writable_search that puts all search results in a single buffer. And if you have them in a single buffer, it would be easy to automate the argument swapping as well, with a macro.

If the :SidewaysRight command is mapped to s>, then the process would be:

  • Search for the function in the buffer with /old_func(
  • Start recording a macro with qq
  • Change the function name with, say, cwnew_func<esc>
  • Go to the first argument with a f(l
  • Perform the sideways motion, s>
  • Go to the next match with n
  • Stop the macro with a q

Now, executing @q will go to the next match and perform the action.

Upvotes: 0

spoorcc
spoorcc

Reputation: 2955

I personally prefer macro's since that requires less brain energy. You record 1 edit and play that back as much as you want.

First search for old_func:

/old_func<ENTER>

Start recording a macro in register q:

qq

Go to the next occurence of new_func and change old into new :

n      # Next occurence
ct_    # change until '_'
new    # 'new'
ESC    # back to normal mode

Go inside the bracket and switch the arguments

f(l    # find '(' and step 1 to the right
d2l    # delete two characters ( 'a' and ',' )
l      # move 1 place to the right
p      # paste deleted characters

Stop recording macro:

q

Playback macro

@q     # once
500@q  # 500 times, it will stop if it can't find anymore occurences of old_func

UPDATE

If your arguments are not called a and b than you can switch the arguments like this:

f(l    # find '(' and step 1 to the right
df,    # delete the characters including the comma
f,     # move to the next comma
p      # paste deleted characters

Upvotes: 2

Fabricator
Fabricator

Reputation: 12782

vim supports backreference (\1 for the first captured group and \2 for the second):

%s/\<old_func(\([^,]*\),\([^,]*\),/new_func(\2,\1,/g

Upvotes: 5

Related Questions