[英]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). 我正在使用ctags和static-analysis / autocompletion / etc插件(例如vim-jedi,youcompleteme等)将Vim慢慢变成我的IDE选择。 But I haven't found anything that can do one specific task:
但是我还没有发现可以完成一项特定任务的任何东西:
Say I have a function (I'll use Python here): 说我有一个函数(我将在这里使用Python):
def my_function(outFile, foo, bar):
outFile.write(foo[bar])
Later I change its signature so the outFile positional-argument is a named one: 后来我更改了其签名,因此outFile位置参数是一个命名的:
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)? 在Vim(或其他Linux utils,例如sed)中,有没有简便的方法可以做到这一点? I know PyCharm etc can do this, but I'm not intending to jump ship just yet.
我知道PyCharm等可以做到这一点,但我还不打算跳船。
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. 阅读vimregex ,特别是捕获组。 Basically, whatever
(\\w*)
matches will be saved and named \\1
(then \\2
, \\3
, etc.) for us to use in the replacement later. 基本上,任何
(\\w*)
匹配项都将被保存并命名为\\1
(然后是\\2
, \\3
等),供我们稍后使用。
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: 另一种
find
(如先前的注释所述),也可以使用grep
打开包含所需功能的文件:
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. 此处的
c
标志是可选的,但我建议您进行此特殊替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.