如何获取光标下方的单词并在Python Gedit插件中更新它

时间:2012-02-29 13:21:55

标签: python plugins gtk gedit

我正在尝试编写一个Gedit 3插件,我希望在当前光标下方获取该字并修改它。我试着查看现有的插件,但没有发现任何类似的东西。

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

以下代码,基于gedit-improving-plugins的line-tools插件,获取所选单词

# help functions
def valid_text(start, end):
    if not start or not end:
        return False
    if start.get_line_offset() > end.get_line_offset():
        (start, end) = (end, start) # swap
    text = doc.get_text(start, end, False)
    for char in text:
        if not re.match("\w", char):
            return False
    return True
def increment(index, incr):
    newindex = index.copy()
    newindex.set_line_offset(index.get_line_offset() + incr)
    return newindex
def find_word_bound(index, step):
    condition = lambda x: not index.get_line_offset() == 0 if step < 0 else lambda x: not x.ends_line()
    while condition(index):
        newindex = increment(index, step)
        # newindex contains word?
        if not valid_text(newindex, index):
            break
        # save new index
        index = newindex
    return index
# get vars
cursor = doc.get_iter_at_mark(doc.get_insert())
start = find_word_bound(cursor, -1)
end = find_word_bound(cursor, +1)
word = doc.get_text(start, end, False)

在此之后,您可以通过删除它来更改单词(doc.delete(begin, end)),设置光标(doc.place_cursor(place))并在光标处插入新单词(doc.insert_at_cursor(str)