autocomplete_w.py 20 KB

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