2008/07/01

python 中实现了entry的多单词自动完成



#!/usr/bin/env python
#coding=utf-8
# a class of completion
import pygtk
import gobject
import gtk
class Completion():
    def __init__(self,Entry,model):
        self.comp= gtk.EntryCompletion()
        Entry.set_completion(self.comp)
        self.comp.set_match_func(self.match_func)
        self.comp.connect("match-selected",self.on_completion_match)
        self.model=model
        self.comp.set_model(model)
        self.comp.set_text_column(0)
        self.Entry=Entry
        Entry.set_completion(self.comp)
        self.comp.set_inline_completion(False)
        self.comp.set_inline_selection(False)
#        self.comp.set_popup_single_match(True)
    def get_comp_point(self):
        str=self.Entry.get_text()
        pos=self.Entry.get_position()
        pos1=str.rfind(" ",0,pos)
        pos2=[str.rfind(" \"",0,pos),str.rfind(" "",0,pos),str.rfind(" "",0,pos),str.rfind(" '",0,pos),str.rfind(" '",0,pos),str.rfind(" '",0,pos)]
        pos3=[str.rfind("\" ",0,pos),str.rfind("" ",0,pos),str.rfind("" ",0,pos),str.rfind("' ",0,pos),str.rfind("' ",0,pos),str.rfind("' ",0,pos)]
        for item in pos2:
            if item>pos2[0]:
                pos2[0]=item
        for item in pos3:
            if item>pos3[0]:
                pos3[0]=item
        if pos2[0]<pos3[0]:
            return pos3[0]
        else:
            return pos1+1
    def match_func(self, completion, key, iter):
        self.pos=self.get_comp_point()
        model = completion.get_model()
        return model[iter][0].startswith(self.Entry.get_text()[self.pos:self.Entry.get_position()])
    def on_completion_match(self, completion, model, iter):
        str=self.Entry.get_text()
        self.Entry.set_text(str[:self.pos]+model[iter][0]+str[self.Entry.get_position():])
        self.Entry.set_position(-1)
        return True
    def add_words(self, words):
        model = self.comp.get_model()
        for word in words:
            model.append([word])