gpt4 book ai didi

macros - 如何在不添加 的情况下将以 结尾的字符串分配给 vimscript 变量?

转载 作者:行者123 更新时间:2023-12-01 10:51:05 24 4
gpt4 key购买 nike

我最近一直在玩 vim 宏(目前在 MacVim 中),有时我喜欢使用例如显式地将宏分配到寄存器中:let @a='(macro keystrokes)' .这通常工作正常,但我发现一个奇怪的行为,每当我分配一个以回车符/^M 结尾的字符串值时,vim 会在将它放入寄存器之前自动在末尾添加一个换行符/^J,这会影响执行宏!

示例:假设我录制了一个简单的宏,它进入插入模式,键入“嘿”,退出插入模式,然后按两次 Enter 进入 2 行。我通过输入 qaihey<Escape><Enter><Enter>q 将其记录到寄存器 @a 中,它将以下内容存储在@a中:

ihey^[^M^M

到目前为止一切顺利,通过键入 @a 执行宏做它应该做的。另一种非常好的方法可以让这个相同的宏进入寄存器@a 是通过将整个东西( ihey<Ctrl-V><Escape><Ctrl-V><Enter><Ctrl-V><Enter> )键入缓冲区然后用 "ay 猛拉它——最终结果是一样的。但奇怪的是——假设我只是想使用 let 将该字符串直接分配给@a。声明:

:let @a='ihey^[^M^M'

现在如果我输入 :reg看看它说的值(value)有一个额外的^J最后出于某种原因:

"8     ...
"9 ...
"a ihey^[^M^M^J
"b ...

有额外的^J导致它在我执行宏时多走一行,所以它实际上改变了行为。

有人知道为什么要添加这个额外的字符吗?任何人都知道我如何获得以 ^M 结尾的字符串值进入寄存器(或任何变量),而无需额外的 ^J被添加?

最佳答案

一些快速检查 vim 帮助文件说:

:let @{reg-name} = {expr1}            *:let-register* *:let-@*

...
If the result of {expr1} ends in a <CR> or <NL>, the
register will be linewise, otherwise it will be set to
characterwise.

换句话说,以回车符结尾的字符串将使 Vim 将其解释为行结尾


快速谷歌搜索 this来自 VimTips wiki:

Note however, that the above method using :let will not work as expected for any macros which you make ending in a < CR > or < NL > character (carriage return or newline). This is because, as documented in :help :let-@, Vim will treat the register as "linewise" under these conditions. The reason for this is to make registers set with :let act "the right way" when dealing with yanked/deleted text, but it can cause headaches when dealing with recorded macros. Possible workarounds include using the setreg() function or adding "no-op" commands to the end of the macro, such as a < ESC >. See the discussion on vim_dev about unexpected behavior of the :let command for details.

因此您有几个选择:使用 setreg() 或在使用 let 时向字符串添加某种无操作序列 (< ESC >)。

关于macros - 如何在不添加 <LF> 的情况下将以 <CR> 结尾的字符串分配给 vimscript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20171382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com