2

I often use :line to jump to a line number. How can I automatically center that line vertically after jumping? Essentially the same as running :150zz.

6
  • Wait. This doesn't happen for you automatically? Every time I enter a line number at the command line the jumped-to line is vertically centered. Oh wait...maybe you mean when the jump is small (i.e. the visible lines don't change). Is that right?
    – B Layer
    Commented May 17, 2021 at 18:20
  • No, it never happens. If the page has to scroll then the cursor is at the very extremes of the page (either top or bottom). Commented May 17, 2021 at 19:38
  • You can probably get close with set scrolloff=998, but that has other effects (I prefer more like 5 or so).
    – D. Ben Knoble
    Commented May 18, 2021 at 0:47
  • How strange. Even with -u NONE or --clean I get cursor line centered as long as the jump is to a line not currently on screen. You might try that too (vim --clean filename)...it may indicate that your current config has something preventing the behavior I describe.
    – B Layer
    Commented May 18, 2021 at 13:05
  • @BLayer it works for me the way you describe only for help buffers. All others are as OP describes.
    – Maxim Kim
    Commented May 25, 2021 at 18:05

1 Answer 1

2

It looks like "centering" depends on the length of the jump with the rough ratio (window lines / jump lenght) == 0.625:

If

  • you have 45 window lines and you jump more than 69 lines or
  • you have 22 window lines and you jump more than 33 lines or
  • you have 15 window lines and you jump more than 23 lines

then cursor would be centered in window, otherwise not.

I am not sure if there is an option that you can use to change "jump center size", but set scrolloff=999 makes your cursor almost always be centered.

Another option would be to map command line <CR> to zz after a range:

cnoremap <expr> <CR> (getcmdtype() == ":" && getcmdline() =~ '\d\+') ? "<CR>zz" : "<CR>"
2
  • Hmm. Made sense to me when I thought it was determined by the target line being visible or not. This ratio driven formula...not so much. Wonder what the rationale is behind it.
    – B Layer
    Commented May 27, 2021 at 1:04
  • @Maxim Kim Shouldn't part of the comparison in your answer be getcmdline() =~ '^\d\+$', i.e. with the ^ and $ anchors in the regexp, instead of just getcmdline() =~ '\d\+'?
    – dsimic
    Commented Jan 12 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.