Tags: #vim #stdin
Note: for full details, read https://vimways.org/2018/vims-social-life/
Vim doesn’t handle stdin like other posix commands…
$ echo foo | vim
Vim: Warning: Input is not from a terminal
Vim: Error reading input, exiting...
Vim: Finished.
If you pass -
to vim, then it will accept the stdin and copy it to a new buffer…
$ echo foo | vim -
Before we look ahead at how to handle stdin a bit better, let’s consider the +
flag which tells vim what line to start on (the following example tells vim to jump to line 10):
$ vim ~/.vimrc +10
This will become relevant when we look at two other flags -e
and -s
(see vim -h
for more information on available flags)…
$ echo foo | vim - -es +'%p' +'qa!'
Vim: Reading from stdin...
foo
When using the -e
and -s
flags, we’re able to use +
to execute Ex mode commands (see :help -s-ex
).
Note: if you don’t use
+'qa!'
then vim will cause the terminal to hang (you also need the!
otherwiseqa
would – if dealing with a traditional vim UI – show a message saying the buffer has been edited and can’t be quite).
To avoid the Vim: Reading from stdin...
message we need an additional flag --not-a-term
:
$ echo foo | vim - -es +'%p' +'qa!' --not-a-term
foo
So now if we want to manipulate the content (let’s say uppercase the word foo
to FOO
) we can do:
$ echo foo | vim - -es --not-a-term +'norm VgU' +'%p' +'qa!'
FOO
Note:
norm
says execute the following characters as if the user is typing them, soV
selects the entire line andgU
uppercases the selection. We then print the output to stdout%p
and then quit without trying to save the modifications.