How do I construct and run a Vim Ex command dynamically from a string or variable?
Answer
:execute {string}
Explanation
:execute evaluates a string expression and runs its value as an Ex command. This unlocks dynamic command construction — building commands from variables, function return values, and string concatenation — which is impossible with literal Ex commands alone. It is the foundation of Vim scripting and advanced mappings.
How it works
:execute 'command'— runs the literal string as an Ex command:execute var— runs the value ofvaras an Ex command:execute 'normal! ' . keys— constructs and runs a:normal!command with a variable key sequenceexecute()(the function form, no colon) — returns the output of the command as a string- Special characters like
<CR>,<Esc>must be expressed as"\<CR>"(double-quoted) or vianr2char(13)
Example
Open a file whose name is stored in a variable:
let filename = 'src/main.py'
execute 'edit ' . filename
Run a search for whatever is in a variable:
let pattern = 'TODO'
execute 'normal! /' . pattern . "\<CR>"
Capture command output into a variable:
let output = execute('ls')
echo output
Tips
- Always prefer
:execute 'normal! ...'over:normal ...in scripts — the!skips user mappings andexecutelets you use string expressions for the key sequence - Use
shellescape()when building shell commands::execute '!ls ' . shellescape(dir) - The
execute()function (Vim 8+) captures output; the:executecommand runs it. They are different! :executewith a list runs each element in sequence::execute ['set number', 'set ruler']