简体   繁体   English

如何在vim脚本中替换光标下的单词?

[英]How do I substitute the word under cursor in vim script?

After getting the current word with expand("<cWORD>") and processing the result string, I'm trying to replace the current word with it. 在使用expand("<cWORD>")获取当前单词并处理结果字符串后,我正在尝试用它替换当前单词。

How can I do this? 我怎样才能做到这一点?

EDIT Source added. 编辑来源添加。 I wrote it in python. 我用python写的。

cur_word = vim.eval('expand("<cWORD>")')
parts = cur_word.split('.')
if parts:
    obj, accesses = parts[0], parts[1:]
    result = obj + ''.join("['%s']"%a for a in accesses)
    # how do I replace the current word with result?

Edit 编辑

It looks like you wanted this: 看起来你想要这个:

viW
:s/\%V\.\(\w\+\)\%V/\="['" . submatch(1) . "']"/g

Eg, for the following text, curosr on the second line: 例如,对于以下文本,curosr在第二行:

x = a.get.property;
x = a.git.another.property;   # cursor on the first letter 'e'

The result will be 结果将是

x = a.get.property;
x = a['git']['another']['property'];

You probably wanted you 你可能想要你

  1. yank one word , then 然后扬了一个字
  2. move the cursor (which you don't mention) 移动光标 (你没有提到)
  3. _replace the word under cursor by previously yanked word? _用以前被扯过的单词替换光标下的单词?

That would be 那就是

y i W (move cursor around) v i W p ÝI W(移动光标周围)V I 值WP

So eg: 例如:

 the lazy cow mooned over the racy hump
 cursor here:   ----> +        

Now, doing y i W (yank inner WORD), F a (back to:) 现在,进行Y I W(抽出内WORD),F (回:)

 the lazy cow mooned over the racy hump
  --> +        

Now, v i W p replaces current WORD: 现在, v i W p替换当前的WORD:

 the over cow mooned over the racy hump
    --> +

In the python interface for Vim, you can execute normal mode command, in your case, 在Vim的python界面中,您可以执行普通模式命令,在您的情况下,

  vim.command("normal BcW%s" % result)

will do the trick. 会做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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