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.