0

I'm not sure if the title makes sense, but I'll try to explain what I'm trying to do.

I have a file with some code like:

some_var = 3;
...
func(some_var);

The file has a bunch of calls to func and I'd like to find all occurrences of the variable passed to each call. In this case I'd like to find some_var on the line where it is assigned as well as where it is passed to the function. Unfortunately the variable name may differ in each instance, so I can't just search for the variable name directly.

Is there some way to search for the call to the function, capture the argument passed to it and then set the search pattern to that argument?

I tried the following, but it seems sub-expressions don't work with the :g command:

:g/func(\(\w\+\))/let @/ = \1
5
  • something like /\v(\w+)\s*\=\s*\d+;\n(.*\n)*func\(\1\) ?
    – Sundeep
    Commented Apr 24, 2018 at 8:56
  • 1
    What do you want to do once you've found the next occurrence? Do you want to perform some operation, or just manually inspect each one?
    – Rich
    Commented Apr 24, 2018 at 10:02
  • @Rich for now, I'm just looking to manually inspect each one.
    – Pak
    Commented Apr 24, 2018 at 13:53
  • @Sundeep unfortunately, that's not quite what I'm looking for since. Sorry if my example wasn't entirely clear. The idea is that I don't necessarily know what the variable name is that I'm looking for, so I want to find the calls to func and then find argument passed to the function.
    – Pak
    Commented Apr 24, 2018 at 13:56
  • @Pak that regex is not using any specific variable name, only the function name(func in given sample)... if \w is not sufficient to cover all variable names, try \S instead..
    – Sundeep
    Commented Apr 24, 2018 at 14:19

1 Answer 1

2

I'd probably use a simple macro for this:

qq/func(./e<CR>#q

N.B In the above, <CR> is a single press of your Return key.

Broken down:

  • qq Start recording a macro into the "q register,
  • /func(./e<CR> Search for the function, leaving the cursor on the first character of the argument .
  • # Search backwards for the variable
  • q Stop recording the macro.

You can then press n if necessary, to continue searching backwards for the variable, in case it is assigned to more than once.

When you've finished inspecting that variable, press Ctrl-O to step back through the jumplist until you're back at the function call, and then press @q to replay the macro to find the next call to the function and the argument that is passed to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.