I want to have the very first search result centered on the screen. I know about :nnoremap n nzz mapping, but it only works for centering next matches, not the first.

I thought that maybe I could use some AutoCmd, but I haven't found an appropriate event.


You can use the following mapping:

cnoremap <expr> <CR> getcmdtype() == '/' ? '<CR>zz' : '<CR>'

Which can be explained like this:

  • cnoremap Create a mapping in the command line mode
  • <expr> The mapping will evaluate an expression (allowing to use conditions)
  • <CR> The key to remap (Enter)
  • getcmdtype() Return a character indicating which command line mode is used
  • == '/' Did getcmdtype() returned a / which means we are in search mode?
  • '<CR>zz' If we are in search mode execute zz after pressing <CR>
  • '<CR>' Else execute only <CR>

Related help topics:

EDIT Note that it would be interesting to create a mapping which would work with both forward and backward search i.e. when getcmdtype() return / or ?. Here is the mapping to do that:

cnoremap <expr> <CR> (getcmdtype() == '?' \|\| getcmdtype() == '/') ? '<CR>zz' : '<CR>'

Note the escaping of the | characters: if they are not escapes vim will understand cnoremap <expr> <CR> (getcmdtype() == '?' as the first command to execute followed by getcmdtype() == '/') ? '<CR>zz' : '<CR>' which doesn't make sense and create an error.

EDIT 2 @Antony suggested a more readable solution, thanks to him:

cnoremap <expr> <CR> getcmdtype() =~ '[/?]' ? '<CR>zz' : '<CR>'
| improve this answer | |
  • 3
    Maybe getcmdtype() =~ '[?/]' would be a little easier. – Antony Dec 28 '16 at 13:49
  • @Antony Indeed that's much better, I edited my answer. Thank you! – statox Dec 28 '16 at 13:53
  • 2
    Awesome! Just what I need, thank you! And thanks for detailed explanations, they are very helpful for learning vimscript. – Jan Warchoł Dec 28 '16 at 14:00
  • Recently had a problem with this using / as a motion: e.g. c/search will change from my current position to the next location matching search but, because of the cnoremap, insert the text zz. Thoughts on a workaround, or should I remove the mapping? – D. Ben Knoble Feb 17 '18 at 15:56
  • 1
    @DavidBenKnoble indeed that's a problem I didn't think about. I will try to find a workaround and edit my answer if I find one. – statox Feb 19 '18 at 10:52

Statox's answer is definitely the best so far, but as an alternative, I've just found out about Vim-slash, a plugin aiming to "enhance the in-buffer search experience."

And from it's readme:


zz after search

Places the current match at the center of the window.

noremap <plug>(slash-after) zz

Just tried it out and it is working smoothly in both directions (/ and ?).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.