1""" 2An auto-completion window for IDLE, used by the autocomplete extension 3""" 4import platform 5 6from tkinter import * 7from tkinter.ttk import Scrollbar 8 9from idlelib.autocomplete import FILES, ATTRS 10from idlelib.multicall import MC_SHIFT 11 12HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>" 13HIDE_FOCUS_OUT_SEQUENCE = "<FocusOut>" 14HIDE_SEQUENCES = (HIDE_FOCUS_OUT_SEQUENCE, "<ButtonPress>") 15KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>" 16# We need to bind event beyond <Key> so that the function will be called 17# before the default specific IDLE function 18KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>", 19 "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>", 20 "<Key-Prior>", "<Key-Next>", "<Key-Escape>") 21KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>" 22KEYRELEASE_SEQUENCE = "<KeyRelease>" 23LISTUPDATE_SEQUENCE = "<B1-ButtonRelease>" 24WINCONFIG_SEQUENCE = "<Configure>" 25DOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>" 26 27class AutoCompleteWindow: 28 29 def __init__(self, widget): 30 # The widget (Text) on which we place the AutoCompleteWindow 31 self.widget = widget 32 # The widgets we create 33 self.autocompletewindow = self.listbox = self.scrollbar = None 34 # The default foreground and background of a selection. Saved because 35 # they are changed to the regular colors of list items when the 36 # completion start is not a prefix of the selected completion 37 self.origselforeground = self.origselbackground = None 38 # The list of completions 39 self.completions = None 40 # A list with more completions, or None 41 self.morecompletions = None 42 # The completion mode, either autocomplete.ATTRS or .FILES. 43 self.mode = None 44 # The current completion start, on the text box (a string) 45 self.start = None 46 # The index of the start of the completion 47 self.startindex = None 48 # The last typed start, used so that when the selection changes, 49 # the new start will be as close as possible to the last typed one. 50 self.lasttypedstart = None 51 # Do we have an indication that the user wants the completion window 52 # (for example, he clicked the list) 53 self.userwantswindow = None 54 # event ids 55 self.hideid = self.keypressid = self.listupdateid = \ 56 self.winconfigid = self.keyreleaseid = self.doubleclickid = None 57 # Flag set if last keypress was a tab 58 self.lastkey_was_tab = False 59 # Flag set to avoid recursive <Configure> callback invocations. 60 self.is_configuring = False 61 62 def _change_start(self, newstart): 63 min_len = min(len(self.start), len(newstart)) 64 i = 0 65 while i < min_len and self.start[i] == newstart[i]: 66 i += 1 67 if i < len(self.start): 68 self.widget.delete("%s+%dc" % (self.startindex, i), 69 "%s+%dc" % (self.startindex, len(self.start))) 70 if i < len(newstart): 71 self.widget.insert("%s+%dc" % (self.startindex, i), 72 newstart[i:]) 73 self.start = newstart 74 75 def _binary_search(self, s): 76 """Find the first index in self.completions where completions[i] is 77 greater or equal to s, or the last index if there is no such. 78 """ 79 i = 0; j = len(self.completions) 80 while j > i: 81 m = (i + j) // 2 82 if self.completions[m] >= s: 83 j = m 84 else: 85 i = m + 1 86 return min(i, len(self.completions)-1) 87 88 def _complete_string(self, s): 89 """Assuming that s is the prefix of a string in self.completions, 90 return the longest string which is a prefix of all the strings which 91 s is a prefix of them. If s is not a prefix of a string, return s. 92 """ 93 first = self._binary_search(s) 94 if self.completions[first][:len(s)] != s: 95 # There is not even one completion which s is a prefix of. 96 return s 97 # Find the end of the range of completions where s is a prefix of. 98 i = first + 1 99 j = len(self.completions) 100 while j > i: 101 m = (i + j) // 2 102 if self.completions[m][:len(s)] != s: 103 j = m 104 else: 105 i = m + 1 106 last = i-1 107 108 if first == last: # only one possible completion 109 return self.completions[first] 110 111 # We should return the maximum prefix of first and last 112 first_comp = self.completions[first] 113 last_comp = self.completions[last] 114 min_len = min(len(first_comp), len(last_comp)) 115 i = len(s) 116 while i < min_len and first_comp[i] == last_comp[i]: 117 i += 1 118 return first_comp[:i] 119 120 def _selection_changed(self): 121 """Call when the selection of the Listbox has changed. 122 123 Updates the Listbox display and calls _change_start. 124 """ 125 cursel = int(self.listbox.curselection()[0]) 126 127 self.listbox.see(cursel) 128 129 lts = self.lasttypedstart 130 selstart = self.completions[cursel] 131 if self._binary_search(lts) == cursel: 132 newstart = lts 133 else: 134 min_len = min(len(lts), len(selstart)) 135 i = 0 136 while i < min_len and lts[i] == selstart[i]: 137 i += 1 138 newstart = selstart[:i] 139 self._change_start(newstart) 140 141 if self.completions[cursel][:len(self.start)] == self.start: 142 # start is a prefix of the selected completion 143 self.listbox.configure(selectbackground=self.origselbackground, 144 selectforeground=self.origselforeground) 145 else: 146 self.listbox.configure(selectbackground=self.listbox.cget("bg"), 147 selectforeground=self.listbox.cget("fg")) 148 # If there are more completions, show them, and call me again. 149 if self.morecompletions: 150 self.completions = self.morecompletions 151 self.morecompletions = None 152 self.listbox.delete(0, END) 153 for item in self.completions: 154 self.listbox.insert(END, item) 155 self.listbox.select_set(self._binary_search(self.start)) 156 self._selection_changed() 157 158 def show_window(self, comp_lists, index, complete, mode, userWantsWin): 159 """Show the autocomplete list, bind events. 160 161 If complete is True, complete the text, and if there is exactly 162 one matching completion, don't open a list. 163 """ 164 # Handle the start we already have 165 self.completions, self.morecompletions = comp_lists 166 self.mode = mode 167 self.startindex = self.widget.index(index) 168 self.start = self.widget.get(self.startindex, "insert") 169 if complete: 170 completed = self._complete_string(self.start) 171 start = self.start 172 self._change_start(completed) 173 i = self._binary_search(completed) 174 if self.completions[i] == completed and \ 175 (i == len(self.completions)-1 or 176 self.completions[i+1][:len(completed)] != completed): 177 # There is exactly one matching completion 178 return completed == start 179 self.userwantswindow = userWantsWin 180 self.lasttypedstart = self.start 181 182 # Put widgets in place 183 self.autocompletewindow = acw = Toplevel(self.widget) 184 # Put it in a position so that it is not seen. 185 acw.wm_geometry("+10000+10000") 186 # Make it float 187 acw.wm_overrideredirect(1) 188 try: 189 # This command is only needed and available on Tk >= 8.4.0 for OSX 190 # Without it, call tips intrude on the typing process by grabbing 191 # the focus. 192 acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w, 193 "help", "noActivates") 194 except TclError: 195 pass 196 self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL) 197 self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, 198 exportselection=False) 199 for item in self.completions: 200 listbox.insert(END, item) 201 self.origselforeground = listbox.cget("selectforeground") 202 self.origselbackground = listbox.cget("selectbackground") 203 scrollbar.config(command=listbox.yview) 204 scrollbar.pack(side=RIGHT, fill=Y) 205 listbox.pack(side=LEFT, fill=BOTH, expand=True) 206 acw.lift() # work around bug in Tk 8.5.18+ (issue #24570) 207 208 # Initialize the listbox selection 209 self.listbox.select_set(self._binary_search(self.start)) 210 self._selection_changed() 211 212 # bind events 213 self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) 214 self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) 215 acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE) 216 for seq in HIDE_SEQUENCES: 217 self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) 218 219 self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, 220 self.keypress_event) 221 for seq in KEYPRESS_SEQUENCES: 222 self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq) 223 self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, 224 self.keyrelease_event) 225 self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) 226 self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, 227 self.listselect_event) 228 self.is_configuring = False 229 self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) 230 self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, 231 self.doubleclick_event) 232 return None 233 234 def winconfig_event(self, event): 235 if self.is_configuring: 236 # Avoid running on recursive <Configure> callback invocations. 237 return 238 239 self.is_configuring = True 240 if not self.is_active(): 241 return 242 # Position the completion list window 243 text = self.widget 244 text.see(self.startindex) 245 x, y, cx, cy = text.bbox(self.startindex) 246 acw = self.autocompletewindow 247 acw.update() 248 acw_width, acw_height = acw.winfo_width(), acw.winfo_height() 249 text_width, text_height = text.winfo_width(), text.winfo_height() 250 new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) 251 new_y = text.winfo_rooty() + y 252 if (text_height - (y + cy) >= acw_height # enough height below 253 or y < acw_height): # not enough height above 254 # place acw below current line 255 new_y += cy 256 else: 257 # place acw above current line 258 new_y -= acw_height 259 acw.wm_geometry("+%d+%d" % (new_x, new_y)) 260 acw.update_idletasks() 261 262 if platform.system().startswith('Windows'): 263 # See issue 15786. When on Windows platform, Tk will misbehave 264 # to call winconfig_event multiple times, we need to prevent this, 265 # otherwise mouse button double click will not be able to used. 266 acw.unbind(WINCONFIG_SEQUENCE, self.winconfigid) 267 self.winconfigid = None 268 269 self.is_configuring = False 270 271 def _hide_event_check(self): 272 if not self.autocompletewindow: 273 return 274 275 try: 276 if not self.autocompletewindow.focus_get(): 277 self.hide_window() 278 except KeyError: 279 # See issue 734176, when user click on menu, acw.focus_get() 280 # will get KeyError. 281 self.hide_window() 282 283 def hide_event(self, event): 284 # Hide autocomplete list if it exists and does not have focus or 285 # mouse click on widget / text area. 286 if self.is_active(): 287 if event.type == EventType.FocusOut: 288 # On Windows platform, it will need to delay the check for 289 # acw.focus_get() when click on acw, otherwise it will return 290 # None and close the window 291 self.widget.after(1, self._hide_event_check) 292 elif event.type == EventType.ButtonPress: 293 # ButtonPress event only bind to self.widget 294 self.hide_window() 295 296 def listselect_event(self, event): 297 if self.is_active(): 298 self.userwantswindow = True 299 cursel = int(self.listbox.curselection()[0]) 300 self._change_start(self.completions[cursel]) 301 302 def doubleclick_event(self, event): 303 # Put the selected completion in the text, and close the list 304 cursel = int(self.listbox.curselection()[0]) 305 self._change_start(self.completions[cursel]) 306 self.hide_window() 307 308 def keypress_event(self, event): 309 if not self.is_active(): 310 return None 311 keysym = event.keysym 312 if hasattr(event, "mc_state"): 313 state = event.mc_state 314 else: 315 state = 0 316 if keysym != "Tab": 317 self.lastkey_was_tab = False 318 if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") 319 or (self.mode == FILES and keysym in 320 ("period", "minus"))) \ 321 and not (state & ~MC_SHIFT): 322 # Normal editing of text 323 if len(keysym) == 1: 324 self._change_start(self.start + keysym) 325 elif keysym == "underscore": 326 self._change_start(self.start + '_') 327 elif keysym == "period": 328 self._change_start(self.start + '.') 329 elif keysym == "minus": 330 self._change_start(self.start + '-') 331 else: 332 # keysym == "BackSpace" 333 if len(self.start) == 0: 334 self.hide_window() 335 return None 336 self._change_start(self.start[:-1]) 337 self.lasttypedstart = self.start 338 self.listbox.select_clear(0, int(self.listbox.curselection()[0])) 339 self.listbox.select_set(self._binary_search(self.start)) 340 self._selection_changed() 341 return "break" 342 343 elif keysym == "Return": 344 self.complete() 345 self.hide_window() 346 return 'break' 347 348 elif (self.mode == ATTRS and keysym in 349 ("period", "space", "parenleft", "parenright", "bracketleft", 350 "bracketright")) or \ 351 (self.mode == FILES and keysym in 352 ("slash", "backslash", "quotedbl", "apostrophe")) \ 353 and not (state & ~MC_SHIFT): 354 # If start is a prefix of the selection, but is not '' when 355 # completing file names, put the whole 356 # selected completion. Anyway, close the list. 357 cursel = int(self.listbox.curselection()[0]) 358 if self.completions[cursel][:len(self.start)] == self.start \ 359 and (self.mode == ATTRS or self.start): 360 self._change_start(self.completions[cursel]) 361 self.hide_window() 362 return None 363 364 elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \ 365 not state: 366 # Move the selection in the listbox 367 self.userwantswindow = True 368 cursel = int(self.listbox.curselection()[0]) 369 if keysym == "Home": 370 newsel = 0 371 elif keysym == "End": 372 newsel = len(self.completions)-1 373 elif keysym in ("Prior", "Next"): 374 jump = self.listbox.nearest(self.listbox.winfo_height()) - \ 375 self.listbox.nearest(0) 376 if keysym == "Prior": 377 newsel = max(0, cursel-jump) 378 else: 379 assert keysym == "Next" 380 newsel = min(len(self.completions)-1, cursel+jump) 381 elif keysym == "Up": 382 newsel = max(0, cursel-1) 383 else: 384 assert keysym == "Down" 385 newsel = min(len(self.completions)-1, cursel+1) 386 self.listbox.select_clear(cursel) 387 self.listbox.select_set(newsel) 388 self._selection_changed() 389 self._change_start(self.completions[newsel]) 390 return "break" 391 392 elif (keysym == "Tab" and not state): 393 if self.lastkey_was_tab: 394 # two tabs in a row; insert current selection and close acw 395 cursel = int(self.listbox.curselection()[0]) 396 self._change_start(self.completions[cursel]) 397 self.hide_window() 398 return "break" 399 else: 400 # first tab; let AutoComplete handle the completion 401 self.userwantswindow = True 402 self.lastkey_was_tab = True 403 return None 404 405 elif any(s in keysym for s in ("Shift", "Control", "Alt", 406 "Meta", "Command", "Option")): 407 # A modifier key, so ignore 408 return None 409 410 elif event.char and event.char >= ' ': 411 # Regular character with a non-length-1 keycode 412 self._change_start(self.start + event.char) 413 self.lasttypedstart = self.start 414 self.listbox.select_clear(0, int(self.listbox.curselection()[0])) 415 self.listbox.select_set(self._binary_search(self.start)) 416 self._selection_changed() 417 return "break" 418 419 else: 420 # Unknown event, close the window and let it through. 421 self.hide_window() 422 return None 423 424 def keyrelease_event(self, event): 425 if not self.is_active(): 426 return 427 if self.widget.index("insert") != \ 428 self.widget.index("%s+%dc" % (self.startindex, len(self.start))): 429 # If we didn't catch an event which moved the insert, close window 430 self.hide_window() 431 432 def is_active(self): 433 return self.autocompletewindow is not None 434 435 def complete(self): 436 self._change_start(self._complete_string(self.start)) 437 # The selection doesn't change. 438 439 def hide_window(self): 440 if not self.is_active(): 441 return 442 443 # unbind events 444 self.autocompletewindow.event_delete(HIDE_VIRTUAL_EVENT_NAME, 445 HIDE_FOCUS_OUT_SEQUENCE) 446 for seq in HIDE_SEQUENCES: 447 self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) 448 449 self.autocompletewindow.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideaid) 450 self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hidewid) 451 self.hideaid = None 452 self.hidewid = None 453 for seq in KEYPRESS_SEQUENCES: 454 self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq) 455 self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid) 456 self.keypressid = None 457 self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME, 458 KEYRELEASE_SEQUENCE) 459 self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid) 460 self.keyreleaseid = None 461 self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid) 462 self.listupdateid = None 463 if self.winconfigid: 464 self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid) 465 self.winconfigid = None 466 467 # Re-focusOn frame.text (See issue #15786) 468 self.widget.focus_set() 469 470 # destroy widgets 471 self.scrollbar.destroy() 472 self.scrollbar = None 473 self.listbox.destroy() 474 self.listbox = None 475 self.autocompletewindow.destroy() 476 self.autocompletewindow = None 477 478 479if __name__ == '__main__': 480 from unittest import main 481 main('idlelib.idle_test.test_autocomplete_w', verbosity=2, exit=False) 482 483# TODO: autocomplete/w htest here 484