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

How do I capture Vim command output to a variable or register using the execute() function?

Answer

:let @a = execute('messages')

Explanation

The execute() function (added in Vim 8.0 / Neovim) returns the output of any Ex command as a string. Unlike the older :redir approach, execute() works inline within expressions, inside functions, and in mappings — no open/close bookends required. This makes it far cleaner for programmatic use.

How it works

  • execute('{cmd}') — runs {cmd} and returns its output as a string
  • :let @a = execute('messages') — captures :messages output directly into register a
  • :let output = execute('set all') — saves all option values to a Vimscript variable
  • Multiple commands can be chained: execute('set number | set list')

Example

The old :redir way required three steps:

:redir @a
:silent messages
:redir END

With execute(), the same result in one line:

:let @a = execute('messages')

Now "ap pastes the captured messages output.

Tips

  • Use inside functions: let result = execute('scriptnames') for scripting
  • Chain with :put to insert output below the cursor: :put =execute('jumps')
  • Suppress the newline prefix with execute('cmd', 'silent') as the second argument
  • Works inside :normal! and mappings — :redir could cause recursion issues in those contexts
  • Available in Vim 8.0+; use :redir for older Vim 7 environments

Next

How do I make the = operator use an external formatter instead of Vim's built-in indentation?