I am trying to find a function which will switch back to the original window in a split view for vim. I know about shortcut and I also know about the function :call cursor. But is there a function which can let me switch back to the previous split window so I could stick it in my vim function?
Asked
Active
Viewed 3,920 times
13
-
1Also for questions about Vim and Vi one could be interested in the [dedicated stack exchange site](http://vi.stackexchange.com/). – statox Sep 26 '15 at 23:06
-
1@statox thanks I didn't know about it. Bookmarked!! – SUB Sep 26 '15 at 23:16
-
Why a function when there's `
p`? – romainl Sep 27 '15 at 07:24 -
1@romainl so I can use it in a script. I didn't know how to use a shortcut in vim script – SUB Sep 27 '15 at 20:44
1 Answers
18
In a vimscript you can use:
" Save the window where you are currently
let l:currentWindow=winnr()
" Do stuff where you change of window
" Go back to the original window
exe l:currentWindow . "wincmd w"
For more information the doc is always an excellent reading:
Edit Another way to do it is to use wincmd p
:
wincmd
is the vimscript equivalent to Ctrlw in normal mode.
In normal mode when you change of window you can use Ctrlw + p to come back to the previous window. So in vimscript you simply use:
wincmd p
To go back to the previous window.
Of course if the rest of your function use more than 2 splits you will not go back to your initial window but if you have only two splits it can be lighter than using a variable to keep the number of your window.

statox
- 2,827
- 1
- 21
- 41
-
-
Is there a similar function which checks if there is split already present? then instead of creating a new split I can just switch into the other window and do the stuff... – SUB Sep 26 '15 at 22:57
-
1@SUB For the "how I found it" I was trying to find a way to use `windo` without changing the current window from the user point of view so I read [`:h window`](http://vimdoc.sourceforge.net/htmldoc/windows.html#window) and worked with Vimscript... For your second question you should read [`:h winnr()`](http://vimdoc.sourceforge.net/htmldoc/eval.html#winnr()). Knowing that `winnr('$')` gives you the total number of splits in the current tab you should be able to work with it. – statox Sep 26 '15 at 23:03
-
I am on vim 6.4 The function winnr('$') doesn't work. Is there something old school for finding the number of split windows? – SUB Sep 26 '15 at 23:23
-
2