vimtricks.wiki Concise Vim tricks, one at a time.

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 numbers
  • win_gotoid(id) — jump to the window with that ID; returns 1 on success, 0 if window no longer exists
  • win_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() over winnr() 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 returns 0 if the window was closed before you try to return to it

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?