Keep cursor line vertically centered in vim

Viewed 1321

I want the cursor to be constantly in the middle of my screen in vim.
I am not very comfortable looking constantly down to the end of the file.
What commands in the config will you advise to solve the problem?

3 Answers
:set scrolloff=999

If you set scrollof 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).

Besides :set so=999, I also tried these 2 commands to map the normal k and j to "scroll up/down one line and place that line at the center of the window":

:nnoremap k kzz
:nnoremap j jzz

A little different from setting so, when moving cursor down to the end of the file, it still remains at the center. However it doesn't affect the behavior of shift+g.

From here, this is how to extend this functionality to searching and insert mode. It saves the current cursor position, centers the view, and then restores the cursor position.

autocmd CursorMoved,CursorMovedI * call Center_cursor()

function! Center_cursor()
    let pos = getpos(".")
    normal! zz
    call setpos(".", pos)
endfunction
Related