繁体   English   中英

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

[英]How to get the word below cursor and update it in Python Gedit plugin

我正在尝试编写一个Gedit 3插件,我想在其中找到当前光标下方的单词并对其进行修改。 我尝试查看现有的插件,但没有发现任何类似的事情。

任何帮助都会很棒。

以下代码基于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) )来更改单词。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM