我之前使用 NetBeans,非常喜欢它的一个功能:当你把光标放在一个变量名上时,所有该变量的出现位置都会被高亮。这对于快速查找变量的所有出现位置非常有用。是否可能将此行为添加到 Vim 中?
:set hlsearch
*
或#
查找光标下单词的出现,这将使您达到部分想要的目标。但是,我认为语法感知变量高亮超出了VIM的范围。nmap <leader>*
(双反引号) - Vladimir Zhdanov:autocmd CursorMoved * exe exists("HlUnderCursor")?HlUnderCursor?printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\')):'match none':""
要启用高亮显示,可以使用以下方法:
:let HlUnderCursor=1
并使用以下代码禁用:
:let HlUnderCursor=0
可以很容易地为启用/禁用高亮定义快捷键:
:nnoremap <silent> <F3> :exe "let HlUnderCursor=exists(\"HlUnderCursor\")?HlUnderCursor*-1+1:1"<CR>
:unlet HlUnderCursor
如果您不想在光标停留在语言单词(如if
,#define
等)上时突出显示这些单词,您可以根据@too_much_php的回答将此功能放入您的.vimrc
中:
let g:no_highlight_group_for_current_word=["Statement", "Comment", "Type", "PreProc"]
function s:HighlightWordUnderCursor()
let l:syntaxgroup = synIDattr(synIDtrans(synID(line("."), stridx(getline("."), expand('<cword>')) + 1, 1)), "name")
if (index(g:no_highlight_group_for_current_word, l:syntaxgroup) == -1)
exe printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
else
exe 'match IncSearch /\V\<\>/'
endif
endfunction
autocmd CursorMoved * call s:HighlightWordUnderCursor()
map <F2> :set hlsearch!<CR> * #
这肯定不是完美的。'* #' 跳动得有点多...
这个变量是为了速度优化而设计的(使用CursorHold而不是CursorMoved),并且与hlsearch
兼容。当前搜索词的高亮显示不会被打断。
" autosave delay, cursorhold trigger, default: 4000ms
setl updatetime=300
" highlight the word under cursor (CursorMoved is inperformant)
highlight WordUnderCursor cterm=underline gui=underline
autocmd CursorHold * call HighlightCursorWord()
function! HighlightCursorWord()
" if hlsearch is active, don't overwrite it!
let search = getreg('/')
let cword = expand('<cword>')
if match(cword, search) == -1
exe printf('match WordUnderCursor /\V\<%s\>/', escape(cword, '/\'))
endif
endfunction
与被接受的答案类似,但这种方法允许您在将光标悬停在单词上后设置延迟时间,然后突出显示。 1000
的单位是毫秒,意味着它将在 1 秒后突出显示。
set updatetime=1000
autocmd CursorHold * exe
\ printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
更多信息请参见:h CursorHold
。
vim-illuminate 对我很有用。
match-up 对我很有用。
vim match-up: 连同 modern matchit 和 matchparen,更好的 % 导航和高亮匹配单词
特性
- 跳转到匹配单词
- 跳转到开启和结束单词
- 在括号内跳转(z%)
- 完整的文本对象集合
- 突出显示 (), [], 和 {}
- 突出显示全部匹配单词
- 显示屏幕外匹配单词
- 显示当前位置(面包屑导航)
- (neovim) tree-sitter 集成
:autocmd CursorMoved * silent! exe printf('match IncSearch /\<%s\>/', expand('<cword>'))
。 - UncleZeiv