How do I evaluate a Vimscript expression and insert the result into a command-line command?
Answer
<C-r>= (command-line mode)
Explanation
Just like <C-r>= lets you insert evaluated expressions in insert mode, you can use it inside an Ex command on the command line to embed any Vimscript expression result mid-command. This lets you build dynamic commands — computing filenames, line numbers, timestamps, or buffer values — without leaving the command line or writing a separate mapping.
How it works
- Start typing an Ex command (e.g.,
:%s/old/) - At the point where you want a dynamic value, press
<C-r>= - The
=prompt appears; type any Vimscript expression and press<CR> - The evaluated result is inserted into the command as a plain string
- Finish the command normally
Example
Replace TODO with today's date:
:%s/TODO/<C-r>=strftime("%Y-%m-%d")<CR>/g
After pressing <CR> on the expression, it becomes:
:%s/TODO/2026-03-07/g
Open a file path computed from the word under cursor:
:e <C-r>=expand('<cfile>')<CR>
Tips
- Any Vimscript function works:
line('.'),col('.'),shellescape(expand('%')),system('hostname') - Works in search patterns too: press
/then<C-r>=to embed a computed regex - Combine with
<C-r><C-w>(word under cursor) and<C-r><C-a>(WORD under cursor) for other inline insertions - See
:help c_CTRL-R_=for full documentation