:)我喜欢在Vim
中使用搜索突出显示。但过了一段时间,它就很糟糕了,我必须手动删除它(映射已定义)。所以我写了一个函数,在一段时间后删除突出显示,绑定到自动命令。因为如果你只是关注搜索结果,时间可能会成为一个问题,我将此函数绑定到事件并引入一个计数器直到零。如果我在结果之间跳转或决定稍后跳转到搜索结果元素,这可以正常工作,并且所有结果都会再次突出显示(手动测试)。CursorMoved
我插入了很多echo消息来跟踪行为。它绝对可以正常工作,直到计数器“过期”(变为零)。然后应该删除突出显示和计数器。两者都按照输出所述工作echo,但不是视觉上的。在取消设置后检查并echom v:hlsearch批准突出显示,它已起作用,但随后立即再次突出显示(延迟不可见)。因此循环再次开始,导致计数器过期,但检测到“新”突出显示。调用与函数中相同的命令可以完美地工作。那么会发生什么呢?
这是我的代码.vimrc:
" Function used if something is highlighted in the document.
" Is meant to be called several times by a autocommand.
" Sets a counter on the first call.
" Afterwards it decrease the counter each time get called, until zero.
" When the highlighting will be removed and the counter also.
" By this the time until remove highlighting depends on the frequency of
" function calls and that depend on the bounded auto command.
"
function! s:remove_highlight()
echom 'Call'
" Only makes sense when something is highlighted.
if v:hlsearch
echom 'In'
" First call, so set the start time
if !exists('g:highlight_counter')
echom 'first call after new highlighting'
let g:highlight_counter = 4
else
" Decrease highlight counter.
let g:highlight_counter = g:highlight_counter - 1
echom 'check ' . g:highlight_counter
" Check if the counter is expired.
if g:highlight_counter <= 0
" Unset counter and remove highlight.
unlet g:highlight_counter
execute 'nohlsearch'
echom 'done? ' . !v:hlsearch
else
endif
endif
echom 'out'
endif
echom 'End'
endfunction
Run Code Online (Sandbox Code Playgroud)
有什么想法这里会发生什么吗?我不知道...
从函数内部试试这个:
call feedkeys( ":nohlsearch\<CR>" )
Run Code Online (Sandbox Code Playgroud)
注意:请注意双引号,它们是转义序列所必需的。即使在函数内部,这对我也适用(使用 vim 8 测试)。我不是 vimscript 专家,但这里可能发生的情况是,它将键添加到队列中,并仅在函数完成后才处理它们。