/Lib/idlelib/AutoCompleteWindow.py

http://unladen-swallow.googlecode.com/ · Python · 407 lines · 357 code · 13 blank · 37 comment · 22 complexity · 6d5c30a383c582072e498b9e2a390dc0 MD5 · raw file

  1. """
  2. An auto-completion window for IDLE, used by the AutoComplete extension
  3. """
  4. from Tkinter import *
  5. from MultiCall import MC_SHIFT
  6. import AutoComplete
  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. self._change_start(completed)
  148. i = self._binary_search(completed)
  149. if self.completions[i] == completed and \
  150. (i == len(self.completions)-1 or
  151. self.completions[i+1][:len(completed)] != completed):
  152. # There is exactly one matching completion
  153. return
  154. self.userwantswindow = userWantsWin
  155. self.lasttypedstart = self.start
  156. # Put widgets in place
  157. self.autocompletewindow = acw = Toplevel(self.widget)
  158. # Put it in a position so that it is not seen.
  159. acw.wm_geometry("+10000+10000")
  160. # Make it float
  161. acw.wm_overrideredirect(1)
  162. try:
  163. # This command is only needed and available on Tk >= 8.4.0 for OSX
  164. # Without it, call tips intrude on the typing process by grabbing
  165. # the focus.
  166. acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
  167. "help", "noActivates")
  168. except TclError:
  169. pass
  170. self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
  171. self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
  172. exportselection=False, bg="white")
  173. for item in self.completions:
  174. listbox.insert(END, item)
  175. self.origselforeground = listbox.cget("selectforeground")
  176. self.origselbackground = listbox.cget("selectbackground")
  177. scrollbar.config(command=listbox.yview)
  178. scrollbar.pack(side=RIGHT, fill=Y)
  179. listbox.pack(side=LEFT, fill=BOTH, expand=True)
  180. # Initialize the listbox selection
  181. self.listbox.select_set(self._binary_search(self.start))
  182. self._selection_changed()
  183. # bind events
  184. self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
  185. self.hide_event)
  186. for seq in HIDE_SEQUENCES:
  187. self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
  188. self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
  189. self.keypress_event)
  190. for seq in KEYPRESS_SEQUENCES:
  191. self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
  192. self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
  193. self.keyrelease_event)
  194. self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
  195. self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
  196. self.listselect_event)
  197. self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
  198. self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
  199. self.doubleclick_event)
  200. def winconfig_event(self, event):
  201. if not self.is_active():
  202. return
  203. # Position the completion list window
  204. text = self.widget
  205. text.see(self.startindex)
  206. x, y, cx, cy = text.bbox(self.startindex)
  207. acw = self.autocompletewindow
  208. acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
  209. text_width, text_height = text.winfo_width(), text.winfo_height()
  210. new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
  211. new_y = text.winfo_rooty() + y
  212. if (text_height - (y + cy) >= acw_height # enough height below
  213. or y < acw_height): # not enough height above
  214. # place acw below current line
  215. new_y += cy
  216. else:
  217. # place acw above current line
  218. new_y -= acw_height
  219. acw.wm_geometry("+%d+%d" % (new_x, new_y))
  220. def hide_event(self, event):
  221. if not self.is_active():
  222. return
  223. self.hide_window()
  224. def listselect_event(self, event):
  225. if not self.is_active():
  226. return
  227. self.userwantswindow = True
  228. cursel = int(self.listbox.curselection()[0])
  229. self._change_start(self.completions[cursel])
  230. def doubleclick_event(self, event):
  231. # Put the selected completion in the text, and close the list
  232. cursel = int(self.listbox.curselection()[0])
  233. self._change_start(self.completions[cursel])
  234. self.hide_window()
  235. def keypress_event(self, event):
  236. if not self.is_active():
  237. return
  238. keysym = event.keysym
  239. if hasattr(event, "mc_state"):
  240. state = event.mc_state
  241. else:
  242. state = 0
  243. if keysym != "Tab":
  244. self.lastkey_was_tab = False
  245. if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
  246. or (self.mode==AutoComplete.COMPLETE_FILES and keysym in
  247. ("period", "minus"))) \
  248. and not (state & ~MC_SHIFT):
  249. # Normal editing of text
  250. if len(keysym) == 1:
  251. self._change_start(self.start + keysym)
  252. elif keysym == "underscore":
  253. self._change_start(self.start + '_')
  254. elif keysym == "period":
  255. self._change_start(self.start + '.')
  256. elif keysym == "minus":
  257. self._change_start(self.start + '-')
  258. else:
  259. # keysym == "BackSpace"
  260. if len(self.start) == 0:
  261. self.hide_window()
  262. return
  263. self._change_start(self.start[:-1])
  264. self.lasttypedstart = self.start
  265. self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
  266. self.listbox.select_set(self._binary_search(self.start))
  267. self._selection_changed()
  268. return "break"
  269. elif keysym == "Return":
  270. self.hide_window()
  271. return
  272. elif (self.mode == AutoComplete.COMPLETE_ATTRIBUTES and keysym in
  273. ("period", "space", "parenleft", "parenright", "bracketleft",
  274. "bracketright")) or \
  275. (self.mode == AutoComplete.COMPLETE_FILES and keysym in
  276. ("slash", "backslash", "quotedbl", "apostrophe")) \
  277. and not (state & ~MC_SHIFT):
  278. # If start is a prefix of the selection, but is not '' when
  279. # completing file names, put the whole
  280. # selected completion. Anyway, close the list.
  281. cursel = int(self.listbox.curselection()[0])
  282. if self.completions[cursel][:len(self.start)] == self.start \
  283. and (self.mode==AutoComplete.COMPLETE_ATTRIBUTES or self.start):
  284. self._change_start(self.completions[cursel])
  285. self.hide_window()
  286. return
  287. elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
  288. not state:
  289. # Move the selection in the listbox
  290. self.userwantswindow = True
  291. cursel = int(self.listbox.curselection()[0])
  292. if keysym == "Home":
  293. newsel = 0
  294. elif keysym == "End":
  295. newsel = len(self.completions)-1
  296. elif keysym in ("Prior", "Next"):
  297. jump = self.listbox.nearest(self.listbox.winfo_height()) - \
  298. self.listbox.nearest(0)
  299. if keysym == "Prior":
  300. newsel = max(0, cursel-jump)
  301. else:
  302. assert keysym == "Next"
  303. newsel = min(len(self.completions)-1, cursel+jump)
  304. elif keysym == "Up":
  305. newsel = max(0, cursel-1)
  306. else:
  307. assert keysym == "Down"
  308. newsel = min(len(self.completions)-1, cursel+1)
  309. self.listbox.select_clear(cursel)
  310. self.listbox.select_set(newsel)
  311. self._selection_changed()
  312. self._change_start(self.completions[newsel])
  313. return "break"
  314. elif (keysym == "Tab" and not state):
  315. if self.lastkey_was_tab:
  316. # two tabs in a row; insert current selection and close acw
  317. cursel = int(self.listbox.curselection()[0])
  318. self._change_start(self.completions[cursel])
  319. self.hide_window()
  320. return "break"
  321. else:
  322. # first tab; let AutoComplete handle the completion
  323. self.userwantswindow = True
  324. self.lastkey_was_tab = True
  325. return
  326. elif reduce(lambda x, y: x or y,
  327. [keysym.find(s) != -1 for s in ("Shift", "Control", "Alt",
  328. "Meta", "Command", "Option")
  329. ]):
  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