如何用Python脚本修改Vim缓冲区?

5 投票
2 回答
2271 浏览
提问于 2025-04-16 18:29

官方的Vim Python接口文档上说,用Python修改缓冲区是非常简单的,基本上就是这样:

:py import vim
:py vim.current.buffer[0] = "Hello world"

但是,当我尝试这样做时,Python却抛出了一个异常:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: bad argument type for built-in operation

只读访问(比如 :py print vim.current.buffer[0] 这样是可以正常工作的。我是不是漏掉了什么?为什么我不能用Python脚本修改Vim的缓冲区呢?

[注意:我使用的是最近的Vim 7.3]

2 个回答

0

这可能是编码的问题。我遇到过一个非常相似(但不完全相同)的情况,比如在一个vim的python函数里:

buf = vim.current.buffer
names = [x.name for x in triggers] #encoded as a default python unicode, e.g. u'foo'
names = [x.encode('utf-8') for x in names] # Force to utf-8
buf[:] = names #Now this works.

如果不强制把它转换成utf-8,我会遇到同样的错误。我觉得这个问题和vim处理python默认的(对我来说是)us-ascii字符串的方式有关。转换成utf-8后就没问题了。希望这能帮到你。

3

对我来说没问题,“Hello World”已经插入到缓冲区了。你的vim是用+python编译的吗?

我用的是7.3.162版本。

编辑

在hg日志中查看if_python.c时,我看到很多和python相关的问题,比如这个:

changeset:   2641:b803b2776880
tag:         v7-3-062
user:        Bram Moolenaar <bram@vim.org>
date:        Tue Nov 16 19:26:02 2010 +0100
files:       src/auto/configure src/configure.in src/if_python.c src/if_python3.c src/version.c
description:
updated for version 7.3.062
Problem:    Python doesn't work properly when installed in another directory
        than expected.
Solution:   Figure out home directory in configure and use Py_SetPythonHome()
        at runtime. (Roland Puntaier)

你用的是什么版本?

撰写回答