2

I often find myself doing something like this with a tiny header file with only a few lines:

  • Ctrl-W, ^
  • Ctrl-W, j
  • 50, Ctrl-W, -
  • 50, Ctrl-W, -
  • 30, Ctrl-W, -
  • 10, Ctrl-W, -

… or similar, to slowly "zero in" my window-height on the height of the actual file's contents.

Ideally, I'd like the sort of “inverse” of 'scrolloff' — “for new splits, if there's <= 'lines' of text in the buffer, then set 'winheight' to 'lines' + N”; but if that's not possible, a hotkey to achieve the same for the current window would probably suffice!

1
1

Manual approach

You can use 2<c-w>0 to resize current window to fit buffer, with 2 extra lines.

It's fully commented, read comment as explanation.

" Resize window to fit buffer + <count>. It works the same as <c-w>_ if there
" are too many lines to fit.
command -count WinFitBuf call s:win_fit_buf(<count>)
nnoremap <expr> <c-w>0 printf(':<c-u>%dWinFitBuf<cr>', v:count)

function s:win_fit_buf(extra_lines) abort

  " save old view
  let cview = winsaveview()

  try

    " I must find screen line count for current buffer, I don't know how to do
    " it directly, so I decide to maximize current window first, then shrink to
    " fit, I only need last screen line of current buffer this way.
    wincmd _

    " Clear scroll, goto last byte. I start this with ex 0 and $, but they don't
    " clear scroll until script finished.
    keepjump norm! ggG$

    " resize to fit
    exe printf('%dwincmd _',  winline() + a:extra_lines)

  finally

    " restore old view
    cal winrestview(cview)
  endtry

endfunction

Automatic

It's tricky to do it automatically:

  • You can't do it with WinNew, as you don't know new buffer line count in this moment, the <afile> and bufname() all points to the old buffer name.
  • You can't do it with WinBufEnter, as :e file will trigger it.

  • You must also make sure new window is in a col layout.

  • You must make sure it's not a blank buffer.

I didn't do it, it looks complicate and fragile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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