- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathautoexpand.py
96 lines (85 loc) · 3.14 KB
/
autoexpand.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'''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
the cycle starts again.
Changing the current text line or leaving the cursor in a different
place before requesting the next selection causes AutoExpand to reset
its state.
There is only one instance of Autoexpand.
'''
importre
importstring
classAutoExpand:
wordchars=string.ascii_letters+string.digits+"_"
def__init__(self, editwin):
self.text=editwin.text
self.bell=self.text.bell
self.state=None
defexpand_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")
ifnotself.state:
words=self.getwords()
index=0
else:
words, index, insert, line=self.state
ifinsert!=curinsertorline!=curline:
words=self.getwords()
index=0
ifnotwords:
self.bell()
return"break"
word=self.getprevword()
self.text.delete("insert - %d chars"%len(word), "insert")
newword=words[index]
index= (index+1) %len(words)
ifindex==0:
self.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"break"
defgetwords(self):
"Return a list of words that match the prefix before the cursor."
word=self.getprevword()
ifnotword:
return []
before=self.text.get("1.0", "insert wordstart")
wbefore=re.findall(r"\b"+word+r"\w+\b", before)
delbefore
after=self.text.get("insert wordend", "end")
wafter=re.findall(r"\b"+word+r"\w+\b", after)
delafter
ifnotwbeforeandnotwafter:
return []
words= []
dict= {}
# search backwards through words before
wbefore.reverse()
forwinwbefore:
ifdict.get(w):
continue
words.append(w)
dict[w] =w
# search onwards through words after
forwinwafter:
ifdict.get(w):
continue
words.append(w)
dict[w] =w
words.append(word)
returnwords
defgetprevword(self):
"Return the word prefix before the cursor."
line=self.text.get("insert linestart", "insert")
i=len(line)
whilei>0andline[i-1] inself.wordchars:
i=i-1
returnline[i:]
if__name__=='__main__':
fromunittestimportmain
main('idlelib.idle_test.test_autoexpand', verbosity=2)