How do I replace the Vim command-line content with the result of a Vimscript expression?
Answer
<C-\>e {expr}<CR>
Explanation
Pressing <C-\>e while in command-line mode (:, /, ?, or !) evaluates a Vimscript expression and replaces the entire command-line with its result. This lets you build commands dynamically using Vim functions without leaving the command line.
How it works
- Start typing any command on the
:(or/) prompt - Press
<C-\>e— the cursor moves to a mini expression prompt - Type a Vimscript expression and press
<CR> - The result replaces whatever was on the command line
- Press
<CR>again to execute the resulting command
Example
Suppose you want to open a file in the same directory as the current file. Instead of typing the path manually:
:e <C-\>e 'e ' . expand('%:p:h') . '/'<CR>
This evaluates 'e ' . expand('%:p:h') . '/' and replaces the command line with something like :e /home/user/myproject/, ready for Tab completion.
Another example — substitute using a pattern from a register:
:%s/<C-\>e @a<CR>//g
This replaces the pattern field with the contents of register a.
Tips
- Works in all command-line modes:
:,/,?, and! - Combine with
expand(),getcwd(),getline('.'), and other Vimscript functions - To insert just a function result into the command line (not replace it), use
<C-r>=instead