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

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 h is 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 :execute expressions

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 w cycles through windows (like <C-w>w)
  • :wincmd p jumps to the previously focused window — useful for toggling between two panes
  • Use :execute "wincmd " . key when the target key is computed at runtime
  • In Neovim Lua: vim.cmd('wincmd h') or vim.api.nvim_command('wincmd h')
  • :wincmd is particularly useful in plugins that need to reposition focus without assuming the user has not remapped <C-w>

Next

How do I programmatically set a register's content in Vimscript to pre-load a macro?