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

How do I execute Ctrl-W window commands from a Vimscript mapping or function without using :normal?

Answer

:wincmd {key}

Explanation

:wincmd is the Ex command equivalent of any <C-w> keystroke. Instead of calling :normal! <C-w>k (which can be fragile in functions and mappings), you use :wincmd k to move to the window above. This is the idiomatic way to issue window commands from Vimscript, autocmds, or custom mappings.

How it works

  • :wincmd {key} — runs the <C-w>{key} command
  • {key} can be any character that follows <C-w> in normal mode: h/j/k/l for focus movement, H/J/K/L for repositioning, = to equalize, _ to maximize, etc.
  • Accepts a [count] prefix for commands that support it: :5wincmd w rotates 5 windows forward

Example

A mapping that opens a terminal split and focuses it:

nnoremap <leader>t :split \| terminal<CR> \| :wincmd j<CR>

Or in a function:

function! FocusLeft()
  wincmd h
endfunction

The function-level call omits the : colon, but the effect is identical.

Tips

  • All <C-w> commands have a :wincmd equivalent — check :help CTRL-W for the full list
  • Prefer :wincmd over :normal! <C-w>... in functions and plugins; it is safer and more explicit
  • :wincmd n opens a new empty window, equivalent to :new
  • In Neovim Lua, use vim.cmd('wincmd k') or vim.cmd.wincmd('k')

Next

How do I paste the contents of a register as a new line below the cursor regardless of the register type in Vim?