How do I save and restore the current window layout after temporarily changing window sizes in a Vim script?
Answer
winrestcmd()
Explanation
The winrestcmd() function returns a string of Ex commands that, when executed, restore all window sizes to their state at the time of the call. This makes it possible to temporarily resize or maximize a window inside a Vimscript function, then cleanly return to the original layout when done.
How it works
winrestcmd()captures the current window layout as a restore-command string- Store it in a variable:
let save = winrestcmd() - Perform any resize operations
- Restore with:
execute save
Common resize commands to pair with it:
wincmd _— maximize height of current windowwincmd |— maximize width of current windowvertical resize N/resize N— set explicit sizes
Example
A toggle-maximize mapping that restores the original layout on the second press:
let g:_winrestore = ''
function! ToggleMaximize() abort
if g:_winrestore ==# ''
let g:_winrestore = winrestcmd()
wincmd _ | wincmd |
else
execute g:_winrestore
let g:_winrestore = ''
endif
endfunction
nnoremap <silent> <leader>m :call ToggleMaximize()<CR>
Or inline in a script to temporarily maximize, run a command, then restore:
let save = winrestcmd()
wincmd _ | wincmd |
execute 'normal! gg=G'
execute save
Tips
winrestcmd()captures window sizes only — usewin_getid()andwin_gotoid()to also preserve window focus- Combine with
winsaveview()/winrestview()to preserve cursor position and scroll state within a window - This is the pattern many plugins use when temporarily expanding a window for output display