Roy Fulbright
Roy Fulbright

Reputation: 67

How to Override/Redefine Vim Search Command

I need to override/redefine Vim's search operator "/" to also execute "zszH" after the search to center the search results on the screen horizontally.

For example, I want to enter: /varchar and have the search results (i.e., the string "varchar") displayed in the middle of the scren horizontally.

I can do that now by manually entering "zszH" after each search, but that is very tedious.

Upvotes: 1

Views: 245

Answers (1)

Peter Rincker
Peter Rincker

Reputation: 45097

You can use the CmdlineLeave event. Add the following to your vimrc

augroup RecenterSearch
  autocmd!
  autocmd CmdlineLeave [/?] call feedkeys('zszH', 't')
augroup END

Note: CmdlineLeave requires Vim 8.1

Or you can map <cr>:

cnoremap <expr> <cr> "\<cr>" . (getcmdtype() =~ '[?/]' ? "zszH" : '')

Some mappings which might be helpful:

nnoremap n nzszH
nnoremap N NzszH

If you do not have a new enough version on Vim then maybe look into 'wrap' or create a mapping

For more help see:

:h CmdlineLeave
:h :autocmd
:h feedkeys()
:h expression-mapping
:h getcmdtype()

Upvotes: 2

Related Questions