Posted on Wed, 20 Jan 2016 by adamlamers
I discovered this trick while trying to do some quick investigation in Vim, and
not wanting to have to leave the editor, found a way to quickly replace Python
code (or anything you can pipe to an external command) with it's output in Vim.
What you do is, write the code inside a buffer, then select it in visual mode.
Once it's selected, press : and you will get Vim's
:'<,'> range, which
means all the text between the beginning and end of the visual cursor.
Say, for example I want to do some checking on where the position of a particular character is in a string. I could do this:
print([i for i, c in enumerate('ABCDQQFGHQQIQJ') if c == 'Q'])
Then select the line it's on by pressing V, then press : and execute
and it will be replaced with
[4, 5, 9, 10, 12] inline.
It's also useful for multiline things, such as using requests to pull a webpage into your buffer.
import requests print(requests.get("http://api.ipify.org").text)
Select both lines with V, then execute them and the code will be replaced by your external IP address.
You can pretty much do this trick with any standard-output-writing program. So, you could do it with shell scripts, lua, node, php anything you want.
I just realized while writing this how cool it is to write a query and have it replaced by the data:
SELECT * FROM lottery_drawings LIMIT 5;
:'<,'>!sqlite3 -header /Users/adam/code/lottery_data.sqlite3 becomes:
date|numbers|hash|lottery_name 2015-10-15 00:00:00|38-7-42-15-18 9|4f33b4f41656d17cc4707ad52245cf0d|Lucky For Life 2015-10-12 00:00:00|7-37-43-48-4 5|918dcc8d28314189c52d85c899812e86|Lucky For Life 2015-10-08 00:00:00|8-21-48-42-1 4|1c804ff089ed12ecd6eab4f8ad9e39f0|Lucky For Life 2015-10-05 00:00:00|48-28-41-31-8 5|fb3c0624dbca146a24b4103ee227f10a|Lucky For Life 2015-10-01 00:00:00|33-4-41-46-24 4|9714ff834aaa654c019ff0ad0607a4dc|Lucky For Life
If you're going to use this a lot, you might think about rebinding a key in visual mode to do your
most common operation. Just place this line in your vimrc, replacing 'python' with the command you
want to execute, and
vnoremap <F5> :!python<CR>