How to swap files between windows in VIM?
I wrote and have been using the following code snippet in my vimrc for copy-pasting my Vim windows.
This defines for example the following shortcuts:
<c-w>y
: "Yanks the window", i.e. stores the number of the buffer in the current window in a global variable.<c-w>pp
: "Puts the window in Place of the current window", i.e. it reads the buffer number stored previously and opens that buffer in the current window. It also stores the number of the buffer that used to be in the current window.
If by "swapping those windows in places", you mean "opening the buffer in window A in window B, and vice versa, without changing the position of the windows", you can use the following keyboard sequence to swap the windows:
- Select window A (either with mouse or with keyboard commands)
- Press
<c-w>y
(yanking the buffer number) - Select window B
- Press
<c-w>pp
(pasting the buffer) - Select window A
- Press
<c-w>pp
(pasting the buffer again)
It works only in Vim >= 7.0.
if version >= 700
function! HOpen(dir,what_to_open)
let [type,name] = a:what_to_open
if a:dir=='left' || a:dir=='right'
vsplit
elseif a:dir=='up' || a:dir=='down'
split
end
if a:dir=='down' || a:dir=='right'
exec "normal! \<c-w>\<c-w>"
end
if type=='buffer'
exec 'buffer '.name
else
exec 'edit '.name
end
endfunction
function! HYankWindow()
let g:window = winnr()
let g:buffer = bufnr('%')
let g:bufhidden = &bufhidden
endfunction
function! HDeleteWindow()
call HYankWindow()
set bufhidden=hide
close
endfunction
function! HPasteWindow(direction)
let old_buffer = bufnr('%')
call HOpen(a:direction,['buffer',g:buffer])
let g:buffer = old_buffer
let &bufhidden = g:bufhidden
endfunction
noremap <c-w>d :call HDeleteWindow()<cr>
noremap <c-w>y :call HYankWindow()<cr>
noremap <c-w>p<up> :call HPasteWindow('up')<cr>
noremap <c-w>p<down> :call HPasteWindow('down')<cr>
noremap <c-w>p<left> :call HPasteWindow('left')<cr>
noremap <c-w>p<right> :call HPasteWindow('right')<cr>
noremap <c-w>pk :call HPasteWindow('up')<cr>
noremap <c-w>pj :call HPasteWindow('down')<cr>
noremap <c-w>ph :call HPasteWindow('left')<cr>
noremap <c-w>pl :call HPasteWindow('right')<cr>
noremap <c-w>pp :call HPasteWindow('here')<cr>
noremap <c-w>P :call HPasteWindow('here')<cr>
endif
There are a few useful commands built in which give you a certain amount of control, but it's not comprehensive. The main ones are:
Ctrl-W, r (i.e. hold CTRL, press W, release CTRL, press r) - which rotates the windows (The first window becomes the second one, the second one becomes the third one, etc.)
Ctrl-W, x - swap the current window with the next one
Ctrl-W, Shift-H - move this window to the far left
Ctrl-W, Shift-K - move this window to the top
(and similarly for Ctrl-W, Shift-J and Ctrl-W, Shift-L). See:
:help window-moving
for more information.