Brandon
Brandon

Reputation: 2125

Smart window resizing with splits in MacVim

I'm using the latest MacVim. Is there any way to have it so if I open MacVim without a file or with only one file, it sets the window width to n characters? Then if I do a vertical split it will expand the window width to 2n characters? Same for 3 vertical splits but it will stop increasing the width after the window is 3n characters. Then if I close those splits it will resize down?

Upvotes: 4

Views: 1487

Answers (2)

Randy Morris
Randy Morris

Reputation: 40927

This appears to work. Whether or not a horizontal split has been done, any time a vsplit is created or deleted the window is resized.

let g:auto_resize_width = 40
function! s:AutoResize()
    let win_width = winwidth(winnr())
    if win_width < g:auto_resize_width
        let &columns += g:auto_resize_width + 1
    elseif win_width > g:auto_resize_width
        let &columns -= g:auto_resize_width + 1
    endif
    wincmd =
endfunction

augroup AutoResize
    autocmd!
    autocmd WinEnter * call <sid>AutoResize()
augroup END

Configure the window width by changing the variable at the top. You probably want to do something like let g:auto_resize_width = &columns to set it to use the width of the original window as the width to resize by.

Things get a little wonky if you have so many vsplits that the window becomes maximized horizontally. I'm trying to find a fix and I'll post it if I find one.

Upvotes: 4

Prince Goulash
Prince Goulash

Reputation: 15715

I realized that my first post modified window height, not width. Here is what I meant:

Here's a quick solution I came up with, but it's not perfect. The function counts the number of open windows and then sets the window width to original_width * num_windows. The autocommands call the function when Vim starts, and whenever a new window is opened. You can change the default window width (80) to suit your needs.

function! SmartWidth( width )
    let num_wins = 0
    windo let num_wins+=1
    sil exe "set columns=" . num_wins * a:width
    sil exe "normal! \<c-w>="
endfunction

autocmd VimEnter * call SmartWidth(80)
autocmd WinEnter * call SmartWidth(80)

This works in the basic case, but does not distinguish between horizontal and vertical splits. I don't know how to do that!

Upvotes: 0

Related Questions