How do I create a Neovim mapping that runs an Ex command without entering command-line mode or changing the current mode?
Answer
<Cmd>
Explanation
The <Cmd> pseudo-key in Neovim allows a mapping to execute an Ex command directly, without going through command-line mode. Unlike a mapping that starts with :, using <Cmd> does not temporarily switch to command-line mode, does not affect mode(), and does not discard or alter visual selections. This makes it the correct way to write robust, mode-agnostic mappings.
How it works
- Regular
:mapping:nnoremap <leader>n :echo line('.')<CR>— enters command-line mode briefly, may cause flicker or side effects <Cmd>mapping:nnoremap <leader>n <Cmd>echo line('.')<CR>— runs the command internally without any mode change
The key difference is that <Cmd> does NOT invoke CTRL-\CTRL-N first, so in visual mode the selection is still active when the command runs.
Example
" Toggle line numbers without mode flicker:
nnoremap <leader>n <Cmd>set number!<CR>
" Works in visual mode without losing the selection:
xnoremap <leader>s <Cmd>sort<CR>
" Lua equivalent in Neovim config:
vim.keymap.set('n', '<leader>n', '<Cmd>set number!<CR>')
Tips
<Cmd>works in all modes (normal, insert, visual, terminal) with the same syntax- Unlike
:,<Cmd>does not consume<C-u>to clear any preceding range — it is handled automatically - Prefer
<Cmd>over:in all new mappings to avoid unintended mode-switching side effects - See
:help <Cmd>for the full specification