为什么 vim 在函数内部表现不同?

Why does vim behave differently inside a function?

我正在尝试让以下内容在函数内部工作。

let pat = 'set'
:execute "normal /" . pat . "\<CR>"

然而,当我运行它是这样的(字面上复制粘贴到vim)

:function! BSearch(pat)
   execute "normal /" . a:pat . "\<CR>"
endfunction
:call BSearch('tag')

它搜索标签,但不做任何突出显示。 "set" 仍然突出显示,如果我按 n 它会转到 "set",而不是 "tag"。

我束手无策 -- 似乎函数内部的 execute 行为不同。

如果您知道解决方法,请提供帮助。

很好的解决方法

我能够写出我的完整命令并让它按预期工作

command! -nargs=1 Ack2 execute "Ack " . <q-args> | execute "/".<q-args>

ack.vim 扩展没有突出显示我搜索的字词。由于我已将我的搜索配置为使用 perl 正则表达式(并且 ag 使用 perl 正则表达式,这是我用作搜索器的),这些术语现在不仅突出显示,我还可以使用 n 就像我进行任何正常搜索一样(除了它现在显然在我的整个项目中)。

非常感谢!

您不需要 normal 即可 execute 进行 / 搜索。对于您的情况,这应该足够了:

function! BSearch(pat)
  execute "/" . a:pat
endfunction

看看这个:

:h function-search-undo

全文如下:

The last used search pattern and the redo command "."
will not be changed by the function.  This also
implies that the effect of |:nohlsearch| is undone
when the function returns.

也许您可以将搜索移动到用户命令中,例如:

command! -nargs=1 BSearch execute "/".<q-args>