9

I've read lots of threads about running shell commands from vim, lots of documentation on vim commands, .vimrc and all that, but I just can't seem to understand the "ex" language or vim mappings well enough to do what I want, so here I am asking this question. Here goes:

I have an open buffer in vim (using the latest stable MacVim on Snow Leopard, but not in gui mode) whose contents I will later feed into a command-line tool that will process it and give me some output. What I want is to be able to:

  1. Press a key (or key combination, or issue a vi command)
  2. Run my command-line utility with the contents of my current buffer (which might not be saved to the file) piped into it
  3. Capture its output and show it in vim, preferrably in a new split window (like :help does)

So, in summary: I can run

$ cat ~/myinput.txt | myScript > output.txt

But I want to do something like that inside of vim, putting the output in a new split window if possible.

UPDATE:
Of course, just after posting, I found some more information on the subject. I now know that I can do this inside vim:

:%! myScript

And it will put the output of myScript (with the buffer contents piped to it) into my current buffer, replacing whatever I have in it right now.

So is there a way to put these contents into a new, split window, buffer? Thanks!

4 Answers 4

7

I would put something like this in my ~/.vimrc or a file with the .vim extension in ~/.vim/plugin/:

command! FW call FilterToNewWindow('myscript')

function! FilterToNewWindow(script)
    let TempFile = tempname()
    let SaveModified = &modified
    exe 'w ' . TempFile
    let &modified = SaveModified
    exe 'split ' . TempFile
    exe '%! ' . a:script
endfunction

Then you can just do ":FW".

It might be a good idea to change the command definition to require a filter script name argument to pass to the function instead of "hard coding" it.

1
  • This worked, thanks! I'll see about the parameters later, lots to learn about scripting vim. Thank you for your help.
    – malvim
    Apr 6, 2011 at 22:38
0

The function from @Heptite, made more generic:

function! FilterToNewWindow()
    let TempFile = tempname()
    let SaveModified = &modified
    exe 'w ' . TempFile
    exe '!chmod +x ' . TempFile
    let &modified = SaveModified
    exe ':e ' . TempFile
    exe '%! ' . @%
   exe 'w!'
endfunction

" bash execute contents of current buffer and filter it to a new window
command! FW call FilterToNewWindow()

```

0

This command will do half of what you want.

map <Leader>r :!%:p<cr>

The current buffer has to be an executable with a shebang line for this to work.

0

There’s a plugin that does this quite nicely

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .