在vim中应用于选择的函数

2024-06-30 08:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

当vim在ssh会话中运行时,我正在编写一个删除所选文本(以特殊方式)的函数:

python << EOF
def delSelection():
    buf = vim.current.buffer
    (lnum1, col1) = buf.mark('<')
    (lnum2, col2) = buf.mark('>')

    # get selected text
    # lines = vim.eval('getline({}, {})'.format(lnum1, lnum2))
    # lines[0] = lines[0][col1:]
    # lines[-1] = lines[-1][:col2+1]
    # selected =  "\n".join(lines) + "\n"
    # passStrNc(selected)

    # delete selected text
    lnum1 -= 1
    lnum2 -= 1
    firstSeletedLine = buf[lnum1]
    firstSeletedLineNew = buf[lnum1][:col1]
    lastSelectedLine = buf[lnum2]
    lastSelectedLineNew = buf[lnum2][(col2 + 1):]
    newBuf = ["=" for i in range(lnum2 - lnum1 + 1)]
    newBuf[0] = firstSeletedLineNew
    newBuf[-1] = lastSelectedLineNew
    print(len(newBuf))
    print(len(buf[lnum1:(lnum2 + 1)]))
    buf[lnum1:(lnum2 + 1)] = newBuf

EOF


function! DelSelection()
python << EOF
delSelection()
EOF
endfunction

python << EOF
import os
sshTty = os.getenv("SSH_TTY")
if sshTty:
    cmd6 = "vnoremap d :call DelSelection()<cr>"
    vim.command(cmd6)
EOF

显然,vim在所选的每一行上都调用函数,这破坏了函数的整体目的。我应该如何正确地做到这一点?你知道吗


Tags: 函数textvimcol2col1marklinesselected
2条回答

好的,我知道了。我只需要在调用函数之前添加一个Esc键:

python << EOF
import os
sshTty = os.getenv("SSH_TTY")
if sshTty:
    cmd6 = "vnoremap d <esc>:call DelSelection()<cr>"
    vim.command(cmd6)
EOF

这是因为:在以可视模式发出时会自动插入'<,'>范围。清除的标准方法是在映射前面加<C-u>

cmd6 = "vnoremap d :<C-u>call DelSelection()<cr>"

或者,也可以将range关键字附加到:function定义cp.:help a:firstline。你知道吗

相关问题 更多 >