Switch buffers between two windows intuitively

1 Point

Enan Ajmain Enan Ajmain

5 years ago

Vim has :h CTRL-W_x to switch windows. But it doesn't work as well if horizontal and vertical splits are mixed. The following snippet will provide a function that will switch buffers between two windows effectively emulating :h CTRL-W_x but with much more intuitive keybinding.

You need to know the window numbers of the windows for this keybinding to work. You could use your statusline to do that with set stl += %{winnr()}. Then you can call the function with argument of window number of the window that you want to swap with the current window. It will swap the buffers between those windows, effectively emulating swapping the windows between those two splits.

NOTICE: This may not work as expected if you have any situation where you really have to swap windows and not buffers between them. For example, when using :h matchetc.

function! SwitchWindow(count) abort
    let l:current_buf = winbufnr(0)
    exe "buffer" . winbufnr(a:count)
    exe a:count . "wincmd w"
    exe "buffer" . l:current_buf
    wincmd p
endfunction
nnoremap <Leader>wx :<C-u>call SwitchWindow(v:count1)<CR>