简体   繁体   English

vim:使用选定的行作为python函数的输入

[英]vim: use selected line as input of a python function

I am quite newbie in vim. 我是vim的新手。 What I want to achieve is that vim will return the output of a python function in my text file. 我想要实现的是vim将在我的文本文件中返回python函数的输出。 The idea is that I select a part of text and press F5 and get the output. 我的想法是我选择一部分文本并按F5并获得输出。 The complication is that this function is part of a library and I have to import it. 复杂的是,这个函数是库的一部分,我必须导入它。 I tried this 我试过这个

command MyPythonFunction execute "!python from Bio.Seq import reverse_complement; reverse_complement(%)"
map <F5> :MyPythonFunction<CR>

and I get "no range allowed" 我得到“不允许范围”

Selected lines are passed to stdin of the command. 选定的行传递给命令的stdin。 So read it using sys.stdin.read() 所以使用sys.stdin.read()读取它

fun! ReverseComplement()
    exec ":'<,'>! python -c \"import sys, Bio.Seq; print Bio.Seq.reverse_complement(sys.stdin.read().rstrip())\""
endfun

vnoremap <F5> :call ReverseComplement()<CR>

EDIT 编辑

pass a part of a line: 传递一部分线:

vnoremap <F5> d:let @a=system('python -c "import sys, Bio.Seq; sys.stdout.write(Bio.Seq.reverse_complement(\"' . @" . '\"))"')<CR>"aP
  • d -> delete selected part. d - >删除所选部分。 side effect: content of register " changed. 副作用:登记内容"改变了。
  • @" : content of register " (cut contents) @" :注册内容" (剪切内容)
  • . : binary operator that concatenate strings. :连接字符串的二元运算符。
  • let @a = system(..) : Execute external command, and save its output to a register. let @a = system(..)执行外部命令,并且它的输出保存到a寄存器中。
  • "aP: Paste content of a register before current cursor position. “AP:粘贴的内容a当前光标位置之前寄存器。

First of all, you are going to need** write your python parts in such a manner that the data is read from stdin and then output to stdout. 首先,您将需要以这样的方式编写您的python部分,即从stdin读取数据然后输出到stdout。 You can then apply your code in following style: 然后,您可以按以下样式应用代码:

fun! DoMyPythonThing() range
    exec ":'<,'>! python ./path/to/your/script.py"
endfun

vnoremap <F3> :call DoMyPythonThing()<CR>

The idea behind ex's command :! ex命令背后的想法:! is that you give it an executable program, and vim pipes the visualized text to it and replaces the region with the ouput of the program. 是你给它一个可执行程序,vim将可视化文本传递给它,并用程序的输出替换该区域。

Note the range there in the function definition. 请注意函数定义中的range Note about the mapping that we restrict ourselves in visual mode mappings only. 请注意我们仅在可视模式映射中限制自己的映射。 If you like to wave the mouse as well, consider mapping in selection mode as well. 如果您也想挥动鼠标,请考虑在选择模式下进行映射。

**) Well, it's possible to write in-vim python to perform this, but that's harder to test and you went with the external-program route by calling ! **)嗯,可以编写in-vim python来执行此操作,但是这很难测试,你通过调用你去了外部程序路线! anyway. 无论如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM