'''Complete the current word before the cursor with words in the editor.
Each menu selection or shortcut key selection replaces the word with a
different word with the same prefix. The search for matches begins
before the target and moves toward the top of the editor. It then starts
after the cursor and moves down. It then returns to the original word and
Changing the current text line or leaving the cursor in a different
place before requesting the next selection causes AutoExpand to reset
This is an extension file and there is only one instance of AutoExpand.
###$ event <<expand-word>>
('E_xpand Word', '<<expand-word>>'),
wordchars = string.ascii_letters + string.digits + "_"
def __init__(self, editwin):
def 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")
words, index, insert, line = self.state
if insert != curinsert or line != curline:
word = self.getprevword()
self.text.delete("insert - %d chars" % len(word), "insert")
index = (index + 1) % len(words)
self.text.bell() # Warn we cycled around
self.text.insert("insert", newword)
curinsert = self.text.index("insert")
curline = self.text.get("insert linestart", "insert lineend")
self.state = words, index, curinsert, curline
"Return a list of words that match the prefix before the cursor."
word = self.getprevword()
before = self.text.get("1.0", "insert wordstart")
wbefore = re.findall(r"\b" + word + r"\w+\b", before)
after = self.text.get("insert wordend", "end")
wafter = re.findall(r"\b" + word + r"\w+\b", after)
if not wbefore and not wafter:
# search backwards through words before
# search onwards through words after
"Return the word prefix before the cursor."
line = self.text.get("insert linestart", "insert")
while i > 0 and line[i-1] in self.wordchars:
if __name__ == '__main__':
unittest.main('idlelib.idle_test.test_autoexpand', verbosity=2)