5

I would like Vim to place my cursor in the middle of screen after search. I have achieved for *, #, n and N commands with the following lines in .vimrc

nmap * *zz
nmap # #zz
nmap n nzz
nmap N Nzz

My question is: how to map / and ? the same way? I.e. I would like to position cursor after some text has been found using

/some-text-to-find-forward
?some-text-to-find-backward
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
user2146414
  • 840
  • 11
  • 29
  • 1
    The [vim-oblique plugin](https://github.com/junegunn/vim-oblique) does that. But it has a lot of dependencies and sometimes creates lags. – statox Oct 06 '16 at 14:22

3 Answers3

4

Edit: Threw away my initial answer as it was too much of a kludge. Here's a much better solution.

function! CenterSearch()
  let cmdtype = getcmdtype()
  if cmdtype == '/' || cmdtype == '?'
    return "\<enter>zz"
  endif
  return "\<enter>"
endfunction

cnoremap <silent> <expr> <enter> CenterSearch()

The way this works is to remap Enter in command-line-mode to a custom expression.

The function performs the current search followed by zz if the command-line is currently in a search. Otherwise it just executes whatever command was being done.

Randy Morris
  • 39,631
  • 8
  • 69
  • 76
1

It's not very pretty, but

:nnoremap / :execute "normal! /\<lt>cr>zz"<c-left><right>

will get the job done. (Puts an :execute "normal! /" command on the commandline, then adds a <cr>zz to the end to it so that you automatically zz when you issue the command. The final <c-left><right> just steps into the search pattern at the right spot

Wolfie
  • 143
  • 6
  • Thank you! You are right: it's "not verry pretty" but works:) I've tried and put it into my vimrc but now I want to try Randy's solution that seems to be a little bit cleaner;) – user2146414 Oct 07 '16 at 21:13
  • His is the better version (cleaner and without as much a chance to mess up with a stray backspace...) and I'm very confused as to why I didn't think of it myself. Kudos to him. – Wolfie Oct 07 '16 at 21:30
1

Solution from Randy Morris but as a oneliner:

cnoremap <silent><expr> <enter> index(['/', '?'], getcmdtype()) >= 0 ? '<enter>zz' : '<enter>'
aleks
  • 21
  • 2