autocomplete.py 8.7 KB

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