document updated 12 years ago, on Jul 8, 2012
This is a HACK. (I like hacks :)
Did you know that Vim can be used as a filter, to read things from STDIN, and output to STDOUT?
This page describes how to do this via VimScript
HOWTO: write to STDOUT
It's not possible to do this directly. The only way to do this is to open Vim with a temporary file, have Vim write to that, have the shell read the temporary file, and then delete it.
HOWTO: write to STDERR
HOWTO: read from STDIN
If you specify - as the filename, then it will read the contents of STDIN, and use that as the buffer.
HOWTO: display a Vim variable, and exit
Sometimes you want to know the contents of a Vim variable, from the command-line. How do you do this?
vimpager is a famous example of this.
Steps to do this:
- make sure you start with -e
this avoids the error "Warning: Output is not to a terminal"
- starting it with -X is optional, but a very good idea
- use -c 'echo &some_variable' to actually output what you want
- use -c q to tell Vim to exit at the end
- In the program that calls Vim, you have to strip out the escape characters. There are several ways to do this:
- if you want to look at it manually, during development, use one of these:
- vim ... | cat -v
- vim ... | xxd | cat
- to strip off the escape characters completely, use one of these:
- vim ... | perl -ple 's/\e[^a-z]*[a-z]?//sig'
this strips off all escape characters, but leaves the wonky line-ending of 0D 0D 0A
- vim ... | perl -0777 -ple 's/\e[^a-z]*[a-z]?//sig; s/\x0d\x0d\x0a/\n/sg'
this strips off all escape characters, AND fixes the wonky line-endings
- if you use that a lot, use this shortcut:
alias fixvim="perl -0777 -ple 's/\e[^a-z]*[a-z]?//sig; s/\x0d\x0d\x0a/\n/sg'"
- there are alternate ways to deal with it..
- vim -X -e -c 'echo "ignored" | echo $VIMRUNTIME | q' | awk 'NR>=2&&!/^\033/{print}'
print a throw-away value for the first line, and display the rest of the lines (except for the last line, which is nothing but escape codes)
- vim -X -e -c 'echo "ignored" | echo $VIMRUNTIME | q' | awk 'NR>=2&&!/^\033/{sub(/\r\r$/,"");print}'
same as above, but also fix the broken line-endings
TL;DR:
VIMRUNTIME=$(vim -Xec 'echo "ignored" | echo $VIMRUNTIME | q' | awk 'NR==2{sub(/\r\r$/,"");print}')