How to insert the result of a command into the text in vim?

You can use the expression register, "=, with p (or P) in normal mode or <C-R> in insert mode:

In normal mode:
(<C-M> here means Control+M, or just press Enter/Return)

"=strftime('%c')<C-M>p

In insert mode:
(<C-M> has the same meaning as above, <C-R> means Control+R)

<C-R>=strftime('%c')<C-M>

If you want to insert the result of the same expression many times, then you might want to map them onto keys in your .vimrc:
(here the <C-M> and <C-R> should be typed literally (a sequence of five printable characters—Vim will translate them internally))

:nmap <F2> "=strftime('%c')<C-M>p
:imap <F2> <C-R>=strftime('%c')<C-M>

:r!date +\%c

see :help :r!

Note, this is for external commands (they run in your shell), not vim commands.


If you want to insert the output of a vim command (as opposed to the return value of a function call or an expression), you have to capture it. This is accomplished via the :redir command, which allows you to redirect vim's equivalent of standard output into a variable, file, register, or other target.

:redir is sort of painfully inconvenient to use; I would write a function to encapsulate its functionality in a more convenient way, something like

funct! Exec(command)
    redir =>output
    silent exec a:command
    redir END
    return output
endfunct!

Once you've declared such a function, you can use the expression register (as explained by Chris Johnsen) to insert the output of a command at the cursor position. So, from normal mode, hit i^R=Exec('ls') to insert the list of vim's current buffers.

Be aware that the command will execute in the function namespace, so if you use a global variable you will have to explicitly namespace it by prefixing it with g:. Also note that Exec(), as written above, will append a terminating newline to even one-line output. You might want to add a call to substitute() into the function to avoid this.

Also see https://stackoverflow.com/questions/2573021/vim-how-to-redirect-ex-command-output-into-current-buffer-or-file/2573054#2573054 for more blathering on about redir and a link to a related command.

Tags:

Vim