3

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 '21 at 09:37
  • (And yes, I should have put that in an answer but I have to leave suddenly. Cheers.) – B Layer May 15 '21 at 09:46
  • 1
    :help wincmd, but I think there’s a better way – D. Ben Knoble May 15 '21 at 13:02
  • Welcome to [vi.se]! – filbranden May 15 '21 at 18:26

1 Answers1

6

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()

So

" get current window identifier
let wid = win_getid()

" do splits split newfile vert split anotherfile

" go back call win_gotoid(wid)

Maxim Kim
  • 13,376
  • 2
  • 18
  • 46
  • 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 '21 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 '21 at 19:55