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

时间:2013-08-10 20:17:37

标签: python vim

Here is some text
here is line two of text

我在Vim中从isis直观地选择:(括号代表视觉选择[ ]

Here [is some text
here is] line two of text

使用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

我来源此文件::so %,直观地选择文字,运行:<,'>call GetRange()

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

is some text\nhere is

很高兴:

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

3 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:4)

如果您使用纯vimscript

,这可能会有效
function! GetRange()
    let @" = substitute(@", '\n', '\\n', 'g')
endfunction

vnoremap ,r y:call GetRange()<CR>gvp

这会在视觉选择中将所有换行转换为\n,并用该字符串替换选择。

此映射将选择内容放入"寄存器。调用函数(因为它只有一个命令,所以不是必需的)。然后使用gv重新选择视觉选择,然后将引用寄存器粘贴回选定的区域。

注意:在vimscript中,所有用户定义的函数都必须以大写字母开头。

答案 2 :(得分:2)

这是基于Conner答案的另一个版本。我接受了qed的建议,并在选择完全在一行内时添加了修复。

import vim

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