5

When I press n or N to find the next match, it often happens that the window is redrawn such that the next match is displayed on the bottom-most or top-most line on the screen, and I have to scroll a few lines further to see enough context to know if I actually want to edit that line.

Is there a way to force the matches to be displayed such that a few surrounding lines are always visible?

3 Answers 3

7

Check if set scrolloff=5 is what you need.

    Minimal number of screen lines to keep above and below the cursor.
    This will make some context visible around where you are working.  If
    you set it to a very large value (999) the cursor line will always be
    in the middle of the window (except at the start or end of the file or
    when long lines wrap).
4

Using scrolloff is the right answer.

Although when searching I usually prefer doing zz (scroll the current line to the middle)

And when doing confirmed substitution I usually prefer doing Ctrl e (scrolling one line)

2

The following mappings were adapted from Drew Neil's Practical Vim:

:nnoremap <Leader>n nzz
:nnoremap <Leader>N Nzz

They will make n go to the next match as usual and <Leader>n will go to the next match, centering the screen. You could also drop <Leader> from the mapping to change the defaults and have (next) searches also centered.

4
  • 1
    You probably want nnoremap.
    – D. Ben Knoble
    Commented Feb 4 at 16:47
  • I actually hesitated there. I'd probably also want it centered in visual mode, not so much in operator-pending mode. The book says :noremap and in the end I decided to quote verbatim.
    – Friedrich
    Commented Feb 4 at 17:54
  • 1
    I recall having problems with even the normal-mode mapping (when I had it on n/N) 6 years ago (something like cgn would insert zz, which I can't explain unless gn uses some path that executes mappings on n). Anyway
    – D. Ben Knoble
    Commented Feb 4 at 19:59
  • The problems you mention may have been the motivation for the <Leader> mappings. I couldn't reproduce them but Vim has improved in those 6 years.
    – Friedrich
    Commented Feb 5 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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