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:messagesoutput directly into registera: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
:putto 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 —:redircould cause recursion issues in those contexts - Available in Vim 8.0+; use
:redirfor older Vim 7 environments