Jake Bringham
Jake Bringham

Reputation: 66

Match Variadic Function - Vim Regex

Suppose you have the following C function:

void foo(int a, int b, const char* fmt, ...)

and you wanted to find/replace function calls of foo() with bar()

void bar(int a, int b, int c, const char* fmt, ...)

How would you match calls of foo() with capture groups around a, b, fmt as well as the variadic arguments ...?

I would also like the solution to not depend on the data type of the parameters at all if possible.

My current attempt is: foo(\(.*\),\s*\n*\s*\(.*\),\s*\n*\s*\(.*\),\s*\n*\s*\(.*\));

But it breaks as the final \(.*\) doesn't match newlines with the wildcard character.

Upvotes: 0

Views: 105

Answers (1)

romainl
romainl

Reputation: 196546

Best solution: use an actual refactoring tool.

Best time/effort compromise in Vim:

  1. Search your whole project for foo() calls with something like:

    :grep -r foo\( **/*.{c,h}
    

    This populates the quickfix list with entries for each line where there is an occurrence of foo( in the given files.

  2. substitute foo with bar on each match, with confirmation:

    :cdo s/foo(/bar(/gc
    

    This runs the substitution on every entry in the quickfix list and thus on every line where there is an occurrence of foo(. With the /c flag, you get a prompt asking you to confirm the substitution. It is a bit pedestrian but:

    • it puts you in control of the refactoring,
    • it also works on comments,
    • it doesn't require too much regexp work upfront, ie: you would be finished by now.

Upvotes: 1

Related Questions