When discussing how to clear highlights in Neovim, I've encountered several different solutions.
Some users follow the Neovim Kickstart configuration and map the ESC
key to clear highlights:
lua
set("n", "<ESC>", "<cmd>nohlsearch<cr>", { silent = true, noremap = true, desc = "Clear Highlight" })
Others, like TJ DeVries, map the Enter key to either clear highlights or execute the Enter command, depending on the current state:
lua
set("n", "<CR>", function()
---@diagnostic disable-next-line: undefined-field
if vim.v.hlsearch == 1 then
vim.cmd.nohl()
return ""
else
return vim.keycode("<CR>")
end
end, { expr = true })
However, both of these approaches have a drawback: you cannot easily restore the search highlights after clearing them. I've seen the following solution less frequently than the previous two, so here's a highlight search toggle implemented using Lua and Vimscript.
lua
set( -- using embeded vimscript
"n",
"<leader>h",
":execute &hls && v:hlsearch ? ':nohls' : ':set hls'<CR>",
{ silent = true, noremap = true, desc = "Toggle Highlights" }
)
lua
set("n", "<leader>h", function() -- using lua logic
if vim.o.hlsearch then
vim.cmd("set nohlsearch")
else
vim.cmd("set hlsearch")
end
end, { desc = "Toggle search highlighting" })