blob: 3374c6e94510aae80dc91e5529c3cb42dbb51c68 [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 Reedybfbaa6b2016-08-31 00:50:55 -04006
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04007from idlelib.autocomplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -04008from idlelib.multicall import MC_SHIFT
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00009
10HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
11HIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
12KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
13# We need to bind event beyond <Key> so that the function will be called
14# before the default specific IDLE function
Thomas Wouterscf297e42007-02-23 15:07:44 +000015KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
16 "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
17 "<Key-Prior>", "<Key-Next>")
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000018KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
19KEYRELEASE_SEQUENCE = "<KeyRelease>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000020LISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000021WINCONFIG_SEQUENCE = "<Configure>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000022DOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000023
24class AutoCompleteWindow:
25
26 def __init__(self, widget):
27 # The widget (Text) on which we place the AutoCompleteWindow
28 self.widget = widget
29 # The widgets we create
30 self.autocompletewindow = self.listbox = self.scrollbar = None
31 # The default foreground and background of a selection. Saved because
32 # they are changed to the regular colors of list items when the
33 # completion start is not a prefix of the selected completion
34 self.origselforeground = self.origselbackground = None
35 # The list of completions
36 self.completions = None
37 # A list with more completions, or None
38 self.morecompletions = None
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -040039 # The completion mode. Either autocomplete.COMPLETE_ATTRIBUTES or
40 # autocomplete.COMPLETE_FILES
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000041 self.mode = None
42 # The current completion start, on the text box (a string)
43 self.start = None
44 # The index of the start of the completion
45 self.startindex = None
46 # The last typed start, used so that when the selection changes,
47 # the new start will be as close as possible to the last typed one.
48 self.lasttypedstart = None
49 # Do we have an indication that the user wants the completion window
50 # (for example, he clicked the list)
51 self.userwantswindow = None
52 # event ids
53 self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
54 = self.keyreleaseid = self.doubleclickid = None
Thomas Wouterscf297e42007-02-23 15:07:44 +000055 # Flag set if last keypress was a tab
56 self.lastkey_was_tab = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000057
58 def _change_start(self, newstart):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000059 min_len = min(len(self.start), len(newstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000060 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +000061 while i < min_len and self.start[i] == newstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000062 i += 1
63 if i < len(self.start):
64 self.widget.delete("%s+%dc" % (self.startindex, i),
65 "%s+%dc" % (self.startindex, len(self.start)))
66 if i < len(newstart):
67 self.widget.insert("%s+%dc" % (self.startindex, i),
68 newstart[i:])
69 self.start = newstart
70
71 def _binary_search(self, s):
72 """Find the first index in self.completions where completions[i] is
73 greater or equal to s, or the last index if there is no such
74 one."""
75 i = 0; j = len(self.completions)
76 while j > i:
77 m = (i + j) // 2
78 if self.completions[m] >= s:
79 j = m
80 else:
81 i = m + 1
82 return min(i, len(self.completions)-1)
83
84 def _complete_string(self, s):
85 """Assuming that s is the prefix of a string in self.completions,
86 return the longest string which is a prefix of all the strings which
87 s is a prefix of them. If s is not a prefix of a string, return s."""
88 first = self._binary_search(s)
89 if self.completions[first][:len(s)] != s:
90 # There is not even one completion which s is a prefix of.
91 return s
92 # Find the end of the range of completions where s is a prefix of.
93 i = first + 1
94 j = len(self.completions)
95 while j > i:
96 m = (i + j) // 2
97 if self.completions[m][:len(s)] != s:
98 j = m
99 else:
100 i = m + 1
101 last = i-1
102
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000103 if first == last: # only one possible completion
104 return self.completions[first]
105
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000106 # We should return the maximum prefix of first and last
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000107 first_comp = self.completions[first]
108 last_comp = self.completions[last]
109 min_len = min(len(first_comp), len(last_comp))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000110 i = len(s)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000111 while i < min_len and first_comp[i] == last_comp[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000112 i += 1
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000113 return first_comp[:i]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000114
115 def _selection_changed(self):
116 """Should be called when the selection of the Listbox has changed.
117 Updates the Listbox display and calls _change_start."""
118 cursel = int(self.listbox.curselection()[0])
119
120 self.listbox.see(cursel)
121
122 lts = self.lasttypedstart
123 selstart = self.completions[cursel]
124 if self._binary_search(lts) == cursel:
125 newstart = lts
126 else:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000127 min_len = min(len(lts), len(selstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000128 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000129 while i < min_len and lts[i] == selstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000130 i += 1
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000131 newstart = selstart[:i]
132 self._change_start(newstart)
133
134 if self.completions[cursel][:len(self.start)] == self.start:
135 # start is a prefix of the selected completion
136 self.listbox.configure(selectbackground=self.origselbackground,
137 selectforeground=self.origselforeground)
138 else:
139 self.listbox.configure(selectbackground=self.listbox.cget("bg"),
140 selectforeground=self.listbox.cget("fg"))
141 # If there are more completions, show them, and call me again.
142 if self.morecompletions:
143 self.completions = self.morecompletions
144 self.morecompletions = None
145 self.listbox.delete(0, END)
146 for item in self.completions:
147 self.listbox.insert(END, item)
148 self.listbox.select_set(self._binary_search(self.start))
149 self._selection_changed()
150
151 def show_window(self, comp_lists, index, complete, mode, userWantsWin):
152 """Show the autocomplete list, bind events.
153 If complete is True, complete the text, and if there is exactly one
154 matching completion, don't open a list."""
155 # Handle the start we already have
156 self.completions, self.morecompletions = comp_lists
157 self.mode = mode
158 self.startindex = self.widget.index(index)
159 self.start = self.widget.get(self.startindex, "insert")
160 if complete:
161 completed = self._complete_string(self.start)
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300162 start = self.start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000163 self._change_start(completed)
164 i = self._binary_search(completed)
165 if self.completions[i] == completed and \
166 (i == len(self.completions)-1 or
167 self.completions[i+1][:len(completed)] != completed):
168 # There is exactly one matching completion
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300169 return completed == start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000170 self.userwantswindow = userWantsWin
171 self.lasttypedstart = self.start
172
173 # Put widgets in place
174 self.autocompletewindow = acw = Toplevel(self.widget)
175 # Put it in a position so that it is not seen.
176 acw.wm_geometry("+10000+10000")
177 # Make it float
178 acw.wm_overrideredirect(1)
179 try:
180 # This command is only needed and available on Tk >= 8.4.0 for OSX
181 # Without it, call tips intrude on the typing process by grabbing
182 # the focus.
183 acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
184 "help", "noActivates")
185 except TclError:
186 pass
187 self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
188 self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
189 exportselection=False, bg="white")
190 for item in self.completions:
191 listbox.insert(END, item)
192 self.origselforeground = listbox.cget("selectforeground")
193 self.origselbackground = listbox.cget("selectbackground")
194 scrollbar.config(command=listbox.yview)
195 scrollbar.pack(side=RIGHT, fill=Y)
196 listbox.pack(side=LEFT, fill=BOTH, expand=True)
Terry Jan Reedyd2134c72015-09-26 20:03:57 -0400197 acw.lift() # work around bug in Tk 8.5.18+ (issue #24570)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000198
199 # Initialize the listbox selection
200 self.listbox.select_set(self._binary_search(self.start))
201 self._selection_changed()
202
203 # bind events
204 self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
205 self.hide_event)
206 for seq in HIDE_SEQUENCES:
207 self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
208 self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
209 self.keypress_event)
210 for seq in KEYPRESS_SEQUENCES:
211 self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
212 self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
213 self.keyrelease_event)
214 self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
215 self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
Thomas Wouterscf297e42007-02-23 15:07:44 +0000216 self.listselect_event)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000217 self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
218 self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
219 self.doubleclick_event)
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400220 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000221
222 def winconfig_event(self, event):
223 if not self.is_active():
224 return
225 # Position the completion list window
Thomas Wouterscf297e42007-02-23 15:07:44 +0000226 text = self.widget
227 text.see(self.startindex)
228 x, y, cx, cy = text.bbox(self.startindex)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000229 acw = self.autocompletewindow
Thomas Wouterscf297e42007-02-23 15:07:44 +0000230 acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
231 text_width, text_height = text.winfo_width(), text.winfo_height()
232 new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
233 new_y = text.winfo_rooty() + y
234 if (text_height - (y + cy) >= acw_height # enough height below
235 or y < acw_height): # not enough height above
236 # place acw below current line
237 new_y += cy
238 else:
239 # place acw above current line
240 new_y -= acw_height
241 acw.wm_geometry("+%d+%d" % (new_x, new_y))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000242
243 def hide_event(self, event):
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -0400244 if self.is_active():
245 self.hide_window()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000246
Thomas Wouterscf297e42007-02-23 15:07:44 +0000247 def listselect_event(self, event):
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400248 if self.is_active():
249 self.userwantswindow = True
250 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():
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400261 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000262 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()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400286 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000287 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()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400296 return None
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()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400312 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000313
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
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400353 return None
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
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400358 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000359
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()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400372 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000373
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