AutoCompleteWindow.py 17 KB

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