I am writing a function which splits open vim in three parts but the focus shifts towards the newly opened window and I don't want that that to happen is there any way to stop this? or is there a command which does this for me so that i can insert that in the function? or how can i use the <c-w> h in the function?

  • I wouldn't worry about maintaining focus in current window while you're opening others. Just mark your location, open everything, and jump back to that position. Really easy way to do that is use a capital letter mark (e.g. mX) and return with backtick then that letter. To run Normal mode commands in a function see :h :normal. Non-Normal mode way is to save the current cursor location with :h getpos(), and return with :h setpos().
    – B Layer
    May 15, 2021 at 9:37
  • (And yes, I should have put that in an answer but I have to leave suddenly. Cheers.)
    – B Layer
    May 15, 2021 at 9:46
  • 1
    :help wincmd, but I think there’s a better way
    – D. Ben Knoble
    May 15, 2021 at 13:02
  • Welcome to Vi and Vim!
    – filbranden
    May 15, 2021 at 18:26

1 Answer 1


I would do it this way:

  1. :h win_getid() to get (and then save) current window identifier
  2. Do your splits
  3. Go back to your saved window with :h win_gotoid()


" get current window identifier
let wid = win_getid()

" do splits
split newfile
vert split anotherfile

" go back
call win_gotoid(wid)
  • 1
    Oh, winsaveview/winrestview is what I was thinking of in the comments; they would enhance this technique, which is already pretty solid
    – D. Ben Knoble
    May 15, 2021 at 18:02
  • 1
    @Ben Not sure if winrestview() is useful when you're changing the layout by moving or adding new windows (such as in this case), since I believe it will try to save and restore the dimensions of the window, which might shrink the newly created ones... (I haven't tested it, so not sure how that would behave here.)
    – filbranden
    May 15, 2021 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.