vimtricks.wiki Concise Vim tricks, one at a time.

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>
  • :execute evaluates a string as an Ex command
  • "normal! ..." is the string being executed
  • normal! runs keys in Normal mode while ignoring user mappings
  • gg=G jumps 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 execute when command pieces come from variables (for example register names or search terms)
  • Prefer normal! over normal in automation so mappings cannot change behavior

Next

How do I mix very-nomagic and magic sections in a single Vim search?