/Lib/rlcompleter.py

http://unladen-swallow.googlecode.com/ · Python · 170 lines · 156 code · 5 blank · 9 comment · 3 complexity · b326645746ed6ae6f41d19c1084d0ec9 MD5 · raw file

  1. """Word completion for GNU readline 2.0.
  2. This requires the latest extension to the readline module. The completer
  3. completes keywords, built-ins and globals in a selectable namespace (which
  4. defaults to __main__); when completing NAME.NAME..., it evaluates (!) the
  5. expression up to the last dot and completes its attributes.
  6. It's very cool to do "import sys" type "sys.", hit the
  7. completion key (twice), and see the list of names defined by the
  8. sys module!
  9. Tip: to use the tab key as the completion key, call
  10. readline.parse_and_bind("tab: complete")
  11. Notes:
  12. - Exceptions raised by the completer function are *ignored* (and
  13. generally cause the completion to fail). This is a feature -- since
  14. readline sets the tty device in raw (or cbreak) mode, printing a
  15. traceback wouldn't work well without some complicated hoopla to save,
  16. reset and restore the tty state.
  17. - The evaluation of the NAME.NAME... form may cause arbitrary
  18. application defined code to be executed if an object with a
  19. __getattr__ hook is found. Since it is the responsibility of the
  20. application (or the user) to enable this feature, I consider this an
  21. acceptable risk. More complicated expressions (e.g. function calls or
  22. indexing operations) are *not* evaluated.
  23. - GNU readline is also used by the built-in functions input() and
  24. raw_input(), and thus these also benefit/suffer from the completer
  25. features. Clearly an interactive application can benefit by
  26. specifying its own completer function and using raw_input() for all
  27. its input.
  28. - When the original stdin is not a tty device, GNU readline is never
  29. used, and this module (and the readline module) are silently inactive.
  30. """
  31. import __builtin__
  32. import __main__
  33. __all__ = ["Completer"]
  34. class Completer:
  35. def __init__(self, namespace = None):
  36. """Create a new completer for the command line.
  37. Completer([namespace]) -> completer instance.
  38. If unspecified, the default namespace where completions are performed
  39. is __main__ (technically, __main__.__dict__). Namespaces should be
  40. given as dictionaries.
  41. Completer instances should be used as the completion mechanism of
  42. readline via the set_completer() call:
  43. readline.set_completer(Completer(my_namespace).complete)
  44. """
  45. if namespace and not isinstance(namespace, dict):
  46. raise TypeError,'namespace must be a dictionary'
  47. # Don't bind to namespace quite yet, but flag whether the user wants a
  48. # specific namespace or to use __main__.__dict__. This will allow us
  49. # to bind to __main__.__dict__ at completion time, not now.
  50. if namespace is None:
  51. self.use_main_ns = 1
  52. else:
  53. self.use_main_ns = 0
  54. self.namespace = namespace
  55. def complete(self, text, state):
  56. """Return the next possible completion for 'text'.
  57. This is called successively with state == 0, 1, 2, ... until it
  58. returns None. The completion should begin with 'text'.
  59. """
  60. if self.use_main_ns:
  61. self.namespace = __main__.__dict__
  62. if state == 0:
  63. if "." in text:
  64. self.matches = self.attr_matches(text)
  65. else:
  66. self.matches = self.global_matches(text)
  67. try:
  68. return self.matches[state]
  69. except IndexError:
  70. return None
  71. def _callable_postfix(self, val, word):
  72. if hasattr(val, '__call__'):
  73. word = word + "("
  74. return word
  75. def global_matches(self, text):
  76. """Compute matches when text is a simple name.
  77. Return a list of all keywords, built-in functions and names currently
  78. defined in self.namespace that match.
  79. """
  80. import keyword
  81. matches = []
  82. n = len(text)
  83. for word in keyword.kwlist:
  84. if word[:n] == text:
  85. matches.append(word)
  86. for nspace in [__builtin__.__dict__, self.namespace]:
  87. for word, val in nspace.items():
  88. if word[:n] == text and word != "__builtins__":
  89. matches.append(self._callable_postfix(val, word))
  90. return matches
  91. def attr_matches(self, text):
  92. """Compute matches when text contains a dot.
  93. Assuming the text is of the form NAME.NAME....[NAME], and is
  94. evaluatable in self.namespace, it will be evaluated and its attributes
  95. (as revealed by dir()) are used as possible completions. (For class
  96. instances, class members are also considered.)
  97. WARNING: this can still invoke arbitrary C code, if an object
  98. with a __getattr__ hook is evaluated.
  99. """
  100. import re
  101. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  102. if not m:
  103. return []
  104. expr, attr = m.group(1, 3)
  105. try:
  106. thisobject = eval(expr, self.namespace)
  107. except Exception:
  108. return []
  109. # get the content of the object, except __builtins__
  110. words = dir(thisobject)
  111. if "__builtins__" in words:
  112. words.remove("__builtins__")
  113. if hasattr(thisobject, '__class__'):
  114. words.append('__class__')
  115. words.extend(get_class_members(thisobject.__class__))
  116. matches = []
  117. n = len(attr)
  118. for word in words:
  119. if word[:n] == attr and hasattr(thisobject, word):
  120. val = getattr(thisobject, word)
  121. word = self._callable_postfix(val, "%s.%s" % (expr, word))
  122. matches.append(word)
  123. return matches
  124. def get_class_members(klass):
  125. ret = dir(klass)
  126. if hasattr(klass,'__bases__'):
  127. for base in klass.__bases__:
  128. ret = ret + get_class_members(base)
  129. return ret
  130. try:
  131. import readline
  132. except ImportError:
  133. pass
  134. else:
  135. readline.set_completer(Completer().complete)