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

How do I build and execute a command dynamically?

Answer

:execute "command"

Explanation

The :execute command evaluates a string expression and runs it as an Ex command. This is essential for building commands dynamically in scripts.

How it works

  • :execute "set tabstop=" . 4 runs :set tabstop=4
  • String concatenation with . builds the command
  • Variables and expressions can be embedded

Example

:let width = 80
:execute "set textwidth=" . width

:let fname = "config.yaml"
:execute "edit " . fname

Tips

  • Use with normal!: :execute "normal! " . count . "j"
  • Essential for writing Vim plugins and scripts
  • \<CR> and \<Esc> are special key sequences in execute strings
  • :execute can chain multiple commands with |
  • Combine with variables from user input for interactive scripts

Next

How do you yank a single word into a named register?