How can you use Python in Vim?


Question

I waste a lot of time between Vim and Python. I find it too slow to manually copy-paste from Python to Vim and vice versa. A good broken example is:

%!python for i in xrange(25); print 6*i \n

How can you do such tweaks direcly in Vim? [Solved]

[Clarification] I need things to Vim, like printing sequences, arithmetics... - things I cannot do in Vim.

[?] Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given (., %, ...)."

[Further Clarification]

If I want to print 'Hello' to lines 4,5, 6 and 7, what is wrong:

:4-7!python -c "print 'hello'"

The dot . modifies the current line. Can I print on multiple lines 7, 32 and 99:

:7,32,99!python -c "print 'hello'"

Clearly not working. How?

1
51
2/1/2009 10:16:10 PM

Accepted Answer

In any of your vim windows, type something like this:

for x in range(1,10):
    print '-> %d' % x

Visually select both of those lines (V to start visual mode), and type the following:

:!python

Because you pressed ':' in visual mode, that will end up looking like:

:'<,'>!python

Hit enter and the selection is replaced by the output of the print statements. You could easily turn it into a mapping:

:vnoremap <f5> :!python<CR>
164
2/1/2009 10:17:12 PM

Can someone elaborate this point: "your script can read from stdin to operate directly on the lines given (., %, ...)."

One common use is to sort lines of text using the 'sort' command available in your shell. For example, you can sort the whole file using this command:

:%!sort

Or, you could sort just a few lines by selecting them in visual mode and then typing:

:!sort

You could sort lines 5-10 using this command:

:5,10!sort

You could write your own command-line script (presuming you know how to do that) which reverses lines of text. It works like this:

bash$ myreverse 'hello world!'
!dlrow olleh

You could apply it to one of your open files in vim in exactly the same way you used sort:

:%!myreverse      <- all lines in your file are reversed

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon