In vim, how do you scroll a buffer so the cursor location is centered in the screen?

Solution 1:

This will center the current line

zz

Optionally you could set scrolloff to something large like 999 and the working line will always be in the center, except when you are towards the start or end of the file.

:set scrolloff=999

Solution 2:

There is a way to keep the cursor centered even near EOF.

scrolloff=999 works fine except near the end of the buffer where it does not center the cursor, I'm not aware of any fix that allows scrolloff to keep the cursor centered at the end of the buffer.

An alternative to scrolloff=999 is to remap your navigation commands to center on cursor. I do the following in my _vimrc/.vimrc:

" Avoids updating the screen before commands are completed
set lazyredraw

" Remap navigation commands to center view on cursor using zz
nnoremap <C-U> 11kzz
nnoremap <C-D> 11jzz
nnoremap j jzz
nnoremap k kzz
nnoremap # #zz
nnoremap * *zz
nnoremap n nzz
nnoremap N Nzz

This will keep the cursor centered vertically all the way to the end of the buffer :)