Since there are no VisualEnter and VisualLeave events, I am trying to make a function that will activate on every cursor movement in visual mode, i.e. it will automatically highlight all the matches of the current visual selection.
The mapping from Automatically highlight all occurrences of the selected text in visual mode:
xnoremap <silent> <cr> "*y:silent! let searchTerm = '\V'.substitute(escape(@*, '\/'), "\n", '\\n', "g") <bar> let @/ = searchTerm <bar> echo '/'.@/ <bar> call histadd("search", searchTerm) <bar> set hls<cr>
works perfectly for me but I am failing to implement it into function. This is what I tried:
function! HighlightVisual(mode)
if mode()=~#"^[vV\<C-v>]"
call feedkeys('"*y')
let searchTerm = '\V'.substitute(escape(@*, '\/'), "\n", '\\n', "g")
let @/ = searchTerm
echo '/'.@/
call histadd("search", searchTerm)
set hls
endif
endfunction
autocmd CursorMoved * call HighlightVisual(mode())
However, it is not working. What am I doing wrong? Moreover, does anybody think there is a better way to search for matches on every cursor movement in visual mode?
@/
register is restored at the end of a function call. See:help function-search-undo
for more details. As a workaround, you canreturn searchTerm
from your function and use anautocmd CursorMoved * let @/ = HighlightVisual(mode())
instead (though you might need to handle the case where you're not in Visual mode to prevent clobbering that register in that case.)