How do I create a mapping that runs an Ex command without switching modes or affecting the current state?
Answer
nnoremap <key> <Cmd>command<CR>
Explanation
The <Cmd> special key (Vim 8.2+ and Neovim) lets you run an Ex command inside a mapping without entering command-line mode or changing the editor's current state. Unlike the usual :command<CR> approach, <Cmd> executes the command transparently — no mode switch, no flickering command line, and no disruption to visual selections, insert mode, or operator-pending mode.
How it works
A conventional mapping like:
nnoremap <F5> :update<CR>
...temporarily switches to command-line mode, runs the command, and returns. In insert or visual mode this can disrupt state (visual selections, insert text) or require additional workarounds.
Using <Cmd> instead:
nnoremap <F5> <Cmd>update<CR>
inoremap <F5> <Cmd>update<CR>
xnoremap <F5> <Cmd>update<CR>
The command runs in all three mappings without leaving the current mode. The visual selection is preserved, insert mode is not exited.
Example
Toggling the quickfix window from any mode:
nnoremap <leader>q <Cmd>copen<CR>
inoremap <leader>q <Cmd>copen<CR>
The insert-mode variant won't exit insert mode, unlike :copen<CR> which would.
Tips
<Cmd>was introduced in Vim 8.2 / Neovim 0.2. Guard it withif has('patch-8.2.1978')for older Vim compatibility- The command string must end with
<CR>to execute <Cmd>cannot take a range the way:range commandcan — usefeedkeys()or a Vimscript function for that