How do I execute Ctrl-W window commands from the command line or a Vimscript function?
Answer
:wincmd
Explanation
:wincmd {key} executes any <C-w>{key} window command from the Ex command line or from inside a Vimscript function. Since you cannot embed a literal <C-w> keystroke in an Ex string or a nnoremap RHS that uses : commands, :wincmd is the standard bridge between Vimscript and window management. It accepts the same single-key arguments as <C-w> and also supports a count prefix.
How it works
:wincmd his equivalent to pressing<C-w>h(move focus to the window on the left)- Works with all
<C-w>subcommands:j k l h(focus),s v(split),=(equalize),_|(maximize),r(rotate),p(previous),w(cycle),c(close), etc. - Accepts a count:
3wincmd >widens the current window by 3 columns - Can be called from functions, autocommands, and
:executeexpressions
Example
A function that opens a file in a vertical split, equalizes window widths, and moves focus back:
function! OpenBeside(file)
execute 'vsplit ' . a:file
wincmd =
wincmd p
endfunction
A mapping that creates a horizontal split and immediately jumps into it:
nnoremap <leader>s :split<CR>:wincmd j<CR>
Dynamic window movement using a variable:
let direction = 'l'
execute 'wincmd ' . direction
Tips
:wincmd wcycles through windows (like<C-w>w):wincmd pjumps to the previously focused window — useful for toggling between two panes- Use
:execute "wincmd " . keywhen the target key is computed at runtime - In Neovim Lua:
vim.cmd('wincmd h')orvim.api.nvim_command('wincmd h') :wincmdis particularly useful in plugins that need to reposition focus without assuming the user has not remapped<C-w>