'''Complete the current word before the cursor with words in the editor.Each menu selection or shortcut key selection replaces the word with adifferent word with the same prefix. The search for matches beginsbefore the target and moves toward the top of the editor. It then startsafter the cursor and moves down. It then returns to the original word andthe cycle starts again.Changing the current text line or leaving the cursor in a differentplace before requesting the next selection causes AutoExpand to resetits state.There is only one instance of Autoexpand.'''import reimport stringclass AutoExpand:wordchars = string.ascii_letters + string.digits + "_"def __init__(self, editwin):self.text = editwin.textself.bell = self.text.bellself.state = Nonedef expand_word_event(self, event):"Replace the current word with the next expansion."curinsert = self.text.index("insert")curline = self.text.get("insert linestart", "insert lineend")if not self.state:words = self.getwords()index = 0else:words, index, insert, line = self.stateif insert != curinsert or line != curline:words = self.getwords()index = 0if not words:self.bell()return "break"word = self.getprevword()self.text.delete("insert - %d chars" % len(word), "insert")newword = words[index]index = (index + 1) % len(words)if index == 0:self.bell() # Warn we cycled aroundself.text.insert("insert", newword)curinsert = self.text.index("insert")curline = self.text.get("insert linestart", "insert lineend")self.state = words, index, curinsert, curlinereturn "break"def getwords(self):"Return a list of words that match the prefix before the cursor."word = self.getprevword()if not word:return []before = self.text.get("1.0", "insert wordstart")wbefore = re.findall(r"\b" + word + r"\w+\b", before)del beforeafter = self.text.get("insert wordend", "end")wafter = re.findall(r"\b" + word + r"\w+\b", after)del afterif not wbefore and not wafter:return []words = []dict = {}# search backwards through words beforewbefore.reverse()for w in wbefore:if dict.get(w):continuewords.append(w)dict[w] = w# search onwards through words afterfor w in wafter:if dict.get(w):continuewords.append(w)dict[w] = wwords.append(word)return wordsdef getprevword(self):"Return the word prefix before the cursor."line = self.text.get("insert linestart", "insert")i = len(line)while i > 0 and line[i-1] in self.wordchars:i = i-1return line[i:]if __name__ == '__main__':from unittest import mainmain('idlelib.idle_test.test_autoexpand', verbosity=2)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。