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

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 of var as an Ex command
  • :execute 'normal! ' . keys — constructs and runs a :normal! command with a variable key sequence
  • execute() (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 via nr2char(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 and execute lets 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 :execute command runs it. They are different!
  • :execute with a list runs each element in sequence: :execute ['set number', 'set ruler']

Next

How do I run a search and replace only within a visually selected region?