Tuesday, November 4, 2014

More on Vim Splits

I wrote a post recently on how you can resize split Vim windows automatically as you move between them. I've been playing around with it for a while and have found a better solution.

The small script I presented in that post works OK. But when you have more then 4-5 windows, you'll notice that the non-focused windows get resized very unevenly. Some will hardly change, others might shrink to a single horizontal or vertical line.

Vim already has a function that can almost do what we want: ctrl-w = makes all windows equal size. But, if you read the manual(1) you'll find that it will also try to make the size of the current window to winheight and winwidth if you set those variables. it will still try to set the other windows to be about equal size.

That means that instead of resizing our window explicitly, like the old script did, we can simply set winheight and winwidth to the size we want, call ctrl-w = and we're done.

One more tweak: With large screens and the old script, the vertical resize would sometimes actually resize the command line as well. A bit annoying. I've removed the maximum vertical size restriction below.

" Resize the current split to at least (90,25) but no more than 140
" characters wide, or 2/3 of the available space otherwise.

function Splitresize()
    let &winwidth = min([max([float2nr(&columns*0.66), 90]), 140])
    let &winheight = max([float2nr(&lines*0.66), 25])
    exe "normal! \<C-w>="

As in the previous post, you can remap ctrl-h, ctrl-j, ctrl-k, ctrl-l to quickly move between splits and trigger the resize each time:

" move between splits using ctrl-h, j, k and l

nnoremap <silent><C-J> <C-W><C-J>:call Splitresize()<CR>
nnoremap <silent><C-K> <C-W><C-K>:call Splitresize()<CR>
nnoremap <silent><C-L> <C-W><C-L>:call Splitresize()<CR>
nnoremap <silent><C-H> <C-W><C-H>:call Splitresize()<CR>

Try this, and let me know what you think.

#1 Yes, I know. I don't read manuals either. Nobody reads manuals. And yet, we spend huge amounts each year on books that describe exactly the same thing as the manuals we never read.

No comments:

Post a Comment

Comment away. Be nice. I no longer allow anonymous posts to reduce the spam.