jpayne@69: """ jpayne@69: An auto-completion window for IDLE, used by the autocomplete extension jpayne@69: """ jpayne@69: import platform jpayne@69: jpayne@69: from tkinter import * jpayne@69: from tkinter.ttk import Frame, Scrollbar jpayne@69: jpayne@69: from idlelib.autocomplete import FILES, ATTRS jpayne@69: from idlelib.multicall import MC_SHIFT jpayne@69: jpayne@69: HIDE_VIRTUAL_EVENT_NAME = "<>" jpayne@69: HIDE_FOCUS_OUT_SEQUENCE = "" jpayne@69: HIDE_SEQUENCES = (HIDE_FOCUS_OUT_SEQUENCE, "") jpayne@69: KEYPRESS_VIRTUAL_EVENT_NAME = "<>" jpayne@69: # We need to bind event beyond so that the function will be called jpayne@69: # before the default specific IDLE function jpayne@69: KEYPRESS_SEQUENCES = ("", "", "", "", jpayne@69: "", "", "", "", jpayne@69: "", "", "") jpayne@69: KEYRELEASE_VIRTUAL_EVENT_NAME = "<>" jpayne@69: KEYRELEASE_SEQUENCE = "" jpayne@69: LISTUPDATE_SEQUENCE = "" jpayne@69: WINCONFIG_SEQUENCE = "" jpayne@69: DOUBLECLICK_SEQUENCE = "" jpayne@69: jpayne@69: class AutoCompleteWindow: jpayne@69: jpayne@69: def __init__(self, widget): jpayne@69: # The widget (Text) on which we place the AutoCompleteWindow jpayne@69: self.widget = widget jpayne@69: # The widgets we create jpayne@69: self.autocompletewindow = self.listbox = self.scrollbar = None jpayne@69: # The default foreground and background of a selection. Saved because jpayne@69: # they are changed to the regular colors of list items when the jpayne@69: # completion start is not a prefix of the selected completion jpayne@69: self.origselforeground = self.origselbackground = None jpayne@69: # The list of completions jpayne@69: self.completions = None jpayne@69: # A list with more completions, or None jpayne@69: self.morecompletions = None jpayne@69: # The completion mode, either autocomplete.ATTRS or .FILES. jpayne@69: self.mode = None jpayne@69: # The current completion start, on the text box (a string) jpayne@69: self.start = None jpayne@69: # The index of the start of the completion jpayne@69: self.startindex = None jpayne@69: # The last typed start, used so that when the selection changes, jpayne@69: # the new start will be as close as possible to the last typed one. jpayne@69: self.lasttypedstart = None jpayne@69: # Do we have an indication that the user wants the completion window jpayne@69: # (for example, he clicked the list) jpayne@69: self.userwantswindow = None jpayne@69: # event ids jpayne@69: self.hideid = self.keypressid = self.listupdateid = \ jpayne@69: self.winconfigid = self.keyreleaseid = self.doubleclickid = None jpayne@69: # Flag set if last keypress was a tab jpayne@69: self.lastkey_was_tab = False jpayne@69: # Flag set to avoid recursive callback invocations. jpayne@69: self.is_configuring = False jpayne@69: jpayne@69: def _change_start(self, newstart): jpayne@69: min_len = min(len(self.start), len(newstart)) jpayne@69: i = 0 jpayne@69: while i < min_len and self.start[i] == newstart[i]: jpayne@69: i += 1 jpayne@69: if i < len(self.start): jpayne@69: self.widget.delete("%s+%dc" % (self.startindex, i), jpayne@69: "%s+%dc" % (self.startindex, len(self.start))) jpayne@69: if i < len(newstart): jpayne@69: self.widget.insert("%s+%dc" % (self.startindex, i), jpayne@69: newstart[i:]) jpayne@69: self.start = newstart jpayne@69: jpayne@69: def _binary_search(self, s): jpayne@69: """Find the first index in self.completions where completions[i] is jpayne@69: greater or equal to s, or the last index if there is no such. jpayne@69: """ jpayne@69: i = 0; j = len(self.completions) jpayne@69: while j > i: jpayne@69: m = (i + j) // 2 jpayne@69: if self.completions[m] >= s: jpayne@69: j = m jpayne@69: else: jpayne@69: i = m + 1 jpayne@69: return min(i, len(self.completions)-1) jpayne@69: jpayne@69: def _complete_string(self, s): jpayne@69: """Assuming that s is the prefix of a string in self.completions, jpayne@69: return the longest string which is a prefix of all the strings which jpayne@69: s is a prefix of them. If s is not a prefix of a string, return s. jpayne@69: """ jpayne@69: first = self._binary_search(s) jpayne@69: if self.completions[first][:len(s)] != s: jpayne@69: # There is not even one completion which s is a prefix of. jpayne@69: return s jpayne@69: # Find the end of the range of completions where s is a prefix of. jpayne@69: i = first + 1 jpayne@69: j = len(self.completions) jpayne@69: while j > i: jpayne@69: m = (i + j) // 2 jpayne@69: if self.completions[m][:len(s)] != s: jpayne@69: j = m jpayne@69: else: jpayne@69: i = m + 1 jpayne@69: last = i-1 jpayne@69: jpayne@69: if first == last: # only one possible completion jpayne@69: return self.completions[first] jpayne@69: jpayne@69: # We should return the maximum prefix of first and last jpayne@69: first_comp = self.completions[first] jpayne@69: last_comp = self.completions[last] jpayne@69: min_len = min(len(first_comp), len(last_comp)) jpayne@69: i = len(s) jpayne@69: while i < min_len and first_comp[i] == last_comp[i]: jpayne@69: i += 1 jpayne@69: return first_comp[:i] jpayne@69: jpayne@69: def _selection_changed(self): jpayne@69: """Call when the selection of the Listbox has changed. jpayne@69: jpayne@69: Updates the Listbox display and calls _change_start. jpayne@69: """ jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: jpayne@69: self.listbox.see(cursel) jpayne@69: jpayne@69: lts = self.lasttypedstart jpayne@69: selstart = self.completions[cursel] jpayne@69: if self._binary_search(lts) == cursel: jpayne@69: newstart = lts jpayne@69: else: jpayne@69: min_len = min(len(lts), len(selstart)) jpayne@69: i = 0 jpayne@69: while i < min_len and lts[i] == selstart[i]: jpayne@69: i += 1 jpayne@69: newstart = selstart[:i] jpayne@69: self._change_start(newstart) jpayne@69: jpayne@69: if self.completions[cursel][:len(self.start)] == self.start: jpayne@69: # start is a prefix of the selected completion jpayne@69: self.listbox.configure(selectbackground=self.origselbackground, jpayne@69: selectforeground=self.origselforeground) jpayne@69: else: jpayne@69: self.listbox.configure(selectbackground=self.listbox.cget("bg"), jpayne@69: selectforeground=self.listbox.cget("fg")) jpayne@69: # If there are more completions, show them, and call me again. jpayne@69: if self.morecompletions: jpayne@69: self.completions = self.morecompletions jpayne@69: self.morecompletions = None jpayne@69: self.listbox.delete(0, END) jpayne@69: for item in self.completions: jpayne@69: self.listbox.insert(END, item) jpayne@69: self.listbox.select_set(self._binary_search(self.start)) jpayne@69: self._selection_changed() jpayne@69: jpayne@69: def show_window(self, comp_lists, index, complete, mode, userWantsWin): jpayne@69: """Show the autocomplete list, bind events. jpayne@69: jpayne@69: If complete is True, complete the text, and if there is exactly jpayne@69: one matching completion, don't open a list. jpayne@69: """ jpayne@69: # Handle the start we already have jpayne@69: self.completions, self.morecompletions = comp_lists jpayne@69: self.mode = mode jpayne@69: self.startindex = self.widget.index(index) jpayne@69: self.start = self.widget.get(self.startindex, "insert") jpayne@69: if complete: jpayne@69: completed = self._complete_string(self.start) jpayne@69: start = self.start jpayne@69: self._change_start(completed) jpayne@69: i = self._binary_search(completed) jpayne@69: if self.completions[i] == completed and \ jpayne@69: (i == len(self.completions)-1 or jpayne@69: self.completions[i+1][:len(completed)] != completed): jpayne@69: # There is exactly one matching completion jpayne@69: return completed == start jpayne@69: self.userwantswindow = userWantsWin jpayne@69: self.lasttypedstart = self.start jpayne@69: jpayne@69: # Put widgets in place jpayne@69: self.autocompletewindow = acw = Toplevel(self.widget) jpayne@69: # Put it in a position so that it is not seen. jpayne@69: acw.wm_geometry("+10000+10000") jpayne@69: # Make it float jpayne@69: acw.wm_overrideredirect(1) jpayne@69: try: jpayne@69: # This command is only needed and available on Tk >= 8.4.0 for OSX jpayne@69: # Without it, call tips intrude on the typing process by grabbing jpayne@69: # the focus. jpayne@69: acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w, jpayne@69: "help", "noActivates") jpayne@69: except TclError: jpayne@69: pass jpayne@69: self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL) jpayne@69: self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, jpayne@69: exportselection=False) jpayne@69: for item in self.completions: jpayne@69: listbox.insert(END, item) jpayne@69: self.origselforeground = listbox.cget("selectforeground") jpayne@69: self.origselbackground = listbox.cget("selectbackground") jpayne@69: scrollbar.config(command=listbox.yview) jpayne@69: scrollbar.pack(side=RIGHT, fill=Y) jpayne@69: listbox.pack(side=LEFT, fill=BOTH, expand=True) jpayne@69: acw.lift() # work around bug in Tk 8.5.18+ (issue #24570) jpayne@69: jpayne@69: # Initialize the listbox selection jpayne@69: self.listbox.select_set(self._binary_search(self.start)) jpayne@69: self._selection_changed() jpayne@69: jpayne@69: # bind events jpayne@69: self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) jpayne@69: self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) jpayne@69: acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE) jpayne@69: for seq in HIDE_SEQUENCES: jpayne@69: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) jpayne@69: jpayne@69: self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, jpayne@69: self.keypress_event) jpayne@69: for seq in KEYPRESS_SEQUENCES: jpayne@69: self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq) jpayne@69: self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, jpayne@69: self.keyrelease_event) jpayne@69: self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) jpayne@69: self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, jpayne@69: self.listselect_event) jpayne@69: self.is_configuring = False jpayne@69: self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) jpayne@69: self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, jpayne@69: self.doubleclick_event) jpayne@69: return None jpayne@69: jpayne@69: def winconfig_event(self, event): jpayne@69: if self.is_configuring: jpayne@69: # Avoid running on recursive callback invocations. jpayne@69: return jpayne@69: jpayne@69: self.is_configuring = True jpayne@69: if not self.is_active(): jpayne@69: return jpayne@69: # Position the completion list window jpayne@69: text = self.widget jpayne@69: text.see(self.startindex) jpayne@69: x, y, cx, cy = text.bbox(self.startindex) jpayne@69: acw = self.autocompletewindow jpayne@69: acw.update() jpayne@69: acw_width, acw_height = acw.winfo_width(), acw.winfo_height() jpayne@69: text_width, text_height = text.winfo_width(), text.winfo_height() jpayne@69: new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width)) jpayne@69: new_y = text.winfo_rooty() + y jpayne@69: if (text_height - (y + cy) >= acw_height # enough height below jpayne@69: or y < acw_height): # not enough height above jpayne@69: # place acw below current line jpayne@69: new_y += cy jpayne@69: else: jpayne@69: # place acw above current line jpayne@69: new_y -= acw_height jpayne@69: acw.wm_geometry("+%d+%d" % (new_x, new_y)) jpayne@69: acw.update_idletasks() jpayne@69: jpayne@69: if platform.system().startswith('Windows'): jpayne@69: # See issue 15786. When on Windows platform, Tk will misbehave jpayne@69: # to call winconfig_event multiple times, we need to prevent this, jpayne@69: # otherwise mouse button double click will not be able to used. jpayne@69: acw.unbind(WINCONFIG_SEQUENCE, self.winconfigid) jpayne@69: self.winconfigid = None jpayne@69: jpayne@69: self.is_configuring = False jpayne@69: jpayne@69: def _hide_event_check(self): jpayne@69: if not self.autocompletewindow: jpayne@69: return jpayne@69: jpayne@69: try: jpayne@69: if not self.autocompletewindow.focus_get(): jpayne@69: self.hide_window() jpayne@69: except KeyError: jpayne@69: # See issue 734176, when user click on menu, acw.focus_get() jpayne@69: # will get KeyError. jpayne@69: self.hide_window() jpayne@69: jpayne@69: def hide_event(self, event): jpayne@69: # Hide autocomplete list if it exists and does not have focus or jpayne@69: # mouse click on widget / text area. jpayne@69: if self.is_active(): jpayne@69: if event.type == EventType.FocusOut: jpayne@69: # On Windows platform, it will need to delay the check for jpayne@69: # acw.focus_get() when click on acw, otherwise it will return jpayne@69: # None and close the window jpayne@69: self.widget.after(1, self._hide_event_check) jpayne@69: elif event.type == EventType.ButtonPress: jpayne@69: # ButtonPress event only bind to self.widget jpayne@69: self.hide_window() jpayne@69: jpayne@69: def listselect_event(self, event): jpayne@69: if self.is_active(): jpayne@69: self.userwantswindow = True jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: self._change_start(self.completions[cursel]) jpayne@69: jpayne@69: def doubleclick_event(self, event): jpayne@69: # Put the selected completion in the text, and close the list jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: self._change_start(self.completions[cursel]) jpayne@69: self.hide_window() jpayne@69: jpayne@69: def keypress_event(self, event): jpayne@69: if not self.is_active(): jpayne@69: return None jpayne@69: keysym = event.keysym jpayne@69: if hasattr(event, "mc_state"): jpayne@69: state = event.mc_state jpayne@69: else: jpayne@69: state = 0 jpayne@69: if keysym != "Tab": jpayne@69: self.lastkey_was_tab = False jpayne@69: if (len(keysym) == 1 or keysym in ("underscore", "BackSpace") jpayne@69: or (self.mode == FILES and keysym in jpayne@69: ("period", "minus"))) \ jpayne@69: and not (state & ~MC_SHIFT): jpayne@69: # Normal editing of text jpayne@69: if len(keysym) == 1: jpayne@69: self._change_start(self.start + keysym) jpayne@69: elif keysym == "underscore": jpayne@69: self._change_start(self.start + '_') jpayne@69: elif keysym == "period": jpayne@69: self._change_start(self.start + '.') jpayne@69: elif keysym == "minus": jpayne@69: self._change_start(self.start + '-') jpayne@69: else: jpayne@69: # keysym == "BackSpace" jpayne@69: if len(self.start) == 0: jpayne@69: self.hide_window() jpayne@69: return None jpayne@69: self._change_start(self.start[:-1]) jpayne@69: self.lasttypedstart = self.start jpayne@69: self.listbox.select_clear(0, int(self.listbox.curselection()[0])) jpayne@69: self.listbox.select_set(self._binary_search(self.start)) jpayne@69: self._selection_changed() jpayne@69: return "break" jpayne@69: jpayne@69: elif keysym == "Return": jpayne@69: self.complete() jpayne@69: self.hide_window() jpayne@69: return 'break' jpayne@69: jpayne@69: elif (self.mode == ATTRS and keysym in jpayne@69: ("period", "space", "parenleft", "parenright", "bracketleft", jpayne@69: "bracketright")) or \ jpayne@69: (self.mode == FILES and keysym in jpayne@69: ("slash", "backslash", "quotedbl", "apostrophe")) \ jpayne@69: and not (state & ~MC_SHIFT): jpayne@69: # If start is a prefix of the selection, but is not '' when jpayne@69: # completing file names, put the whole jpayne@69: # selected completion. Anyway, close the list. jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: if self.completions[cursel][:len(self.start)] == self.start \ jpayne@69: and (self.mode == ATTRS or self.start): jpayne@69: self._change_start(self.completions[cursel]) jpayne@69: self.hide_window() jpayne@69: return None jpayne@69: jpayne@69: elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \ jpayne@69: not state: jpayne@69: # Move the selection in the listbox jpayne@69: self.userwantswindow = True jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: if keysym == "Home": jpayne@69: newsel = 0 jpayne@69: elif keysym == "End": jpayne@69: newsel = len(self.completions)-1 jpayne@69: elif keysym in ("Prior", "Next"): jpayne@69: jump = self.listbox.nearest(self.listbox.winfo_height()) - \ jpayne@69: self.listbox.nearest(0) jpayne@69: if keysym == "Prior": jpayne@69: newsel = max(0, cursel-jump) jpayne@69: else: jpayne@69: assert keysym == "Next" jpayne@69: newsel = min(len(self.completions)-1, cursel+jump) jpayne@69: elif keysym == "Up": jpayne@69: newsel = max(0, cursel-1) jpayne@69: else: jpayne@69: assert keysym == "Down" jpayne@69: newsel = min(len(self.completions)-1, cursel+1) jpayne@69: self.listbox.select_clear(cursel) jpayne@69: self.listbox.select_set(newsel) jpayne@69: self._selection_changed() jpayne@69: self._change_start(self.completions[newsel]) jpayne@69: return "break" jpayne@69: jpayne@69: elif (keysym == "Tab" and not state): jpayne@69: if self.lastkey_was_tab: jpayne@69: # two tabs in a row; insert current selection and close acw jpayne@69: cursel = int(self.listbox.curselection()[0]) jpayne@69: self._change_start(self.completions[cursel]) jpayne@69: self.hide_window() jpayne@69: return "break" jpayne@69: else: jpayne@69: # first tab; let AutoComplete handle the completion jpayne@69: self.userwantswindow = True jpayne@69: self.lastkey_was_tab = True jpayne@69: return None jpayne@69: jpayne@69: elif any(s in keysym for s in ("Shift", "Control", "Alt", jpayne@69: "Meta", "Command", "Option")): jpayne@69: # A modifier key, so ignore jpayne@69: return None jpayne@69: jpayne@69: elif event.char and event.char >= ' ': jpayne@69: # Regular character with a non-length-1 keycode jpayne@69: self._change_start(self.start + event.char) jpayne@69: self.lasttypedstart = self.start jpayne@69: self.listbox.select_clear(0, int(self.listbox.curselection()[0])) jpayne@69: self.listbox.select_set(self._binary_search(self.start)) jpayne@69: self._selection_changed() jpayne@69: return "break" jpayne@69: jpayne@69: else: jpayne@69: # Unknown event, close the window and let it through. jpayne@69: self.hide_window() jpayne@69: return None jpayne@69: jpayne@69: def keyrelease_event(self, event): jpayne@69: if not self.is_active(): jpayne@69: return jpayne@69: if self.widget.index("insert") != \ jpayne@69: self.widget.index("%s+%dc" % (self.startindex, len(self.start))): jpayne@69: # If we didn't catch an event which moved the insert, close window jpayne@69: self.hide_window() jpayne@69: jpayne@69: def is_active(self): jpayne@69: return self.autocompletewindow is not None jpayne@69: jpayne@69: def complete(self): jpayne@69: self._change_start(self._complete_string(self.start)) jpayne@69: # The selection doesn't change. jpayne@69: jpayne@69: def hide_window(self): jpayne@69: if not self.is_active(): jpayne@69: return jpayne@69: jpayne@69: # unbind events jpayne@69: self.autocompletewindow.event_delete(HIDE_VIRTUAL_EVENT_NAME, jpayne@69: HIDE_FOCUS_OUT_SEQUENCE) jpayne@69: for seq in HIDE_SEQUENCES: jpayne@69: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) jpayne@69: jpayne@69: self.autocompletewindow.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideaid) jpayne@69: self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hidewid) jpayne@69: self.hideaid = None jpayne@69: self.hidewid = None jpayne@69: for seq in KEYPRESS_SEQUENCES: jpayne@69: self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq) jpayne@69: self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid) jpayne@69: self.keypressid = None jpayne@69: self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME, jpayne@69: KEYRELEASE_SEQUENCE) jpayne@69: self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid) jpayne@69: self.keyreleaseid = None jpayne@69: self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid) jpayne@69: self.listupdateid = None jpayne@69: if self.winconfigid: jpayne@69: self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid) jpayne@69: self.winconfigid = None jpayne@69: jpayne@69: # Re-focusOn frame.text (See issue #15786) jpayne@69: self.widget.focus_set() jpayne@69: jpayne@69: # destroy widgets jpayne@69: self.scrollbar.destroy() jpayne@69: self.scrollbar = None jpayne@69: self.listbox.destroy() jpayne@69: self.listbox = None jpayne@69: self.autocompletewindow.destroy() jpayne@69: self.autocompletewindow = None jpayne@69: jpayne@69: jpayne@69: if __name__ == '__main__': jpayne@69: from unittest import main jpayne@69: main('idlelib.idle_test.test_autocomplete_w', verbosity=2, exit=False) jpayne@69: jpayne@69: # TODO: autocomplete/w htest here