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