Easy window movement and creation

1 Point

Mathijs Saey Mathijs Saey

2 weeks ago

Use <leader> <prefix key> and one of hjkl to move between windows easily (as with <C-w>). A window is automatically created if you try to move to a location that is not present.

For example, if you press <leader> <prefix key> j when there is no window below the current window, the command automatically opens a new split below the current window and moves to it. If a window is present below the current window, the command just moves to the window.

function! MoveOrCreateWindow(key) abort
    let t:curwin = winnr()
    exec "wincmd ".a:key
    if (t:curwin == winnr())
        if (match(a:key,'[jk]'))
            wincmd v
            wincmd s
        exec "wincmd ".a:key

nnoremap <silent> <Leader>mh :call MoveOrCreateWindow('h')<CR>
nnoremap <silent> <Leader>mj :call MoveOrCreateWindow('j')<CR>
nnoremap <silent> <Leader>mk :call MoveOrCreateWindow('k')<CR>
nnoremap <silent> <Leader>ml :call MoveOrCreateWindow('l')<CR>