fstab
fstab

Reputation: 5029

vim autocmd hook after performing a search in the text?

I had a look at the list of events autocmd can handle, but I could not find one about search queries.

What I would like to do is to add some custom behavior after each text search is performed. I was able to remap the * command with this command:

map * *<F11>

In this case I mapped <F11> to a :call My_function() which will do something with the search pattern contained in @/.

But I still need to add my custom behavior to the / command, which is more complicated, as before it's completed it's getting the input search pattern.

Do you have any hint on how to proceed? Can I use autocmd? Or maybe is there a map trick?

Upvotes: 0

Views: 577

Answers (1)

yolenoyer
yolenoyer

Reputation: 9445

An (bad) way to do it would be to remap the return key (and the esc key) when / is pressed, something like that:

function! MyCustomBehaviour()
    echo "Oui oui"
endf

function! UnmapSearch()
    cunmap <cr>
    cunmap <esc>
endf

function! MapSearch()
    cnoremap <cr> <cr>:call UnmapSearch()<bar>call MyCustomBehaviour()<cr>
    cnoremap <silent> <esc> <c-c>:call UnmapSearch()<cr>
endf

noremap / :<c-u>call MapSearch()<cr>/

It's a bad way because it's quite buggy : if you press Ctrl-C while editing the search, it won't unmap <cr> and <esc>, then the next time you will enter : (command-line) mode, the mappings will still be active... That's a problem that can't be solved (<c-c> can't be remapped).

It's also a bad way because remapping directly the / key this way, IMO, is not a good practice.

But... This was the only solution I found some times ago to half-solve this problem.

Another workaround (the one I finally choose) can be written in one line :

cnoremap <c-cr> <cr>:call MyCustomBehaviour()<cr>

Upvotes: 1

Related Questions