logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

autocomplete.py (9202B)


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