Как получить слово под курсором и обновить его в плагине Python Gedit - PullRequest
0 голосов
/ 29 февраля 2012

Я пытаюсь написать плагин Gedit 3, в котором я хочу получить слово под текущим курсором и изменить его.Я попытался посмотреть на существующие плагины, но не нашел ничего похожего.

Любая помощь будет отличной.

1 Ответ

0 голосов
/ 01 марта 2012

Следующий код, основанный на плагине line-tools gedit -ifying-plugins , получает выбранное слово

# 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))

...