rlcompleter.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. - GNU readline is also used by the built-in functions input() and
  20. raw_input(), and thus these also benefit/suffer from the completer
  21. features. Clearly an interactive application can benefit by
  22. specifying its own completer function and using raw_input() for all
  23. its input.
  24. - When the original stdin is not a tty device, GNU readline is never
  25. used, and this module (and the readline module) are silently inactive.
  26. """
  27. import __builtin__
  28. import __main__
  29. __all__ = ["Completer"]
  30. class Completer:
  31. def __init__(self, namespace = None):
  32. """Create a new completer for the command line.
  33. Completer([namespace]) -> completer instance.
  34. If unspecified, the default namespace where completions are performed
  35. is __main__ (technically, __main__.__dict__). Namespaces should be
  36. given as dictionaries.
  37. Completer instances should be used as the completion mechanism of
  38. readline via the set_completer() call:
  39. readline.set_completer(Completer(my_namespace).complete)
  40. """
  41. if namespace and not isinstance(namespace, dict):
  42. raise TypeError,'namespace must be a dictionary'
  43. # Don't bind to namespace quite yet, but flag whether the user wants a
  44. # specific namespace or to use __main__.__dict__. This will allow us
  45. # to bind to __main__.__dict__ at completion time, not now.
  46. if namespace is None:
  47. self.use_main_ns = 1
  48. else:
  49. self.use_main_ns = 0
  50. self.namespace = namespace
  51. def complete(self, text, state):
  52. """Return the next possible completion for 'text'.
  53. This is called successively with state == 0, 1, 2, ... until it
  54. returns None. The completion should begin with 'text'.
  55. """
  56. if self.use_main_ns:
  57. self.namespace = __main__.__dict__
  58. if state == 0:
  59. if "." in text:
  60. self.matches = self.attr_matches(text)
  61. else:
  62. self.matches = self.global_matches(text)
  63. try:
  64. return self.matches[state]
  65. except IndexError:
  66. return None
  67. def _callable_postfix(self, val, word):
  68. if hasattr(val, '__call__'):
  69. word = word + "("
  70. return word
  71. def global_matches(self, text):
  72. """Compute matches when text is a simple name.
  73. Return a list of all keywords, built-in functions and names currently
  74. defined in self.namespace that match.
  75. """
  76. import keyword
  77. matches = []
  78. seen = {"__builtins__"}
  79. n = len(text)
  80. for word in keyword.kwlist:
  81. if word[:n] == text:
  82. seen.add(word)
  83. matches.append(word)
  84. for nspace in [self.namespace, __builtin__.__dict__]:
  85. for word, val in nspace.items():
  86. if word[:n] == text and word not in seen:
  87. seen.add(word)
  88. matches.append(self._callable_postfix(val, word))
  89. return matches
  90. def attr_matches(self, text):
  91. """Compute matches when text contains a dot.
  92. Assuming the text is of the form NAME.NAME....[NAME], and is
  93. evaluable in self.namespace, it will be evaluated and its attributes
  94. (as revealed by dir()) are used as possible completions. (For class
  95. instances, class members are also considered.)
  96. WARNING: this can still invoke arbitrary C code, if an object
  97. with a __getattr__ hook is evaluated.
  98. """
  99. import re
  100. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  101. if not m:
  102. return []
  103. expr, attr = m.group(1, 3)
  104. try:
  105. thisobject = eval(expr, self.namespace)
  106. except Exception:
  107. return []
  108. # get the content of the object, except __builtins__
  109. words = set(dir(thisobject))
  110. words.discard("__builtins__")
  111. if hasattr(thisobject, '__class__'):
  112. words.add('__class__')
  113. words.update(get_class_members(thisobject.__class__))
  114. matches = []
  115. n = len(attr)
  116. for word in words:
  117. if word[:n] == attr:
  118. try:
  119. val = getattr(thisobject, word)
  120. except Exception:
  121. continue # Exclude properties that are not set
  122. word = self._callable_postfix(val, "%s.%s" % (expr, word))
  123. matches.append(word)
  124. matches.sort()
  125. return matches
  126. def get_class_members(klass):
  127. ret = dir(klass)
  128. if hasattr(klass,'__bases__'):
  129. for base in klass.__bases__:
  130. ret = ret + get_class_members(base)
  131. return ret
  132. try:
  133. import readline
  134. except ImportError:
  135. pass
  136. else:
  137. readline.set_completer(Completer().complete)