'Keep cursor line vertically centered in vim

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?

vim


Solution 1:[1]

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.

Solution 2:[2]

: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).

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Light
Solution 2 cassepipe
Solution 3