如何自动突出显示vim中的当前单词?

时间:2014-08-10 09:31:00

标签: vim highlight

例如,我们的文字是:

hello world
abcd hello world
hello world

在eclipse中,当光标位于某个单词时,单词hello在当前文件中自动高亮显示。当您在正常模式下键入ww时,光标位于当前文件中突出显示的其他字worldhello会自动取消突出显示。此功能对用户来说非常方便。

vim是否可以使用某些插件执行此操作?

4 个答案:

答案 0 :(得分:6)

这样的东西?

set updatetime=10

function! HighlightWordUnderCursor()
    if getline(".")[col(".")-1] !~# '[[:punct:][:blank:]]' 
        exec 'match' 'Search' '/\V\<'.expand('<cword>').'\>/' 
    else 
        match none 
    endif
endfunction

autocmd! CursorHold,CursorHoldI * call HighlightWordUnderCursor()

这不会破坏搜索寄存器,但会使用与通常使用的相同的突出显示。 (如果要为该突出显示组添加不同的突出显示颜色Search。)需要较短的更新时间,以便相当频繁地触发CursorHold事件。如果光标位于标点符号或空格上方,它也不会突出显示任何内容。

iskeyword设置确定在使用expand('<cword>')时被视为单词的一部分。

答案 1 :(得分:3)

是的,有一个vim插件可以自动突出显示单词的出现。此one专门针对 .php 文件中的$variables->properties实施。

DEMO: enter image description here

here是同一个,但适用于 Perl 文件。

DEMO:

enter image description here

您可以为您的目的修改它。

希望这有帮助。

答案 2 :(得分:3)

vim.wikia.com上有一个脚本可以完全执行此操作。它等待,直到您停止移动光标,然后突出显示当前单词的所有实例。然后,您可以像使用搜索结果一样,使用nN在它们之间跳转。

我正在复制它,以防链接出现故障:

" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
    let @/ = ''
    if exists('#auto_highlight')
        au! auto_highlight
        augroup! auto_highlight
        setl updatetime=4000
        echo 'Highlight current word: off'
        return 0
    else
        augroup auto_highlight
            au!
            au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
        augroup end
        setl updatetime=500
        echo 'Highlight current word: ON'
        return 1
    endif
endfunction

如该页面上的评论中所述,如果您始终需要此功能,则可以在定义后从vimrc调用该功能。这样您可以使用z/(或指定的任何快捷方式)稍后再将其关闭。

答案 3 :(得分:0)

改进@FDinoff的惊人答案,使用自定义突出显示-黑色BG和下划线,并在quickfix列表,逃犯文件类型和diff上禁用:

function! HighlightWordUnderCursor()
    let disabled_ft = ["qf", "fugitive", "nerdtree", "gundo", "diff", "fzf", "floaterm"]
    if &diff || &buftype == "terminal" || index(disabled_ft, &filetype) >= 0
        return
    endif
    if getline(".")[col(".")-1] !~# '[[:punct:][:blank:]]'
        hi MatchWord cterm=undercurl gui=undercurl guibg=#3b404a
        exec 'match' 'MatchWord' '/\V\<'.expand('<cword>').'\>/'
    else
        match none
    endif
endfunction

augroup MatchWord
  autocmd!
  autocmd! CursorHold,CursorHoldI * call HighlightWordUnderCursor()
augroup END
相关问题