In vim, how do you scroll a buffer so the cursor location is centered in the screen?
In vim, often I will jump to a mark I made, or a search result, and the cursor will be at the very bottom or very top of the screen. At this point, in order for the screen to be easier to read, I want to scroll the buffer so that the text under the cursor is in the middle of the screen.
Is this possible in vim? How do you do it?
This will center the current line
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.
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 :)
The 'scrolloff' (scroll offset) option determines the number of context lines you would like to see above and below the cursor. Setting it to, say, 5 makes it so there are always 5 lines visible above and below the cursor while moving/scrolling. Setting 'scrolloff' to a large value causes the cursor to stay in the middle line when possible:
To restore normal behavior, enter:
If you're switching between those a lot, you can create a mapping to toggle quickly:
:nnoremap <Leader>ts :let &scrolloff=999-&scrolloff<CR> " ToggleScrolloff
You have to press z twice, like: zz
The scrollfix.vim plugin is great for this. That is what I use, and it works like a charm. You can find it on github here.
The scrollfix plugin allows you to control exactly where (vertically along the buffer) your cursor stays fixed. By default it is at 60% of the buffer from the top, but this is customizable. This affects the position of the cursor in the normal as well as in the insert mode.