autocomplete.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Complete either attribute names or file names.
  2. Either on demand or after a user-selected delay after a key character,
  3. pop up a list of candidates.
  4. """
  5. import __main__
  6. import keyword
  7. import os
  8. import string
  9. import sys
  10. # Two types of completions; defined here for autocomplete_w import below.
  11. ATTRS, FILES = 0, 1
  12. from idlelib import autocomplete_w
  13. from idlelib.config import idleConf
  14. from idlelib.hyperparser import HyperParser
  15. # Tuples passed to open_completions.
  16. # EvalFunc, Complete, WantWin, Mode
  17. FORCE = True, False, True, None # Control-Space.
  18. TAB = False, True, True, None # Tab.
  19. TRY_A = False, False, False, ATTRS # '.' for attributes.
  20. TRY_F = False, False, False, FILES # '/' in quotes for file name.
  21. # This string includes all chars that may be in an identifier.
  22. # TODO Update this here and elsewhere.
  23. ID_CHARS = string.ascii_letters + string.digits + "_"
  24. SEPS = f"{os.sep}{os.altsep if os.altsep else ''}"
  25. TRIGGERS = f".{SEPS}"
  26. class AutoComplete:
  27. def __init__(self, editwin=None):
  28. self.editwin = editwin
  29. if editwin is not None: # not in subprocess or no-gui test
  30. self.text = editwin.text
  31. self.autocompletewindow = None
  32. # id of delayed call, and the index of the text insert when
  33. # the delayed call was issued. If _delayed_completion_id is
  34. # None, there is no delayed call.
  35. self._delayed_completion_id = None
  36. self._delayed_completion_index = None
  37. @classmethod
  38. def reload(cls):
  39. cls.popupwait = idleConf.GetOption(
  40. "extensions", "AutoComplete", "popupwait", type="int", default=0)
  41. def _make_autocomplete_window(self): # Makes mocking easier.
  42. return autocomplete_w.AutoCompleteWindow(self.text)
  43. def _remove_autocomplete_window(self, event=None):
  44. if self.autocompletewindow:
  45. self.autocompletewindow.hide_window()
  46. self.autocompletewindow = None
  47. def force_open_completions_event(self, event):
  48. "(^space) Open completion list, even if a function call is needed."
  49. self.open_completions(FORCE)
  50. return "break"
  51. def autocomplete_event(self, event):
  52. "(tab) Complete word or open list if multiple options."
  53. if hasattr(event, "mc_state") and event.mc_state or\
  54. not self.text.get("insert linestart", "insert").strip():
  55. # A modifier was pressed along with the tab or
  56. # there is only previous whitespace on this line, so tab.
  57. return None
  58. if self.autocompletewindow and self.autocompletewindow.is_active():
  59. self.autocompletewindow.complete()
  60. return "break"
  61. else:
  62. opened = self.open_completions(TAB)
  63. return "break" if opened else None
  64. def try_open_completions_event(self, event=None):
  65. "(./) Open completion list after pause with no movement."
  66. lastchar = self.text.get("insert-1c")
  67. if lastchar in TRIGGERS:
  68. args = TRY_A if lastchar == "." else TRY_F
  69. self._delayed_completion_index = self.text.index("insert")
  70. if self._delayed_completion_id is not None:
  71. self.text.after_cancel(self._delayed_completion_id)
  72. self._delayed_completion_id = self.text.after(
  73. self.popupwait, self._delayed_open_completions, args)
  74. def _delayed_open_completions(self, args):
  75. "Call open_completions if index unchanged."
  76. self._delayed_completion_id = None
  77. if self.text.index("insert") == self._delayed_completion_index:
  78. self.open_completions(args)
  79. def open_completions(self, args):
  80. """Find the completions and create the AutoCompleteWindow.
  81. Return True if successful (no syntax error or so found).
  82. If complete is True, then if there's nothing to complete and no
  83. start of completion, won't open completions and return False.
  84. If mode is given, will open a completion list only in this mode.
  85. """
  86. evalfuncs, complete, wantwin, mode = args
  87. # Cancel another delayed call, if it exists.
  88. if self._delayed_completion_id is not None:
  89. self.text.after_cancel(self._delayed_completion_id)
  90. self._delayed_completion_id = None
  91. hp = HyperParser(self.editwin, "insert")
  92. curline = self.text.get("insert linestart", "insert")
  93. i = j = len(curline)
  94. if hp.is_in_string() and (not mode or mode==FILES):
  95. # Find the beginning of the string.
  96. # fetch_completions will look at the file system to determine
  97. # whether the string value constitutes an actual file name
  98. # XXX could consider raw strings here and unescape the string
  99. # value if it's not raw.
  100. self._remove_autocomplete_window()
  101. mode = FILES
  102. # Find last separator or string start
  103. while i and curline[i-1] not in "'\"" + SEPS:
  104. i -= 1
  105. comp_start = curline[i:j]
  106. j = i
  107. # Find string start
  108. while i and curline[i-1] not in "'\"":
  109. i -= 1
  110. comp_what = curline[i:j]
  111. elif hp.is_in_code() and (not mode or mode==ATTRS):
  112. self._remove_autocomplete_window()
  113. mode = ATTRS
  114. while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127):
  115. i -= 1
  116. comp_start = curline[i:j]
  117. if i and curline[i-1] == '.': # Need object with attributes.
  118. hp.set_index("insert-%dc" % (len(curline)-(i-1)))
  119. comp_what = hp.get_expression()
  120. if (not comp_what or
  121. (not evalfuncs and comp_what.find('(') != -1)):
  122. return None
  123. else:
  124. comp_what = ""
  125. else:
  126. return None
  127. if complete and not comp_what and not comp_start:
  128. return None
  129. comp_lists = self.fetch_completions(comp_what, mode)
  130. if not comp_lists[0]:
  131. return None
  132. self.autocompletewindow = self._make_autocomplete_window()
  133. return not self.autocompletewindow.show_window(
  134. comp_lists, "insert-%dc" % len(comp_start),
  135. complete, mode, wantwin)
  136. def fetch_completions(self, what, mode):
  137. """Return a pair of lists of completions for something. The first list
  138. is a sublist of the second. Both are sorted.
  139. If there is a Python subprocess, get the comp. list there. Otherwise,
  140. either fetch_completions() is running in the subprocess itself or it
  141. was called in an IDLE EditorWindow before any script had been run.
  142. The subprocess environment is that of the most recently run script. If
  143. two unrelated modules are being edited some calltips in the current
  144. module may be inoperative if the module was not the last to run.
  145. """
  146. try:
  147. rpcclt = self.editwin.flist.pyshell.interp.rpcclt
  148. except:
  149. rpcclt = None
  150. if rpcclt:
  151. return rpcclt.remotecall("exec", "get_the_completion_list",
  152. (what, mode), {})
  153. else:
  154. if mode == ATTRS:
  155. if what == "": # Main module names.
  156. namespace = {**__main__.__builtins__.__dict__,
  157. **__main__.__dict__}
  158. bigl = eval("dir()", namespace)
  159. kwds = (s for s in keyword.kwlist
  160. if s not in {'True', 'False', 'None'})
  161. bigl.extend(kwds)
  162. bigl.sort()
  163. if "__all__" in bigl:
  164. smalll = sorted(eval("__all__", namespace))
  165. else:
  166. smalll = [s for s in bigl if s[:1] != '_']
  167. else:
  168. try:
  169. entity = self.get_entity(what)
  170. bigl = dir(entity)
  171. bigl.sort()
  172. if "__all__" in bigl:
  173. smalll = sorted(entity.__all__)
  174. else:
  175. smalll = [s for s in bigl if s[:1] != '_']
  176. except:
  177. return [], []
  178. elif mode == FILES:
  179. if what == "":
  180. what = "."
  181. try:
  182. expandedpath = os.path.expanduser(what)
  183. bigl = os.listdir(expandedpath)
  184. bigl.sort()
  185. smalll = [s for s in bigl if s[:1] != '.']
  186. except OSError:
  187. return [], []
  188. if not smalll:
  189. smalll = bigl
  190. return smalll, bigl
  191. def get_entity(self, name):
  192. "Lookup name in a namespace spanning sys.modules and __main.dict__."
  193. return eval(name, {**sys.modules, **__main__.__dict__})
  194. AutoComplete.reload()
  195. if __name__ == '__main__':
  196. from unittest import main
  197. main('idlelib.idle_test.test_autocomplete', verbosity=2)