2

There's been a few cases where it would be convenient to hook into the search and replace behavior for certain things. For example, I have the following mapping in my vimrc:

nnoremap n nzzzv

Which centers the screen every time you advance to the next match. This works well but does not apply when doing a %s//c command. Is there a way to hook into when the user selects one of the confirmation options y/n/q/q/l/etc. so that you can trigger commands?

3 Answers3

2

Unfortunately not. The usual way to hook into this would be through an

:autocmd CursorMoved * ...

but that event isn't fired while in the :substitute///c query loop. Think of that as a special kind of mode with many restrictions; it would be very difficult to allow custom functionality in there while maintaining the correct search state.

You would have to reimplement the :substitute functionality yourself. Maybe you can use a :help sub-replace-expression with the query in there; I haven't yet tried whether user interaction is possible then.

Ingo Karkat
  • 23,523
2

A workaround for your particular use case of centering the currently substituted line is to

:set scrolloff=999

before the :substitute command. That has the same effect of centering the current line as your zz command.

Ingo Karkat
  • 23,523
1

Based on Ingo Karkat's suggestion to use the scrolloff option I ended up going with this:

command! -nargs=1 CC set scrolloff=999|exec <f-args>|set scrolloff=0

So now you can just run "CC %s//c" and it will center the cursor temporarily during the command. It's tempting to find an abbreviation or something for this but I couldn't think of anything that would work reliably.