blob: d02a69539aede838690586b085674059194efc5b [file] [log] [blame]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001"""
2An auto-completion window for IDLE, used by the AutoComplete extension
3"""
4from Tkinter import *
5from MultiCall import MC_SHIFT
6import AutoComplete
7
8HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
9HIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
10KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
11# We need to bind event beyond <Key> so that the function will be called
12# before the default specific IDLE function
13KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>",
14 "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>")
15KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
16KEYRELEASE_SEQUENCE = "<KeyRelease>"
17LISTUPDATE_SEQUENCE = "<ButtonRelease>"
18WINCONFIG_SEQUENCE = "<Configure>"
19DOUBLECLICK_SEQUENCE = "<Double-ButtonRelease>"
20
21class AutoCompleteWindow:
22
23 def __init__(self, widget):
24 # The widget (Text) on which we place the AutoCompleteWindow
25 self.widget = widget
26 # The widgets we create
27 self.autocompletewindow = self.listbox = self.scrollbar = None
28 # The default foreground and background of a selection. Saved because
29 # they are changed to the regular colors of list items when the
30 # completion start is not a prefix of the selected completion
31 self.origselforeground = self.origselbackground = None
32 # The list of completions
33 self.completions = None
34 # A list with more completions, or None
35 self.morecompletions = None
36 # The completion mode. Either AutoComplete.COMPLETE_ATTRIBUTES or
37 # AutoComplete.COMPLETE_FILES
38 self.mode = None
39 # The current completion start, on the text box (a string)
40 self.start = None
41 # The index of the start of the completion
42 self.startindex = None
43 # The last typed start, used so that when the selection changes,
44 # the new start will be as close as possible to the last typed one.
45 self.lasttypedstart = None
46 # Do we have an indication that the user wants the completion window
47 # (for example, he clicked the list)
48 self.userwantswindow = None
49 # event ids
50 self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
51 = self.keyreleaseid = self.doubleclickid = None
52
53 def _change_start(self, newstart):
54 i = 0
55 while i < len(self.start) and i < len(newstart) and \
56 self.start[i] == newstart[i]:
57 i += 1
58 if i < len(self.start):
59 self.widget.delete("%s+%dc" % (self.startindex, i),
60 "%s+%dc" % (self.startindex, len(self.start)))
61 if i < len(newstart):
62 self.widget.insert("%s+%dc" % (self.startindex, i),
63 newstart[i:])
64 self.start = newstart
65
66 def _binary_search(self, s):
67 """Find the first index in self.completions where completions[i] is
68 greater or equal to s, or the last index if there is no such
69 one."""
70 i = 0; j = len(self.completions)
71 while j > i:
72 m = (i + j) // 2
73 if self.completions[m] >= s:
74 j = m
75 else:
76 i = m + 1
77 return min(i, len(self.completions)-1)
78
79 def _complete_string(self, s):
80 """Assuming that s is the prefix of a string in self.completions,
81 return the longest string which is a prefix of all the strings which
82 s is a prefix of them. If s is not a prefix of a string, return s."""
83 first = self._binary_search(s)
84 if self.completions[first][:len(s)] != s:
85 # There is not even one completion which s is a prefix of.
86 return s
87 # Find the end of the range of completions where s is a prefix of.
88 i = first + 1
89 j = len(self.completions)
90 while j > i:
91 m = (i + j) // 2
92 if self.completions[m][:len(s)] != s:
93 j = m
94 else:
95 i = m + 1
96 last = i-1
97
98 # We should return the maximum prefix of first and last
99 i = len(s)
100 while len(self.completions[first]) > i and \
101 len(self.completions[last]) > i and \
102 self.completions[first][i] == self.completions[last][i]:
103 i += 1
104 return self.completions[first][:i]
105
106 def _selection_changed(self):
107 """Should be called when the selection of the Listbox has changed.
108 Updates the Listbox display and calls _change_start."""
109 cursel = int(self.listbox.curselection()[0])
110
111 self.listbox.see(cursel)
112
113 lts = self.lasttypedstart
114 selstart = self.completions[cursel]
115 if self._binary_search(lts) == cursel:
116 newstart = lts
117 else:
118 i = 0
119 while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]:
120 i += 1
Kurt B. Kaiser1df323a2008-02-14 04:02:10 +0000121 previous_completion = self.completions[cursel - 1]
122 while cursel > 0 and selstart[:i] <= previous_completion:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000123 i += 1
Kurt B. Kaiser1df323a2008-02-14 04:02:10 +0000124 if selstart == previous_completion:
125 break # maybe we have a duplicate?
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000126 newstart = selstart[:i]
127 self._change_start(newstart)
128
129 if self.completions[cursel][:len(self.start)] == self.start:
130 # start is a prefix of the selected completion
131 self.listbox.configure(selectbackground=self.origselbackground,
132 selectforeground=self.origselforeground)
133 else:
134 self.listbox.configure(selectbackground=self.listbox.cget("bg"),
135 selectforeground=self.listbox.cget("fg"))
136 # If there are more completions, show them, and call me again.
137 if self.morecompletions:
138 self.completions = self.morecompletions
139 self.morecompletions = None
140 self.listbox.delete(0, END)
141 for item in self.completions:
142 self.listbox.insert(END, item)
143 self.listbox.select_set(self._binary_search(self.start))
144 self._selection_changed()
145
146 def show_window(self, comp_lists, index, complete, mode, userWantsWin):
147 """Show the autocomplete list, bind events.
148 If complete is True, complete the text, and if there is exactly one
149 matching completion, don't open a list."""
150 # Handle the start we already have
151 self.completions, self.morecompletions = comp_lists
152 self.mode = mode
153 self.startindex = self.widget.index(index)
154 self.start = self.widget.get(self.startindex, "insert")
155 if complete:
156 completed = self._complete_string(self.start)
157 self._change_start(completed)
158 i = self._binary_search(completed)
159 if self.completions[i] == completed and \
160 (i == len(self.completions)-1 or
161 self.completions[i+1][:len(completed)] != completed):
162 # There is exactly one matching completion
163 return
164 self.userwantswindow = userWantsWin
165 self.lasttypedstart = self.start
166
167 # Put widgets in place
168 self.autocompletewindow = acw = Toplevel(self.widget)
169 # Put it in a position so that it is not seen.
170 acw.wm_geometry("+10000+10000")
171 # Make it float
172 acw.wm_overrideredirect(1)
173 try:
174 # This command is only needed and available on Tk >= 8.4.0 for OSX
175 # Without it, call tips intrude on the typing process by grabbing
176 # the focus.
177 acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
178 "help", "noActivates")
179 except TclError:
180 pass
181 self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
182 self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
183 exportselection=False, bg="white")
184 for item in self.completions:
185 listbox.insert(END, item)
186 self.origselforeground = listbox.cget("selectforeground")
187 self.origselbackground = listbox.cget("selectbackground")
188 scrollbar.config(command=listbox.yview)
189 scrollbar.pack(side=RIGHT, fill=Y)
190 listbox.pack(side=LEFT, fill=BOTH, expand=True)
191
192 # Initialize the listbox selection
193 self.listbox.select_set(self._binary_search(self.start))
194 self._selection_changed()
195
196 # bind events
197 self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
198 self.hide_event)
199 for seq in HIDE_SEQUENCES:
200 self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
201 self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
202 self.keypress_event)
203 for seq in KEYPRESS_SEQUENCES:
204 self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
205 self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
206 self.keyrelease_event)
207 self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
208 self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
209 self.listupdate_event)
210 self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
211 self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
212 self.doubleclick_event)
213
214 def winconfig_event(self, event):
215 if not self.is_active():
216 return
217 # Position the completion list window
218 acw = self.autocompletewindow
219 self.widget.see(self.startindex)
220 x, y, cx, cy = self.widget.bbox(self.startindex)
221 acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(),
222 y + self.widget.winfo_rooty() \
223 -acw.winfo_height()))
224
225
226 def hide_event(self, event):
227 if not self.is_active():
228 return
229 self.hide_window()
230
231 def listupdate_event(self, event):
232 if not self.is_active():
233 return
234 self.userwantswindow = True
235 self._selection_changed()
236
237 def doubleclick_event(self, event):
238 # Put the selected completion in the text, and close the list
239 cursel = int(self.listbox.curselection()[0])
240 self._change_start(self.completions[cursel])
241 self.hide_window()
242
243 def keypress_event(self, event):
244 if not self.is_active():
245 return
246 keysym = event.keysym
247 if hasattr(event, "mc_state"):
248 state = event.mc_state
249 else:
250 state = 0
251
252 if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
253 or (self.mode==AutoComplete.COMPLETE_FILES and keysym in
254 ("period", "minus"))) \
255 and not (state & ~MC_SHIFT):
256 # Normal editing of text
257 if len(keysym) == 1:
258 self._change_start(self.start + keysym)
259 elif keysym == "underscore":
260 self._change_start(self.start + '_')
261 elif keysym == "period":
262 self._change_start(self.start + '.')
263 elif keysym == "minus":
264 self._change_start(self.start + '-')
265 else:
266 # keysym == "BackSpace"
267 if len(self.start) == 0:
268 self.hide_window()
269 return
270 self._change_start(self.start[:-1])
271 self.lasttypedstart = self.start
272 self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
273 self.listbox.select_set(self._binary_search(self.start))
274 self._selection_changed()
275 return "break"
276
277 elif keysym == "Return" and not state:
278 # If start is a prefix of the selection, or there was an indication
279 # that the user used the completion window, put the selected
280 # completion in the text, and close the list.
281 # Otherwise, close the window and let the event through.
282 cursel = int(self.listbox.curselection()[0])
283 if self.completions[cursel][:len(self.start)] == self.start or \
284 self.userwantswindow:
285 self._change_start(self.completions[cursel])
286 self.hide_window()
287 return "break"
288 else:
289 self.hide_window()
290 return
291
292 elif (self.mode == AutoComplete.COMPLETE_ATTRIBUTES and keysym in
293 ("period", "space", "parenleft", "parenright", "bracketleft",
294 "bracketright")) or \
295 (self.mode == AutoComplete.COMPLETE_FILES and keysym in
296 ("slash", "backslash", "quotedbl", "apostrophe")) \
297 and not (state & ~MC_SHIFT):
298 # If start is a prefix of the selection, but is not '' when
299 # completing file names, put the whole
300 # selected completion. Anyway, close the list.
301 cursel = int(self.listbox.curselection()[0])
302 if self.completions[cursel][:len(self.start)] == self.start \
303 and (self.mode==AutoComplete.COMPLETE_ATTRIBUTES or self.start):
304 self._change_start(self.completions[cursel])
305 self.hide_window()
306 return
307
308 elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
309 not state:
310 # Move the selection in the listbox
311 self.userwantswindow = True
312 cursel = int(self.listbox.curselection()[0])
313 if keysym == "Home":
314 newsel = 0
315 elif keysym == "End":
316 newsel = len(self.completions)-1
317 elif keysym in ("Prior", "Next"):
318 jump = self.listbox.nearest(self.listbox.winfo_height()) - \
319 self.listbox.nearest(0)
320 if keysym == "Prior":
321 newsel = max(0, cursel-jump)
322 else:
323 assert keysym == "Next"
324 newsel = min(len(self.completions)-1, cursel+jump)
325 elif keysym == "Up":
326 newsel = max(0, cursel-1)
327 else:
328 assert keysym == "Down"
329 newsel = min(len(self.completions)-1, cursel+1)
330 self.listbox.select_clear(cursel)
331 self.listbox.select_set(newsel)
332 self._selection_changed()
333 return "break"
334
335 elif (keysym == "Tab" and not state):
336 # The user wants a completion, but it is handled by AutoComplete
337 # (not AutoCompleteWindow), so ignore.
338 self.userwantswindow = True
339 return
340
341 elif reduce(lambda x, y: x or y,
342 [keysym.find(s) != -1 for s in ("Shift", "Control", "Alt",
343 "Meta", "Command", "Option")
344 ]):
345 # A modifier key, so ignore
346 return
347
348 else:
349 # Unknown event, close the window and let it through.
350 self.hide_window()
351 return
352
353 def keyrelease_event(self, event):
354 if not self.is_active():
355 return
356 if self.widget.index("insert") != \
357 self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
358 # If we didn't catch an event which moved the insert, close window
359 self.hide_window()
360
361 def is_active(self):
362 return self.autocompletewindow is not None
363
364 def complete(self):
365 self._change_start(self._complete_string(self.start))
366 # The selection doesn't change.
367
368 def hide_window(self):
369 if not self.is_active():
370 return
371
372 # unbind events
373 for seq in HIDE_SEQUENCES:
374 self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
375 self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid)
376 self.hideid = None
377 for seq in KEYPRESS_SEQUENCES:
378 self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
379 self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
380 self.keypressid = None
381 self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
382 KEYRELEASE_SEQUENCE)
383 self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
384 self.keyreleaseid = None
385 self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
386 self.listupdateid = None
387 self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
388 self.winconfigid = None
389
390 # destroy widgets
391 self.scrollbar.destroy()
392 self.scrollbar = None
393 self.listbox.destroy()
394 self.listbox = None
395 self.autocompletewindow.destroy()
396 self.autocompletewindow = None