vim中如何在单词两侧重复添加文本?
我在 Python 脚本中有一堆局部变量引用,我想从字典中提取它们。因此,我需要将 foo
、bar
等更改为 env['foo']
、env['bar' ]
等等。我是否需要编写正则表达式并匹配每个要转换的变量名称,或者是否有更直接的方法可以使用 .
命令重复?
I have a bunch of local variable references in a Python script that I want to pull from a dictionary instead. So, I need to essentially change foo
, bar
, and others into env['foo']
, env['bar']
and so on. Do I need to write a regular expression and match each variable name to transform, or is there a more direct approach that I could just repeat with the .
command?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用宏:一次性键入这些命令(留有空格以插入注释),
然后,当您输入下一个单词时,只需按
@a
即可重播宏(甚至可以按 < code>@@ 之后重复上次重播)。You can use a macro: type these commands in one go (with spacing just to insert comments)
then, when you're on the next word, just hit
@a
to replay the macro (or even@@
to repeat the last replay after that).有一种更简单的方法 - 您可以使用正则表达式搜索和替换。通过键入冒号进入 cmdline 模式,然后运行以下命令:
将
foo
、bar
和baz
替换为您的实际变量名称。您可以根据需要添加任意数量的其他变量,只需确保使用反斜杠转义 OR 管道即可。希望有帮助。There's an easier way - you can use a regex search and replace. Go into cmdline mode by typing a colon and then run this command:
Replacing
foo
,bar
, andbaz
with whatever your actual variable names are. You can add as many additional variables as you'd like, just be sure to escape your OR pipes with a backslash. Hope that helps.您可以编写一个可以很好地完成此操作的函数,将其添加到您的 .vimrc 文件中:
这将包围当前光标下出现的每个单词。
如果您想指定每个实例之前和之后发生的事情,您可以使用以下内容:
如果您只想确认变量的每个实例,您可以使用以下内容:
you could write a function that would do this pretty well, add this to your .vimrc file:
This will surround every occurance of the word currently under the cursor.
If you wanted to specify what went before and after each instance you could use this:
If you only want to confirm each instance of the variable you could use this:
我想出了一种方法来完成我需要的事情。使用
q{0-9a-zA-Z"}
将击键记录到缓冲区中。将光标定位在变量名称的开头,然后cw
并输入 < code>env['']。接下来将光标向后移动一个空格到最后一个引号,并使用P
粘贴从cw
命令填充的缓冲区。 ,为每个变量重复使用@{0-9a-z".=*}
记录。I figured out one way to do what I need. Use
q{0-9a-zA-Z"}
to record key strokes into a buffer. Position the cursor at the begging of the variable name, thencw
and typeenv['']
. Next move the cursor back one space to the last quote and paste the buffer filled from thecw
command withP
. Finally, reuse the recording with@{0-9a-z".=*}
for each variable.