Open the output of a shell command in a split pane

23

7

Consider any interpreted programming language.

I can run the currently opened script using ! interpreter %, and use the return key to return to vim after the execution is finished.

Is it somehow possible to not replace the current window with the output of the executed shell command, but open the output in a new split pane instead? I would like to still see my source code during the execution of my script.

I tried :split ! interpreter %, but it didn't work.

Is there a way? I am using vim 7.3.

muffel

Posted 2015-01-24T16:16:22.260

Reputation: 433

Answers

29

With :!, the external command is executed in a shell, and the fleeting output isn't captured inside Vim; you just see what gets printed to the terminal, then control returns to Vim after the external command finishes.

To keep the output, you have to read it into a Vim buffer. For that, there's the :read! command. To open a new scratch buffer, combine this with :new:

:new | 0read ! <command>

If you want to pass the current buffer's filename (%) to the external command, you have to use :execute, so that it is already evaluated in the current buffer:

:execute 'new | 0read ! interpreter' expand('%')

Or, you use the fact that with a new buffer, the previous one becomes the alternate one, and use # instead of %:

:new | 0read ! interpreter #

Get rid of the scratch buffer with :bdelete!.

If you want to see the output asynchronously while it executes, you need an external multiplexer, or a plugin, as mentioned in @chaos answer.

Ingo Karkat

Posted 2015-01-24T16:16:22.260

Reputation: 19 513

The above ":execute ..." command works for me, but when I try to bind it to F9 keystroke, using this .vimrc entry [ nnoremap <buffer> <F9> :execute 'new | 0read !/usr/bin/env python3' expand('%') ], I get the following error: [ /bin/bash: -c: line 0: unexpected EOF while looking for matching `'' expand('%') ]. I tried several escape sequences, but I guess not the right one. =:). Any ideas? Thank you. – NYCeyes – 2016-08-20T23:30:49.927

2

As far as I know, you cannot do that in vim. But use a terminal multiplexer like screen for that. Before opening a vim start the multiplexer:

screen

Then press ctrl-a S for horitzontal and ctrl-a | for a vertical spilt screen.

Now open a file in vim in one of the split screens. And jump to the other screen using ctrl-a tab. Notice that, in the second screen you first have to open a new screen (ctrl-a c) before you can use it.

In the screen with vim you can edit the file and in the other screen you can execute it and see the messages and the code permanently.

Here a quick reference for screen.

chaos

Posted 2015-01-24T16:16:22.260

Reputation: 3 704

Alternatively, you can use tmux multiplexer and vim-dispatch plugin to automate splitting and jumping between panes.

– taketwo – 2015-01-24T17:06:00.200