How do I run a Normal-mode command through :execute in Vim?
Answer
:execute "normal! gg=G"<CR>
Explanation
:execute lets you build and run Ex commands dynamically, which is critical when a command depends on variables, conditionals, or string composition. A practical example is dispatching a raw Normal-mode operation with normal!, so mappings do not interfere and the behavior stays deterministic. This is useful in repeatable refactoring workflows and custom commands where you need exact keystroke semantics.
How it works
:execute "normal! gg=G"<CR>
:executeevaluates a string as an Ex command"normal! ..."is the string being executednormal!runs keys in Normal mode while ignoring user mappingsgg=Gjumps to top and reindents the entire buffer<CR>executes the assembled command
Example
Before:
function demo(){
console.log('x')
}
After running the command, Vim applies your current indent rules to the whole file so structure is normalized consistently.
function demo(){
console.log('x')
}
Tips
- Use
executewhen command pieces come from variables (for example register names or search terms) - Prefer
normal!overnormalin automation so mappings cannot change behavior