Author: @purpleP
Source: Turn off highlight on CursorMoved and InsertEnter without remapping (doesn't break search operator pending mode)
noremap <expr> <Plug>(StopHL) execute('nohlsearch')[-1]
noremap! <expr> <Plug>(StopHL) execute('nohlsearch')[-1]
fu! HlSearch()
let s:pos = match(getline('.'), @/, col('.') - 1) + 1
if s:pos != col('.')
call StopHL()
endif
endfu
fu! StopHL()
if !v:hlsearch || mode() isnot 'n'
return
else
sil call feedkeys("\<Plug>(StopHL)", 'm')
endif
endfu
augroup SearchHighlight
au!
au CursorMoved * call HlSearch()
au InsertEnter * call StopHL()
augroup end
For my init.lua config, I need this in Lua.
PS: I'm a newbie. Tried this for the first time. Please add some fixes to it.
vim.api.nvim_set_keymap('n', '<expr> <Plug>(StopHL)', "execute('nohlsearch')[-1]", { noremap = true })
vim.api.nvim_set_keymap('i', '<expr> <Plug>(StopHL)', "execute('nohlsearch')[-1]", { noremap = true })
function HlSearch()
local pos = vim.fn.match(vim.fn.getline('.'), @/, vim.fn.col('.') - 1) + 1
if pos ~= vim.fn.col('.') then
StopHL()
end
end
function StopHL()
if not vim.v.hlsearch or vim.fn.mode() ~= 'n' then
return
else
vim.cmd[[silent! call feedkeys("\<Plug>(StopHL)", 'm')]]
end
end
vim.cmd('augroup SearchHighlight')
vim.cmd('autocmd!')
vim.cmd('autocmd CursorMoved * lua HlSearch()')
vim.cmd('autocmd InsertEnter * lua StopHL()')
vim.cmd('augroup end')
Error messages:
Error detected while processing /home/killerbee/.config/nvim/init.lua:
E5112: Error while creating lua chunk: /home/killerbee/.config/nvim/init.lua:7: unexpected symbol near '@'
@/
is Vim syntax for getting a register value (there are also functions likegetreg()
/getreginfo()
)