How do I capture the output of a Vim command into a register or buffer?
Answer
:redir @a | {cmd} | redir END
Explanation
The :redir command redirects the output of Ex commands to a register, file, or variable instead of displaying it on the screen. This lets you capture command output and then paste, search, or manipulate it like regular text — turning Vim's informational messages into actionable data.
How it works
:redir @astarts redirecting all subsequent command output into registera- Run any Ex commands that produce output (
:ls,:marks,:hi,:map, etc.) :redir ENDstops the redirection- Now
"appastes the captured output into your buffer
You can redirect to different targets:
:redir @a " redirect to register a
:redir @+ " redirect to system clipboard
:redir > file " redirect to a file (overwrite)
:redir >> file " redirect to a file (append)
:redir => var " redirect to a Vimscript variable
Example
Capture the output of :marks into register a and paste it:
:redir @a
:marks
:redir END
"ap
Your buffer now contains the full marks listing, which you can search, edit, or save.
Capture all key mappings for documentation:
:redir @m
:map
:redir END
"mp
A modern alternative
Vim 8+ provides execute() which is often simpler for one-off captures:
:put =execute('ls')
This inserts the output of :ls directly into the buffer without the :redir ceremony. You can use it with any command:
:put =execute('marks')
:put =execute('highlight')
:put =execute('version')
Tips
- Use
:redir @A(uppercase) to append to registerainstead of overwriting it — useful for capturing output from multiple commands - Always remember to run
:redir ENDwhen you are done — forgetting it causes all subsequent command output to keep accumulating in the register :put =execute('scriptnames')is a quick way to see all loaded scripts in an editable buffer- Combine with
:silentto suppress output from appearing on screen during redirection::silent map - Use
:redir => g:outputto capture into a variable for use in Vimscript functions or conditionals - The
execute()function can be nested inside other expressions::echo len(split(execute('ls'), "\n"))counts the number of open buffers