ms123
ms123

Reputation: 581

Load a vim buffer into a ruby variable

I'm looking for a way to retrieve what has been entered in vim and load it in a ruby variable.

User type:

myProgram -m

Then Vim appears. Whenever the user quit Vim, "myProgram" retrieves the user's input.

I tried doing something (naive)

message = `vim`

However, I get "Vim: Warning: Output is not to a terminal"

Thank you very much

Upvotes: 0

Views: 466

Answers (4)

the Tin Man
the Tin Man

Reputation: 160631

If you can work with gVim or MacVim, you can use the -f flag:

-f or --nofork    Foreground: Don't fork when starting GUI

which will make your Ruby code pause while the app (either gvim or MacVim) is running.

Grabbing the content of the editor is a bit more complex, but easily handled by your code pre-creating a temp file as a stub, and passing that to Vim when its launched. Edit away, save the buffer, then quit the editor. When control returns to Ruby open the file again and read its contents into a variable.

You'll notice that happening on Linux if you set your environment EDITOR variable to vim, and edit a command-line or tell SVN to use it for its svn diff command.

Upvotes: 1

dunedain289
dunedain289

Reputation: 2388

You should just need to write out your data so far to a temporary filename, then run something like system(ENV["EDITOR"], tmpfile), then read tmpfile back in. I suggest using the EDITOR or VISUAL environment variables, people set those to preferred editors for programs to use (ie if someone prefers Emacs and can't even exit Vim, they won't get confused).

Upvotes: 1

Drasill
Drasill

Reputation: 4016

You should look at how the "visudo", "vipw"... commands manage it (on linux).

Upvotes: 0

yan
yan

Reputation: 20992

When inside vim, you can run :%!your_program and your_program will be invoked with the current buffer as it's stdin.

Upvotes: 2

Related Questions