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/lfor focus movement,H/J/K/Lfor repositioning,=to equalize,_to maximize, etc.- Accepts a
[count]prefix for commands that support it::5wincmd wrotates 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:wincmdequivalent — check:help CTRL-Wfor the full list - Prefer
:wincmdover:normal! <C-w>...in functions and plugins; it is safer and more explicit :wincmd nopens a new empty window, equivalent to:new- In Neovim Lua, use
vim.cmd('wincmd k')orvim.cmd.wincmd('k')