autocomplete_w.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 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.update_idletasks() # Need for tk8.6.8 on macOS: #40128.
  189. acw.lift() # work around bug in Tk 8.5.18+ (issue #24570)
  190. # Initialize the listbox selection
  191. self.listbox.select_set(self._binary_search(self.start))
  192. self._selection_changed()
  193. # bind events
  194. self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
  195. self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
  196. acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE)
  197. for seq in HIDE_SEQUENCES:
  198. self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
  199. self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
  200. self.keypress_event)
  201. for seq in KEYPRESS_SEQUENCES:
  202. self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
  203. self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
  204. self.keyrelease_event)
  205. self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
  206. self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
  207. self.listselect_event)
  208. self.is_configuring = False
  209. self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
  210. self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
  211. self.doubleclick_event)
  212. return None
  213. def winconfig_event(self, event):
  214. if self.is_configuring:
  215. # Avoid running on recursive <Configure> callback invocations.
  216. return
  217. self.is_configuring = True
  218. if not self.is_active():
  219. return
  220. # Since the <Configure> event may occur after the completion window is gone,
  221. # catch potential TclError exceptions when accessing acw. See: bpo-41611.
  222. try:
  223. # Position the completion list window
  224. text = self.widget
  225. text.see(self.startindex)
  226. x, y, cx, cy = text.bbox(self.startindex)
  227. acw = self.autocompletewindow
  228. if platform.system().startswith('Windows'):
  229. # On Windows an update() call is needed for the completion
  230. # list window to be created, so that we can fetch its width
  231. # and height. However, this is not needed on other platforms
  232. # (tested on Ubuntu and macOS) but at one point began
  233. # causing freezes on macOS. See issues 37849 and 41611.
  234. acw.update()
  235. acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
  236. text_width, text_height = text.winfo_width(), text.winfo_height()
  237. new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
  238. new_y = text.winfo_rooty() + y
  239. if (text_height - (y + cy) >= acw_height # enough height below
  240. or y < acw_height): # not enough height above
  241. # place acw below current line
  242. new_y += cy
  243. else:
  244. # place acw above current line
  245. new_y -= acw_height
  246. acw.wm_geometry("+%d+%d" % (new_x, new_y))
  247. acw.update_idletasks()
  248. except TclError:
  249. pass
  250. if platform.system().startswith('Windows'):
  251. # See issue 15786. When on Windows platform, Tk will misbehave
  252. # to call winconfig_event multiple times, we need to prevent this,
  253. # otherwise mouse button double click will not be able to used.
  254. try:
  255. acw.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
  256. except TclError:
  257. pass
  258. self.winconfigid = None
  259. self.is_configuring = False
  260. def _hide_event_check(self):
  261. if not self.autocompletewindow:
  262. return
  263. try:
  264. if not self.autocompletewindow.focus_get():
  265. self.hide_window()
  266. except KeyError:
  267. # See issue 734176, when user click on menu, acw.focus_get()
  268. # will get KeyError.
  269. self.hide_window()
  270. def hide_event(self, event):
  271. # Hide autocomplete list if it exists and does not have focus or
  272. # mouse click on widget / text area.
  273. if self.is_active():
  274. if event.type == EventType.FocusOut:
  275. # On Windows platform, it will need to delay the check for
  276. # acw.focus_get() when click on acw, otherwise it will return
  277. # None and close the window
  278. self.widget.after(1, self._hide_event_check)
  279. elif event.type == EventType.ButtonPress:
  280. # ButtonPress event only bind to self.widget
  281. self.hide_window()
  282. def listselect_event(self, event):
  283. if self.is_active():
  284. self.userwantswindow = True
  285. cursel = int(self.listbox.curselection()[0])
  286. self._change_start(self.completions[cursel])
  287. def doubleclick_event(self, event):
  288. # Put the selected completion in the text, and close the list
  289. cursel = int(self.listbox.curselection()[0])
  290. self._change_start(self.completions[cursel])
  291. self.hide_window()
  292. def keypress_event(self, event):
  293. if not self.is_active():
  294. return None
  295. keysym = event.keysym
  296. if hasattr(event, "mc_state"):
  297. state = event.mc_state
  298. else:
  299. state = 0
  300. if keysym != "Tab":
  301. self.lastkey_was_tab = False
  302. if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
  303. or (self.mode == FILES and keysym in
  304. ("period", "minus"))) \
  305. and not (state & ~MC_SHIFT):
  306. # Normal editing of text
  307. if len(keysym) == 1:
  308. self._change_start(self.start + keysym)
  309. elif keysym == "underscore":
  310. self._change_start(self.start + '_')
  311. elif keysym == "period":
  312. self._change_start(self.start + '.')
  313. elif keysym == "minus":
  314. self._change_start(self.start + '-')
  315. else:
  316. # keysym == "BackSpace"
  317. if len(self.start) == 0:
  318. self.hide_window()
  319. return None
  320. self._change_start(self.start[:-1])
  321. self.lasttypedstart = self.start
  322. self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
  323. self.listbox.select_set(self._binary_search(self.start))
  324. self._selection_changed()
  325. return "break"
  326. elif keysym == "Return":
  327. self.complete()
  328. self.hide_window()
  329. return 'break'
  330. elif (self.mode == ATTRS and keysym in
  331. ("period", "space", "parenleft", "parenright", "bracketleft",
  332. "bracketright")) or \
  333. (self.mode == FILES and keysym in
  334. ("slash", "backslash", "quotedbl", "apostrophe")) \
  335. and not (state & ~MC_SHIFT):
  336. # If start is a prefix of the selection, but is not '' when
  337. # completing file names, put the whole
  338. # selected completion. Anyway, close the list.
  339. cursel = int(self.listbox.curselection()[0])
  340. if self.completions[cursel][:len(self.start)] == self.start \
  341. and (self.mode == ATTRS or self.start):
  342. self._change_start(self.completions[cursel])
  343. self.hide_window()
  344. return None
  345. elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
  346. not state:
  347. # Move the selection in the listbox
  348. self.userwantswindow = True
  349. cursel = int(self.listbox.curselection()[0])
  350. if keysym == "Home":
  351. newsel = 0
  352. elif keysym == "End":
  353. newsel = len(self.completions)-1
  354. elif keysym in ("Prior", "Next"):
  355. jump = self.listbox.nearest(self.listbox.winfo_height()) - \
  356. self.listbox.nearest(0)
  357. if keysym == "Prior":
  358. newsel = max(0, cursel-jump)
  359. else:
  360. assert keysym == "Next"
  361. newsel = min(len(self.completions)-1, cursel+jump)
  362. elif keysym == "Up":
  363. newsel = max(0, cursel-1)
  364. else:
  365. assert keysym == "Down"
  366. newsel = min(len(self.completions)-1, cursel+1)
  367. self.listbox.select_clear(cursel)
  368. self.listbox.select_set(newsel)
  369. self._selection_changed()
  370. self._change_start(self.completions[newsel])
  371. return "break"
  372. elif (keysym == "Tab" and not state):
  373. if self.lastkey_was_tab:
  374. # two tabs in a row; insert current selection and close acw
  375. cursel = int(self.listbox.curselection()[0])
  376. self._change_start(self.completions[cursel])
  377. self.hide_window()
  378. return "break"
  379. else:
  380. # first tab; let AutoComplete handle the completion
  381. self.userwantswindow = True
  382. self.lastkey_was_tab = True
  383. return None
  384. elif any(s in keysym for s in ("Shift", "Control", "Alt",
  385. "Meta", "Command", "Option")):
  386. # A modifier key, so ignore
  387. return None
  388. elif event.char and event.char >= ' ':
  389. # Regular character with a non-length-1 keycode
  390. self._change_start(self.start + event.char)
  391. self.lasttypedstart = self.start
  392. self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
  393. self.listbox.select_set(self._binary_search(self.start))
  394. self._selection_changed()
  395. return "break"
  396. else:
  397. # Unknown event, close the window and let it through.
  398. self.hide_window()
  399. return None
  400. def keyrelease_event(self, event):
  401. if not self.is_active():
  402. return
  403. if self.widget.index("insert") != \
  404. self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
  405. # If we didn't catch an event which moved the insert, close window
  406. self.hide_window()
  407. def is_active(self):
  408. return self.autocompletewindow is not None
  409. def complete(self):
  410. self._change_start(self._complete_string(self.start))
  411. # The selection doesn't change.
  412. def hide_window(self):
  413. if not self.is_active():
  414. return
  415. # unbind events
  416. self.autocompletewindow.event_delete(HIDE_VIRTUAL_EVENT_NAME,
  417. HIDE_FOCUS_OUT_SEQUENCE)
  418. for seq in HIDE_SEQUENCES:
  419. self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
  420. self.autocompletewindow.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideaid)
  421. self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hidewid)
  422. self.hideaid = None
  423. self.hidewid = None
  424. for seq in KEYPRESS_SEQUENCES:
  425. self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
  426. self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
  427. self.keypressid = None
  428. self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
  429. KEYRELEASE_SEQUENCE)
  430. self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
  431. self.keyreleaseid = None
  432. self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
  433. self.listupdateid = None
  434. if self.winconfigid:
  435. self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
  436. self.winconfigid = None
  437. # Re-focusOn frame.text (See issue #15786)
  438. self.widget.focus_set()
  439. # destroy widgets
  440. self.scrollbar.destroy()
  441. self.scrollbar = None
  442. self.listbox.destroy()
  443. self.listbox = None
  444. self.autocompletewindow.destroy()
  445. self.autocompletewindow = None
  446. if __name__ == '__main__':
  447. from unittest import main
  448. main('idlelib.idle_test.test_autocomplete_w', verbosity=2, exit=False)
  449. # TODO: autocomplete/w htest here