rlcompleter.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Word completion for GNU readline.
  2. The completer completes keywords, built-ins and globals in a selectable
  3. namespace (which defaults to __main__); when completing NAME.NAME..., it
  4. evaluates (!) the expression up to the last dot and completes its attributes.
  5. It's very cool to do "import sys" type "sys.", hit the completion key (twice),
  6. and see the list of names defined by the sys module!
  7. Tip: to use the tab key as the completion key, call
  8. readline.parse_and_bind("tab: complete")
  9. Notes:
  10. - Exceptions raised by the completer function are *ignored* (and generally cause
  11. the completion to fail). This is a feature -- since readline sets the tty
  12. device in raw (or cbreak) mode, printing a traceback wouldn't work well
  13. without some complicated hoopla to save, reset and restore the tty state.
  14. - The evaluation of the NAME.NAME... form may cause arbitrary application
  15. defined code to be executed if an object with a __getattr__ hook is found.
  16. Since it is the responsibility of the application (or the user) to enable this
  17. feature, I consider this an acceptable risk. More complicated expressions
  18. (e.g. function calls or indexing operations) are *not* evaluated.
  19. - When the original stdin is not a tty device, GNU readline is never
  20. used, and this module (and the readline module) are silently inactive.
  21. """
  22. import atexit
  23. import builtins
  24. import inspect
  25. import keyword
  26. import re
  27. import __main__
  28. __all__ = ["Completer"]
  29. class Completer:
  30. def __init__(self, namespace = None):
  31. """Create a new completer for the command line.
  32. Completer([namespace]) -> completer instance.
  33. If unspecified, the default namespace where completions are performed
  34. is __main__ (technically, __main__.__dict__). Namespaces should be
  35. given as dictionaries.
  36. Completer instances should be used as the completion mechanism of
  37. readline via the set_completer() call:
  38. readline.set_completer(Completer(my_namespace).complete)
  39. """
  40. if namespace and not isinstance(namespace, dict):
  41. raise TypeError('namespace must be a dictionary')
  42. # Don't bind to namespace quite yet, but flag whether the user wants a
  43. # specific namespace or to use __main__.__dict__. This will allow us
  44. # to bind to __main__.__dict__ at completion time, not now.
  45. if namespace is None:
  46. self.use_main_ns = 1
  47. else:
  48. self.use_main_ns = 0
  49. self.namespace = namespace
  50. def complete(self, text, state):
  51. """Return the next possible completion for 'text'.
  52. This is called successively with state == 0, 1, 2, ... until it
  53. returns None. The completion should begin with 'text'.
  54. """
  55. if self.use_main_ns:
  56. self.namespace = __main__.__dict__
  57. if not text.strip():
  58. if state == 0:
  59. if _readline_available:
  60. readline.insert_text('\t')
  61. readline.redisplay()
  62. return ''
  63. else:
  64. return '\t'
  65. else:
  66. return None
  67. if state == 0:
  68. if "." in text:
  69. self.matches = self.attr_matches(text)
  70. else:
  71. self.matches = self.global_matches(text)
  72. try:
  73. return self.matches[state]
  74. except IndexError:
  75. return None
  76. def _callable_postfix(self, val, word):
  77. if callable(val):
  78. word += "("
  79. try:
  80. if not inspect.signature(val).parameters:
  81. word += ")"
  82. except ValueError:
  83. pass
  84. return word
  85. def global_matches(self, text):
  86. """Compute matches when text is a simple name.
  87. Return a list of all keywords, built-in functions and names currently
  88. defined in self.namespace that match.
  89. """
  90. matches = []
  91. seen = {"__builtins__"}
  92. n = len(text)
  93. for word in keyword.kwlist + keyword.softkwlist:
  94. if word[:n] == text:
  95. seen.add(word)
  96. if word in {'finally', 'try'}:
  97. word = word + ':'
  98. elif word not in {'False', 'None', 'True',
  99. 'break', 'continue', 'pass',
  100. 'else', '_'}:
  101. word = word + ' '
  102. matches.append(word)
  103. for nspace in [self.namespace, builtins.__dict__]:
  104. for word, val in nspace.items():
  105. if word[:n] == text and word not in seen:
  106. seen.add(word)
  107. matches.append(self._callable_postfix(val, word))
  108. return matches
  109. def attr_matches(self, text):
  110. """Compute matches when text contains a dot.
  111. Assuming the text is of the form NAME.NAME....[NAME], and is
  112. evaluable in self.namespace, it will be evaluated and its attributes
  113. (as revealed by dir()) are used as possible completions. (For class
  114. instances, class members are also considered.)
  115. WARNING: this can still invoke arbitrary C code, if an object
  116. with a __getattr__ hook is evaluated.
  117. """
  118. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  119. if not m:
  120. return []
  121. expr, attr = m.group(1, 3)
  122. try:
  123. thisobject = eval(expr, self.namespace)
  124. except Exception:
  125. return []
  126. # get the content of the object, except __builtins__
  127. words = set(dir(thisobject))
  128. words.discard("__builtins__")
  129. if hasattr(thisobject, '__class__'):
  130. words.add('__class__')
  131. words.update(get_class_members(thisobject.__class__))
  132. matches = []
  133. n = len(attr)
  134. if attr == '':
  135. noprefix = '_'
  136. elif attr == '_':
  137. noprefix = '__'
  138. else:
  139. noprefix = None
  140. while True:
  141. for word in words:
  142. if (word[:n] == attr and
  143. not (noprefix and word[:n+1] == noprefix)):
  144. match = "%s.%s" % (expr, word)
  145. if isinstance(getattr(type(thisobject), word, None),
  146. property):
  147. # bpo-44752: thisobject.word is a method decorated by
  148. # `@property`. What follows applies a postfix if
  149. # thisobject.word is callable, but know we know that
  150. # this is not callable (because it is a property).
  151. # Also, getattr(thisobject, word) will evaluate the
  152. # property method, which is not desirable.
  153. matches.append(match)
  154. continue
  155. if (value := getattr(thisobject, word, None)) is not None:
  156. matches.append(self._callable_postfix(value, match))
  157. else:
  158. matches.append(match)
  159. if matches or not noprefix:
  160. break
  161. if noprefix == '_':
  162. noprefix = '__'
  163. else:
  164. noprefix = None
  165. matches.sort()
  166. return matches
  167. def get_class_members(klass):
  168. ret = dir(klass)
  169. if hasattr(klass,'__bases__'):
  170. for base in klass.__bases__:
  171. ret = ret + get_class_members(base)
  172. return ret
  173. try:
  174. import readline
  175. except ImportError:
  176. _readline_available = False
  177. else:
  178. readline.set_completer(Completer().complete)
  179. # Release references early at shutdown (the readline module's
  180. # contents are quasi-immortal, and the completer function holds a
  181. # reference to globals).
  182. atexit.register(lambda: readline.set_completer(None))
  183. _readline_available = True