Vim使用Python在视觉选择范围之间获取字符串

tes*_*ter 7 python vim

Here is some text
here is line two of text
Run Code Online (Sandbox Code Playgroud)

我从视觉上选择isis在Vim中:(括号表示可视选择[ ])

Here [is some text
here is] line two of text
Run Code Online (Sandbox Code Playgroud)

使用Python,我可以获得选择的范围元组:

function! GetRange()
python << EOF

import vim

buf   = vim.current.buffer # the buffer
start = buf.mark('<')      # start selection tuple: (1,5)
end   = buf.mark('>')      # end selection tuple: (2,7)

EOF
endfunction
Run Code Online (Sandbox Code Playgroud)

我获取此文件::so %,直观地选择文本,运行:<,'>call GetRange()

现在我已经(1,5)(2,7).在Python中,如何编译以下字符串:

is some text\nhere is

会很高兴:

  1. 获取此字符串以供将来操作
  2. 然后用更新/操作的字符串替换此选定范围

Con*_*ner 8

试试这个:

fun! GetRange()
python << EOF

import vim

buf = vim.current.buffer
(lnum1, col1) = buf.mark('<')
(lnum2, col2) = buf.mark('>')
lines = vim.eval('getline({}, {})'.format(lnum1, lnum2))
lines[0] = lines[0][col1:]
lines[-1] = lines[-1][:col2]
print "\n".join(lines)

EOF
endfun
Run Code Online (Sandbox Code Playgroud)

您可以使用vim.eval获取vim函数和变量的python值.

  • 我认为`line [-1] [:col2 + 1]`会更方便. (2认同)