How do I dynamically build and run Ex commands from strings in Vim?
Answer
:execute 'normal! ' . count . 'j'
Explanation
The :execute command evaluates a string as an Ex command, enabling dynamic command construction. You can build commands using variables, expressions, and concatenation, making it the cornerstone of Vimscript metaprogramming.
How it works
:execute {string}— evaluates the string as an Ex command- Strings can be concatenated with
.operator - Variables and expressions are interpolated when building the string
- Nested
executecalls are supported
Example
" Dynamic normal mode command
:let count = 5
:execute 'normal! ' . count . 'j'
" Dynamic substitution
:let old = 'foo'
:let new = 'bar'
:execute '%s/' . old . '/' . new . '/g'
" Open file from variable
:let fname = 'config.yml'
:execute 'edit ' . fname
Tips
- Use
executeto run commands with special characters that are hard to type literally - Combine with
normal!(with bang) to avoid triggering user mappings executecan run multiple commands separated by|- Use
fnameescape()when using filenames::execute 'edit ' . fnameescape(name)