Vim 使用变量值的普通命令

Vim normal command using variable value

我需要做以下事情:

我首先使用 let temp=100 将值 100 设置为临时值。

然后我想出了以下我可以应用于一行的 ex 命令::execute "normal! ". temp. "^A" 这将需要临时并将当前行的数字增加 temp

不幸的是,当我在视觉上 select 一系列行然后点击 : 将命令应用于所有行时,这将不起作用 selected.

除了一定范围的线,我怎样才能达到同样的效果?

这是一个例子:

1
2
3
4
5

应该变成

101
102
103
104
105

然后我会将温度更新为 let temp=temp + 100 并重复下一个块等。

谢谢!

我刚刚找到了一个解决方法,如果没有人知道更好的方法的话。

我在当前行录制了一个宏b到运行execute "normal! " . temp . "^A"。然后记录了另一个宏 a,它将在视觉上 select 组中感兴趣的所有行和 运行 :'<,'>norm @b 这将在每一行上应用该操作,然后在结束之前宏@a,我也设置了let temp=temp+100.

直接回答你的问题,:help :execute 阻碍你的原因有两个:

  • :execute 不接受范围,
  • :execute 不是必需的开头。

以下命令在没有 :execute 的情况下完成工作:

:[range]normal! <C-r>=temp<CR><C-v><C-a><CR>

细分:

  • [range] 在视觉 selection 之后会是 '<,'>
  • :help :normal 在正常模式下执行给定的宏。
  • :help c_ctrl-r 在命令行中插入给定寄存器的内容。
  • :help "= 是表达式寄存器,其中 returns 一个求值表达式。
  • temp是要求值的表达式,所以<C-r>=temp<CR>插入变量temp.
  • 的内容
  • <C-v><C-a> 插入文字 ^A.
  • <CR> 执行命令。

但是要输入的内容很多,因此在这种情况下,简单的映射似乎更合适:

xnoremap <expr> <key> temp . '<C-a>'

细分:

  • :help :xnoremap 创建视觉模式映射。
  • :help <expr> 使其成为一个表达式映射,其中实际的 RHS 在运行时 .
  • 求值
  • <key> 是您要按的键。
  • temp . '<C-a>' 是你的表达式,它将 temp 的当前值与 <C-a> 连接起来以获得 100<C-a>200<C-a> 等..

用法:

  1. 设置temp为想要的值:

    :let temp = 100
    
  2. Select 一些行:

    v<motion>
    
  3. 增加每行的第一个数字:

    <key>
    
  4. 改变temp的值:

    :let temp += 100
    
  5. 移动到下一个块和select一些行:

    <motion>
    v<motion>
    
  6. 增加每行的第一个数字:

    <key>
    

然而,手动方式是这样的:

v<motion>    " visually select the desired lines
100<C-a>     " increment the first number on each line by 100

然后:

<motion>
v<motion>
200<C-a>     " increment the first number on each line by 200

等等……所以我不确定在这里引入变量:normal等有什么好处。

我认为我们可以使用全局命令来完成这项工作,它接受范围。

:'<,'>g/./execute "normal! ". temp. "^A"