VonHeikemen / searchbox.nvim

Start your search from a more comfortable place, say the upper right corner?

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Feature request]: add hook to define mappings

younger-1 opened this issue · comments

I notice that your another awesome neovim plugin fine-cmdline provide a hook set_keymaps to makes non-recursive mappings in insert mode. It is very useful to customize the searchbox behaviour. I simulate what I want below:

require('searchbox').setup({
  hooks = {
    set_keymaps = function(imap)
       imap('<C-a>', require('searchbox').match_all())
       imap('<C-r>', require('searchbox').incsearch({reverse = true}))
       imap('<C-x>', require('searchbox').incsearch({exact = true))
    end
  }
})

Say I use global mapping <C-f> to trigger SearchBoxIncSearch. In the searchbox's input I can use local mapping <C-a> to trigger SearchBoxMatchAll or use <C-r> to search backward or use <C-x> to search an exact match.

Basiclly it allow users to define only one global mappings to trigger all SearchBox's functions.

I kind of regret adding that hook in fine-cmdline, because all the bugs and problems that hook solves they have been fixed in neovim 0.7.

You can still make custom keymaps. You'll need to use the after_mount hook.

Now, the keymaps you want... those are tricky. In some systems closing an input can be a little bit slow, so you might need to add a little delay between closing the current input and making the command to open the new one.

Here is the "safest" way to do what you want.

require('searchbox').setup({
  hooks = {
    after_mount = function(input)
      local map = function(lhs, rhs)
        vim.api.nvim_buf_set_keymap(input.bufnr, 'i', lhs, rhs, {noremap = false})
      end

      local mode = "<Esc><cmd>sleep 3m<CR><cmd>SearchBox%s<CR>"

      map('<C-a>', mode:format('MatchAll'))
      map('<C-r>', mode:format('IncSearch reverse=true'))
      map('<C-x>', mode:format('IncSearch exact=true'))
    end
  }
})

If you have neovim 0.7 you could use lua functions with vim.keymap.set.

require('searchbox').setup({
  hooks = {
    after_mount = function(input)
      local opts = {buffer = input.bufnr}
      local mode = function(m, args)
        local delay = 3
        input.input_props.on_close()
        vim.defer_fn(function() require('searchbox')[m](args) end, delay)
      end

      vim.keymap.set('i', '<C-a>', function() mode('match_all', {}) end, opts)
      vim.keymap.set('i', '<C-r>', function() mode('incsearch', {reverse = true}) end, opts)
      vim.keymap.set('i', '<C-x>', function() mode('incsearch', {exact = true}) end, opts)
    end
  }
})

Again, play with the delay. You can delete it or change the number of miliseconds.

Thank you very much and the mappings functions well.
I am going to close this, still but I also want to reverse the search text after triggering mapping inside search box