autocomplete.py 9.1 KB

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