How to invoke vim editor and pipe output to bash
vipe
is a program for editing pipelines:
command1 | vipe | command2
You get an editor with the complete output of command1
, and when you exit, the contents are passed on to command2
via the pipe.
In this case, there's no command1
. So, you could do:
: | vipe | pandoc -o foo.pdf
Or:
vipe <&- | pandoc -o foo.pdf
vipe
picks up on the EDITOR
and VISUAL
variables, so you can use those to get it to open Vim.
If you've not got it installed, vipe
is available in the moreutils
package; sudo apt-get install moreutils
, or whatever your flavour's equivalent is.
You can do this from within Vim:
:w !pandoc -o file.pdf
Or even write the buffer into a complex pipeline:
:w !grep pattern | somecommand > file.txt
And then you can exit Vim without saving:
:q!
However, considering your specific use case, there is probably a better solution by using vi
as your command line editor. Assuming you use bash
:
set -o vi
This sets your keybindings to vi
. So you can edit your commands right on the command line with basic vi
keybindings by pressing <Esc>
and then typing vi
commands such as x
, cw
, etc. (You can get back in insert mode by pressing i
.)
Even better, and more relevant to this question, you can open Vim to create your command line content directly. Just type <Esc>v
and you will get an empty Vim buffer. When you save and exit, that is the command on your command line and it is immediately run. This is much much more flexible than editing on the command line directly as you can write a whole mini-script if you want.
So, for example, if you want to write some tricky text and pipe it into pandoc immediately, you could just type:
<Esc>v
Then edit the Vim buffer until you have something like:
cat <<EOF | pandoc -o file.pdf
stuff for pandoc
more stuff for pandoc
EOF
Then save and exit (with :x
) and the whole thing will be run as a shell command.
It will also be available in your shell's command history.
Running in a pipeline
Try:
quickedit() ( trap 'rm ~/temp$$' exit; vim ~/temp$$ >/dev/tty; cat ~/temp$$ )
The key is that, to be able to use vim
normally, vim
needs stdout to be the terminal. We accomplish that here with the redirect >/dev/tty
.
For purposes of security, I put the temporary file in the user's home directory. For more on this, see Greg's FAQ Question 062. This eliminates the need to use an obscure file name.
Example:
When vim
opens, I type This function succeeded.
and save the file. The result on the screen looks like:
$ quickedit | grep succeeded
This function succeeded.
Even though the output of quickedit
is redirected to a pipeline, vim
still works normally because we have given it direct access to /dev/tty
.
Running a program from within vim
As I mentioned in the comments, vim can pipe a file to a command. From within vim, for example, issue the command :w !pandoc -o file.pdf
(Note: the space between w and ! is essential).