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()
" 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.
" 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)
" restore old view
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
bufname() all points to the old buffer
You can't do it with
:e file will trigger it.
You must also make sure new window is in a
- You must make sure it's not a blank buffer.
I didn't do it, it looks complicate and fragile.