简体   繁体   中英

Vim: change a function's call-signature througout the code-base

I'm slowly turning Vim into my IDE-of-choice, with ctags and static-analysis/autocompletion/etc plugins (eg vim-jedi, youcompleteme, etc). But I haven't found anything that can do one specific task:

Say I have a function (I'll use Python here):

def my_function(outFile, foo, bar):
  outFile.write(foo[bar])

Later I change its signature so the outFile positional-argument is a named one:

def my_function(foo, bar, outFile=None):
  if outFile is None:
      outFile = getDefaultOutfile()
  outFile.write(foo[bar])

Now I want to change all of the old calls, thoughout the entire codebase:

my_function(oF, f, b)

to

my_function(f, b, outFile=oF)

Is there an easy way to do this in Vim (or other Linux utils eg sed)? I know PyCharm etc can do this, but I'm not intending to jump ship just yet.

You can do this following regex substitution:

:s/\vmy_function\((\w*), (\w*), (\w*)\)/my_function(\2, \3, outfile=\1)/g

Read up on vimregex , specifically capturing groups. Basically, whatever (\\w*) matches will be saved and named \\1 (then \\2 , \\3 , etc.) for us to use in the replacement later.

It's worth noting that this works for your example, but will not work if there's extra or missing spaces. To make this more robust, you could change it to:

:s/\vmy_function\((\w*),\s*(\w*),\s*(\w*)\)/my_function(\2, \3, outfile=\1)/g

As an alternative to find (described in an earlier comment), one can also use grep to open the files containing the desired function:

vim `grep -l 'my_function' *py`

The files will be loaded in different buffers. Then use a general buffer replacement:

bufdo %s/\(my_function\)(.*)/\1(f, b, outFile=oF)/gc

The c flag here is optional but I would recommended for this particular replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM