13

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?

SUB
  • 287
  • 3
  • 14

1 Answers1

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
  • May I ask how you found it? – SUB Sep 26 '15 at 22:54
  • 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
    @SUB upgrade... (Vim 6.4 came out almost 10 years ago) – FDinoff Sep 27 '15 at 00:11