Evaluate ruby (or any command) and insert into Vim buffers

Something I commonly want to do is evaluate a bit of code and insert the result into my Vim window. For example, if I want to generate a 40-character UID, I could use ruby's SecureRandom class:

require 'securerandom'
puts SecureRandom.hex(40)

As you'll probably know you can run ruby code directly from Vim, as a command:

:ruby require 'securerandom'; puts SecureRandom.hex(40)

This prints it out, but doesn't do anything else with the output. However, we can capture the output of any command and add it into a register. We can then use that register to modify our current buffer. Here's a quick function I wrote to do that:

function! InsertCommand(command)
    redir => output
    silent execute a:command
    redir END
    call feedkeys('i'.substitute(output, '^[\n]*\(.\{-}\)[\n]*$', '\1', 'gm'))

Firstly, this redirects all output into the output register. Then, it executes whichever command has been passed as an argument. It then stops the redirection and inserts the register into the current cursor position (after stripping all surrounding whitespace and new lines).

This allows us to capture the output of any command, e.g.:

:call InsertCommand("ruby require 'securerandom'; puts SecureRandom.hex(40)")

We can make this more manageable by registering a command:

command -nargs=+ Iruby call InsertCommand("ruby " . <q-args>)

That allows us to use:

:Iruby require 'securerandom'; puts SecureRandom.hex(40)

And we can make it generic by adding a command I:

command -nargs=+ I call InsertCommand(<q-args>)

Which allows us to execute any vim command and insert the output into the buffer:

:I echo "WIN"

Job done - no need for a plugin.

← Previous post: Monit style alerts for Systemd Next post: Looking for another vdebug maintainer →
comments powered by Disqus