sahlte / timed-highlight.nvim

Turn off highlighted text after set time period in Neovim
MIT License
12 stars 1 forks source link

Errors when pressing n or N on a search that can't be found #2

Open jps327 opened 21 hours ago

jps327 commented 21 hours ago

Thanks for putting together this plugin! It's exactly what I'm looking for to clear search highlights on their own.

It works smoothly but I found a bug.

Steps to reproduce

  1. Make a search query that does not exist in the file
  2. You will get a normal "Pattern not found" error which is expected.
  3. Hit "n" or "N" to find the next (or previous) match.
  4. A much bigger error now shows up:
E5108: Error executing lua: vim/_editor.lua:0: nvim_exec2(): Vim(normal):E486: Pattern not found: woah
stack traceback:
        [C]: in function 'nvim_exec2'
        vim/_editor.lua: in function 'cmd'
        ...vim/lazy/timed-highlight.nvim/plugin/timed-highlight.lua:4: in function 'searchAndOpenFold'
        ...vim/lazy/timed-highlight.nvim/plugin/timed-highlight.lua:13: in function <...vim/lazy/timed-highlight.nvim/plugin/timed-highlight.lua:13>

Expected behavior When pressing n or N, the error message should just continue being the normal error message ("Pattern not found") rather than a stack traceback.

My setup I am using Lazy to install plugins. This is my configuration as per the Readme:

local function timed_highlight_config()
    require("timed-highlight").setup({
        highlight_timeout_ms = 3000
    })
end

return {
  'sahlte/timed-highlight.nvim',
  config=timed_highlight_config,
}

Output from nvim -v:

NVIM v0.10.2
Build type: Release
LuaJIT 2.1.1727870382

Let me know if you need anything else to debug & fix this! Thanks again for a helpful plugin.

jps327 commented 16 hours ago

A fix for this is to update the searchAndOpenFold function in timed-highlight.lua to the following:

local function searchAndOpenFold(key)
    -- Get the current search term
    local search_term = vim.fn.getreg('/')

    -- Use pcall to safely execute the command and catch any errors
    local success, _ = pcall(function()
        vim.cmd('normal! ' .. key)
    end)

    if not success then
        vim.api.nvim_err_writeln('E486: Pattern not found: ' .. search_term)
    end

    if string.find(vim.o.foldopen, "search") and vim.fn.foldclosed('.') ~= -1 then
        vim.cmd('normal! zv')
    end

    require('timed-highlight').turn_off_highlight_after_expiration()
end

Basically, to use pcall to wrap vim.cmd to avoid printing the entire stack trace, and then we manually write the error instead to nvim.

Let me know if you want me to submit a PR or if its easier for you to just add this fix.