rlcompleter.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 __main__
  25. __all__ = ["Completer"]
  26. class Completer:
  27. def __init__(self, namespace = None):
  28. """Create a new completer for the command line.
  29. Completer([namespace]) -> completer instance.
  30. If unspecified, the default namespace where completions are performed
  31. is __main__ (technically, __main__.__dict__). Namespaces should be
  32. given as dictionaries.
  33. Completer instances should be used as the completion mechanism of
  34. readline via the set_completer() call:
  35. readline.set_completer(Completer(my_namespace).complete)
  36. """
  37. if namespace and not isinstance(namespace, dict):
  38. raise TypeError('namespace must be a dictionary')
  39. # Don't bind to namespace quite yet, but flag whether the user wants a
  40. # specific namespace or to use __main__.__dict__. This will allow us
  41. # to bind to __main__.__dict__ at completion time, not now.
  42. if namespace is None:
  43. self.use_main_ns = 1
  44. else:
  45. self.use_main_ns = 0
  46. self.namespace = namespace
  47. def complete(self, text, state):
  48. """Return the next possible completion for 'text'.
  49. This is called successively with state == 0, 1, 2, ... until it
  50. returns None. The completion should begin with 'text'.
  51. """
  52. if self.use_main_ns:
  53. self.namespace = __main__.__dict__
  54. if not text.strip():
  55. if state == 0:
  56. if _readline_available:
  57. readline.insert_text('\t')
  58. readline.redisplay()
  59. return ''
  60. else:
  61. return '\t'
  62. else:
  63. return None
  64. if state == 0:
  65. if "." in text:
  66. self.matches = self.attr_matches(text)
  67. else:
  68. self.matches = self.global_matches(text)
  69. try:
  70. return self.matches[state]
  71. except IndexError:
  72. return None
  73. def _callable_postfix(self, val, word):
  74. if callable(val):
  75. word = word + "("
  76. return word
  77. def global_matches(self, text):
  78. """Compute matches when text is a simple name.
  79. Return a list of all keywords, built-in functions and names currently
  80. defined in self.namespace that match.
  81. """
  82. import keyword
  83. matches = []
  84. seen = {"__builtins__"}
  85. n = len(text)
  86. for word in keyword.kwlist:
  87. if word[:n] == text:
  88. seen.add(word)
  89. if word in {'finally', 'try'}:
  90. word = word + ':'
  91. elif word not in {'False', 'None', 'True',
  92. 'break', 'continue', 'pass',
  93. 'else'}:
  94. word = word + ' '
  95. matches.append(word)
  96. for nspace in [self.namespace, builtins.__dict__]:
  97. for word, val in nspace.items():
  98. if word[:n] == text and word not in seen:
  99. seen.add(word)
  100. matches.append(self._callable_postfix(val, word))
  101. return matches
  102. def attr_matches(self, text):
  103. """Compute matches when text contains a dot.
  104. Assuming the text is of the form NAME.NAME....[NAME], and is
  105. evaluable in self.namespace, it will be evaluated and its attributes
  106. (as revealed by dir()) are used as possible completions. (For class
  107. instances, class members are also considered.)
  108. WARNING: this can still invoke arbitrary C code, if an object
  109. with a __getattr__ hook is evaluated.
  110. """
  111. import re
  112. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  113. if not m:
  114. return []
  115. expr, attr = m.group(1, 3)
  116. try:
  117. thisobject = eval(expr, self.namespace)
  118. except Exception:
  119. return []
  120. # get the content of the object, except __builtins__
  121. words = set(dir(thisobject))
  122. words.discard("__builtins__")
  123. if hasattr(thisobject, '__class__'):
  124. words.add('__class__')
  125. words.update(get_class_members(thisobject.__class__))
  126. matches = []
  127. n = len(attr)
  128. if attr == '':
  129. noprefix = '_'
  130. elif attr == '_':
  131. noprefix = '__'
  132. else:
  133. noprefix = None
  134. while True:
  135. for word in words:
  136. if (word[:n] == attr and
  137. not (noprefix and word[:n+1] == noprefix)):
  138. match = "%s.%s" % (expr, word)
  139. if isinstance(getattr(type(thisobject), word, None),
  140. property):
  141. # bpo-44752: thisobject.word is a method decorated by
  142. # `@property`. What follows applies a postfix if
  143. # thisobject.word is callable, but know we know that
  144. # this is not callable (because it is a property).
  145. # Also, getattr(thisobject, word) will evaluate the
  146. # property method, which is not desirable.
  147. matches.append(match)
  148. continue
  149. if (value := getattr(thisobject, word, None)) is not None:
  150. matches.append(self._callable_postfix(value, match))
  151. else:
  152. matches.append(match)
  153. if matches or not noprefix:
  154. break
  155. if noprefix == '_':
  156. noprefix = '__'
  157. else:
  158. noprefix = None
  159. matches.sort()
  160. return matches
  161. def get_class_members(klass):
  162. ret = dir(klass)
  163. if hasattr(klass,'__bases__'):
  164. for base in klass.__bases__:
  165. ret = ret + get_class_members(base)
  166. return ret
  167. try:
  168. import readline
  169. except ImportError:
  170. _readline_available = False
  171. else:
  172. readline.set_completer(Completer().complete)
  173. # Release references early at shutdown (the readline module's
  174. # contents are quasi-immortal, and the completer function holds a
  175. # reference to globals).
  176. atexit.register(lambda: readline.set_completer(None))
  177. _readline_available = True