blob: 38f860115639d2525ce996bb33b8ea6ad7eb7103 [file] [log] [blame]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001"""
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04002An auto-completion window for IDLE, used by the autocomplete extension
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00003"""
Georg Brandl14fc4272008-05-17 18:39:55 +00004from tkinter import *
Terry Jan Reedy01e35752016-06-10 18:19:21 -04005from tkinter.ttk import Scrollbar
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04006from idlelib.multicall import MC_SHIFT
7from idlelib.autocomplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00008
9HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
10HIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
11KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
12# We need to bind event beyond <Key> so that the function will be called
13# before the default specific IDLE function
Thomas Wouterscf297e42007-02-23 15:07:44 +000014KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
15 "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
16 "<Key-Prior>", "<Key-Next>")
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000017KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
18KEYRELEASE_SEQUENCE = "<KeyRelease>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000019LISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000020WINCONFIG_SEQUENCE = "<Configure>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000021DOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000022
23class AutoCompleteWindow:
24
25 def __init__(self, widget):
26 # The widget (Text) on which we place the AutoCompleteWindow
27 self.widget = widget
28 # The widgets we create
29 self.autocompletewindow = self.listbox = self.scrollbar = None
30 # The default foreground and background of a selection. Saved because
31 # they are changed to the regular colors of list items when the
32 # completion start is not a prefix of the selected completion
33 self.origselforeground = self.origselbackground = None
34 # The list of completions
35 self.completions = None
36 # A list with more completions, or None
37 self.morecompletions = None
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040038 # The completion mode. Either autocomplete.COMPLETE_ATTRIBUTES or
39 # autocomplete.COMPLETE_FILES
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000040 self.mode = None
41 # The current completion start, on the text box (a string)
42 self.start = None
43 # The index of the start of the completion
44 self.startindex = None
45 # The last typed start, used so that when the selection changes,
46 # the new start will be as close as possible to the last typed one.
47 self.lasttypedstart = None
48 # Do we have an indication that the user wants the completion window
49 # (for example, he clicked the list)
50 self.userwantswindow = None
51 # event ids
52 self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
53 = self.keyreleaseid = self.doubleclickid = None
Thomas Wouterscf297e42007-02-23 15:07:44 +000054 # Flag set if last keypress was a tab
55 self.lastkey_was_tab = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000056
57 def _change_start(self, newstart):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000058 min_len = min(len(self.start), len(newstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000059 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +000060 while i < min_len and self.start[i] == newstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000061 i += 1
62 if i < len(self.start):
63 self.widget.delete("%s+%dc" % (self.startindex, i),
64 "%s+%dc" % (self.startindex, len(self.start)))
65 if i < len(newstart):
66 self.widget.insert("%s+%dc" % (self.startindex, i),
67 newstart[i:])
68 self.start = newstart
69
70 def _binary_search(self, s):
71 """Find the first index in self.completions where completions[i] is
72 greater or equal to s, or the last index if there is no such
73 one."""
74 i = 0; j = len(self.completions)
75 while j > i:
76 m = (i + j) // 2
77 if self.completions[m] >= s:
78 j = m
79 else:
80 i = m + 1
81 return min(i, len(self.completions)-1)
82
83 def _complete_string(self, s):
84 """Assuming that s is the prefix of a string in self.completions,
85 return the longest string which is a prefix of all the strings which
86 s is a prefix of them. If s is not a prefix of a string, return s."""
87 first = self._binary_search(s)
88 if self.completions[first][:len(s)] != s:
89 # There is not even one completion which s is a prefix of.
90 return s
91 # Find the end of the range of completions where s is a prefix of.
92 i = first + 1
93 j = len(self.completions)
94 while j > i:
95 m = (i + j) // 2
96 if self.completions[m][:len(s)] != s:
97 j = m
98 else:
99 i = m + 1
100 last = i-1
101
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000102 if first == last: # only one possible completion
103 return self.completions[first]
104
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000105 # We should return the maximum prefix of first and last
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000106 first_comp = self.completions[first]
107 last_comp = self.completions[last]
108 min_len = min(len(first_comp), len(last_comp))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000109 i = len(s)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000110 while i < min_len and first_comp[i] == last_comp[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000111 i += 1
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000112 return first_comp[:i]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000113
114 def _selection_changed(self):
115 """Should be called when the selection of the Listbox has changed.
116 Updates the Listbox display and calls _change_start."""
117 cursel = int(self.listbox.curselection()[0])
118
119 self.listbox.see(cursel)
120
121 lts = self.lasttypedstart
122 selstart = self.completions[cursel]
123 if self._binary_search(lts) == cursel:
124 newstart = lts
125 else:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000126 min_len = min(len(lts), len(selstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000127 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000128 while i < min_len and lts[i] == selstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000129 i += 1
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000130 newstart = selstart[:i]
131 self._change_start(newstart)
132
133 if self.completions[cursel][:len(self.start)] == self.start:
134 # start is a prefix of the selected completion
135 self.listbox.configure(selectbackground=self.origselbackground,
136 selectforeground=self.origselforeground)
137 else:
138 self.listbox.configure(selectbackground=self.listbox.cget("bg"),
139 selectforeground=self.listbox.cget("fg"))
140 # If there are more completions, show them, and call me again.
141 if self.morecompletions:
142 self.completions = self.morecompletions
143 self.morecompletions = None
144 self.listbox.delete(0, END)
145 for item in self.completions:
146 self.listbox.insert(END, item)
147 self.listbox.select_set(self._binary_search(self.start))
148 self._selection_changed()
149
150 def show_window(self, comp_lists, index, complete, mode, userWantsWin):
151 """Show the autocomplete list, bind events.
152 If complete is True, complete the text, and if there is exactly one
153 matching completion, don't open a list."""
154 # Handle the start we already have
155 self.completions, self.morecompletions = comp_lists
156 self.mode = mode
157 self.startindex = self.widget.index(index)
158 self.start = self.widget.get(self.startindex, "insert")
159 if complete:
160 completed = self._complete_string(self.start)
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300161 start = self.start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000162 self._change_start(completed)
163 i = self._binary_search(completed)
164 if self.completions[i] == completed and \
165 (i == len(self.completions)-1 or
166 self.completions[i+1][:len(completed)] != completed):
167 # There is exactly one matching completion
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300168 return completed == start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000169 self.userwantswindow = userWantsWin
170 self.lasttypedstart = self.start
171
172 # Put widgets in place
173 self.autocompletewindow = acw = Toplevel(self.widget)
174 # Put it in a position so that it is not seen.
175 acw.wm_geometry("+10000+10000")
176 # Make it float
177 acw.wm_overrideredirect(1)
178 try:
179 # This command is only needed and available on Tk >= 8.4.0 for OSX
180 # Without it, call tips intrude on the typing process by grabbing
181 # the focus.
182 acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
183 "help", "noActivates")
184 except TclError:
185 pass
186 self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
187 self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
188 exportselection=False, bg="white")
189 for item in self.completions:
190 listbox.insert(END, item)
191 self.origselforeground = listbox.cget("selectforeground")
192 self.origselbackground = listbox.cget("selectbackground")
193 scrollbar.config(command=listbox.yview)
194 scrollbar.pack(side=RIGHT, fill=Y)
195 listbox.pack(side=LEFT, fill=BOTH, expand=True)
Terry Jan Reedyd2134c72015-09-26 20:03:57 -0400196 acw.lift() # work around bug in Tk 8.5.18+ (issue #24570)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000197
198 # Initialize the listbox selection
199 self.listbox.select_set(self._binary_search(self.start))
200 self._selection_changed()
201
202 # bind events
203 self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
204 self.hide_event)
205 for seq in HIDE_SEQUENCES:
206 self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
207 self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
208 self.keypress_event)
209 for seq in KEYPRESS_SEQUENCES:
210 self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
211 self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
212 self.keyrelease_event)
213 self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
214 self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
Thomas Wouterscf297e42007-02-23 15:07:44 +0000215 self.listselect_event)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000216 self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
217 self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
218 self.doubleclick_event)
219
220 def winconfig_event(self, event):
221 if not self.is_active():
222 return
223 # Position the completion list window
Thomas Wouterscf297e42007-02-23 15:07:44 +0000224 text = self.widget
225 text.see(self.startindex)
226 x, y, cx, cy = text.bbox(self.startindex)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000227 acw = self.autocompletewindow
Thomas Wouterscf297e42007-02-23 15:07:44 +0000228 acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
229 text_width, text_height = text.winfo_width(), text.winfo_height()
230 new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
231 new_y = text.winfo_rooty() + y
232 if (text_height - (y + cy) >= acw_height # enough height below
233 or y < acw_height): # not enough height above
234 # place acw below current line
235 new_y += cy
236 else:
237 # place acw above current line
238 new_y -= acw_height
239 acw.wm_geometry("+%d+%d" % (new_x, new_y))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000240
241 def hide_event(self, event):
242 if not self.is_active():
243 return
244 self.hide_window()
245
Thomas Wouterscf297e42007-02-23 15:07:44 +0000246 def listselect_event(self, event):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000247 if not self.is_active():
248 return
249 self.userwantswindow = True
Thomas Wouterscf297e42007-02-23 15:07:44 +0000250 cursel = int(self.listbox.curselection()[0])
251 self._change_start(self.completions[cursel])
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000252
253 def doubleclick_event(self, event):
254 # Put the selected completion in the text, and close the list
255 cursel = int(self.listbox.curselection()[0])
256 self._change_start(self.completions[cursel])
257 self.hide_window()
258
259 def keypress_event(self, event):
260 if not self.is_active():
261 return
262 keysym = event.keysym
263 if hasattr(event, "mc_state"):
264 state = event.mc_state
265 else:
266 state = 0
Thomas Wouterscf297e42007-02-23 15:07:44 +0000267 if keysym != "Tab":
268 self.lastkey_was_tab = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000269 if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +0000270 or (self.mode == COMPLETE_FILES and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000271 ("period", "minus"))) \
272 and not (state & ~MC_SHIFT):
273 # Normal editing of text
274 if len(keysym) == 1:
275 self._change_start(self.start + keysym)
276 elif keysym == "underscore":
277 self._change_start(self.start + '_')
278 elif keysym == "period":
279 self._change_start(self.start + '.')
280 elif keysym == "minus":
281 self._change_start(self.start + '-')
282 else:
283 # keysym == "BackSpace"
284 if len(self.start) == 0:
285 self.hide_window()
286 return
287 self._change_start(self.start[:-1])
288 self.lasttypedstart = self.start
289 self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
290 self.listbox.select_set(self._binary_search(self.start))
291 self._selection_changed()
292 return "break"
293
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000294 elif keysym == "Return":
295 self.hide_window()
296 return
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000297
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +0000298 elif (self.mode == COMPLETE_ATTRIBUTES and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000299 ("period", "space", "parenleft", "parenright", "bracketleft",
300 "bracketright")) or \
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +0000301 (self.mode == COMPLETE_FILES and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000302 ("slash", "backslash", "quotedbl", "apostrophe")) \
303 and not (state & ~MC_SHIFT):
304 # If start is a prefix of the selection, but is not '' when
305 # completing file names, put the whole
306 # selected completion. Anyway, close the list.
307 cursel = int(self.listbox.curselection()[0])
308 if self.completions[cursel][:len(self.start)] == self.start \
Kurt B. Kaisere1b4a162007-08-10 02:45:06 +0000309 and (self.mode == COMPLETE_ATTRIBUTES or self.start):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000310 self._change_start(self.completions[cursel])
311 self.hide_window()
312 return
313
314 elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
315 not state:
316 # Move the selection in the listbox
317 self.userwantswindow = True
318 cursel = int(self.listbox.curselection()[0])
319 if keysym == "Home":
320 newsel = 0
321 elif keysym == "End":
322 newsel = len(self.completions)-1
323 elif keysym in ("Prior", "Next"):
324 jump = self.listbox.nearest(self.listbox.winfo_height()) - \
325 self.listbox.nearest(0)
326 if keysym == "Prior":
327 newsel = max(0, cursel-jump)
328 else:
329 assert keysym == "Next"
330 newsel = min(len(self.completions)-1, cursel+jump)
331 elif keysym == "Up":
332 newsel = max(0, cursel-1)
333 else:
334 assert keysym == "Down"
335 newsel = min(len(self.completions)-1, cursel+1)
336 self.listbox.select_clear(cursel)
337 self.listbox.select_set(newsel)
338 self._selection_changed()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000339 self._change_start(self.completions[newsel])
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000340 return "break"
341
342 elif (keysym == "Tab" and not state):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000343 if self.lastkey_was_tab:
344 # two tabs in a row; insert current selection and close acw
345 cursel = int(self.listbox.curselection()[0])
346 self._change_start(self.completions[cursel])
347 self.hide_window()
348 return "break"
349 else:
350 # first tab; let AutoComplete handle the completion
351 self.userwantswindow = True
352 self.lastkey_was_tab = True
353 return
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000354
Guido van Rossum89da5d72006-08-22 00:21:25 +0000355 elif any(s in keysym for s in ("Shift", "Control", "Alt",
356 "Meta", "Command", "Option")):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000357 # A modifier key, so ignore
358 return
359
Martin v. Löwis97aa21b2012-06-03 12:26:09 +0200360 elif event.char and event.char >= ' ':
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200361 # Regular character with a non-length-1 keycode
362 self._change_start(self.start + event.char)
363 self.lasttypedstart = self.start
364 self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
365 self.listbox.select_set(self._binary_search(self.start))
366 self._selection_changed()
367 return "break"
368
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000369 else:
370 # Unknown event, close the window and let it through.
371 self.hide_window()
372 return
373
374 def keyrelease_event(self, event):
375 if not self.is_active():
376 return
377 if self.widget.index("insert") != \
378 self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
379 # If we didn't catch an event which moved the insert, close window
380 self.hide_window()
381
382 def is_active(self):
383 return self.autocompletewindow is not None
384
385 def complete(self):
386 self._change_start(self._complete_string(self.start))
387 # The selection doesn't change.
388
389 def hide_window(self):
390 if not self.is_active():
391 return
392
393 # unbind events
394 for seq in HIDE_SEQUENCES:
395 self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
396 self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid)
397 self.hideid = None
398 for seq in KEYPRESS_SEQUENCES:
399 self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
400 self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
401 self.keypressid = None
402 self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
403 KEYRELEASE_SEQUENCE)
404 self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
405 self.keyreleaseid = None
406 self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
407 self.listupdateid = None
408 self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
409 self.winconfigid = None
410
411 # destroy widgets
412 self.scrollbar.destroy()
413 self.scrollbar = None
414 self.listbox.destroy()
415 self.listbox = None
416 self.autocompletewindow.destroy()
417 self.autocompletewindow = None