Last Updated: February 25, 2016
·
1.131K
· caioariede

Vim: Automatically split windows at 79 columns

As a Vim addicted user that spends most of the time programming in Python, I like to split my windows at exactly 79 columns, as a coding convention defined by PEP 8.

Paste the code below in your .vimrc if you want this behavior too.

function! SplitByColumnSize(col)
    let l:s_s = &nu ? a:col + &numberwidth : a:col
    let l:s_t = trunc(round(winwidth(0) / round(l:s_s)))
    let l:s_c = 1

    " Split window s_t times
    while l:s_c < l:s_t
        vne
        wincmd w
        let l:s_c = l:s_c + 1
    endwhile

    wincmd H

    let l:s_c = 1

    " Resize splits
    while l:s_c < l:s_t
        exe 'vert resize '.l:s_s
        wincmd w
        let l:s_c = l:s_c + 1
    endwhile
endfunction

command PySplit call SplitByColumnSize(79)

" Comment the line below to not split at startup
PySplit

If you want to split windows by your own, just comment the last line and then call the :PySplit command when you need it.

Closing buffers without messing the splits go to protip ↠

The following map allows you to close a buffer without losing the splits. Just type \c

It depends on your mapleader configuration. See :help leader

nmap <leader>c :ene<CR>:bd #<CR>