In vim, how do you scroll a buffer so the cursor l

2020-05-19 17:57发布

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?

标签: vim
5条回答
\"骚年 ilove
2楼-- · 2020-05-19 18:05

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:

:set so=999

To restore normal behavior, enter:

:set so=0

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
查看更多
家丑人穷心不美
3楼-- · 2020-05-19 18:10

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.

查看更多
▲ chillily
4楼-- · 2020-05-19 18:11

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

查看更多
Fickle 薄情
5楼-- · 2020-05-19 18:17

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
查看更多
Melony?
6楼-- · 2020-05-19 18:26

You have to press z twice, like: zz

查看更多
登录 后发表回答