How do I save my current window and return to it after navigating other windows from a script or function?
Answer
:let winid = win_getid() | ... | call win_gotoid(winid)
Explanation
The win_getid() and win_gotoid() functions let you bookmark a window by its stable integer ID and jump back to it reliably. This is essential when writing Vimscript functions that visit other windows (to run commands, inspect buffers, etc.) and must restore the original context afterward.
Unlike winnr() which returns a window's position number (which shifts when windows open or close), a window ID returned by win_getid() is stable for the lifetime of that window.
How it works
win_getid()— returns the unique ID of the current window (integer)win_getid(winnr, tabnr)— optionally specify window and tab numberswin_gotoid(id)— jump to the window with that ID; returns 1 on success, 0 if window no longer existswin_id2win(id)— convert a window ID back to a window number
Example
function! RunInQuickfix(cmd)
let winid = win_getid() " save caller's window
copen " open or focus quickfix window
execute a:cmd " run command in quickfix context
call win_gotoid(winid) " return to the original window
endfunction
Tips
- Always prefer
win_getid()overwinnr()in functions that open new windows or tabs, since window numbers renumber dynamically - Combine with
win_findbuf(bufnr)to locate which window displays a specific buffer - Check the return value of
win_gotoid(): it returns0if the window was closed before you try to return to it