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