rlcompleter.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 readline
  32. import __builtin__
  33. import __main__
  34. __all__ = ["Completer"]
  35. class Completer:
  36. def __init__(self, namespace = None):
  37. """Create a new completer for the command line.
  38. Completer([namespace]) -> completer instance.
  39. If unspecified, the default namespace where completions are performed
  40. is __main__ (technically, __main__.__dict__). Namespaces should be
  41. given as dictionaries.
  42. Completer instances should be used as the completion mechanism of
  43. readline via the set_completer() call:
  44. readline.set_completer(Completer(my_namespace).complete)
  45. """
  46. if namespace and not isinstance(namespace, dict):
  47. raise TypeError,'namespace must be a dictionary'
  48. # Don't bind to namespace quite yet, but flag whether the user wants a
  49. # specific namespace or to use __main__.__dict__. This will allow us
  50. # to bind to __main__.__dict__ at completion time, not now.
  51. if namespace is None:
  52. self.use_main_ns = 1
  53. else:
  54. self.use_main_ns = 0
  55. self.namespace = namespace
  56. def complete(self, text, state):
  57. """Return the next possible completion for 'text'.
  58. This is called successively with state == 0, 1, 2, ... until it
  59. returns None. The completion should begin with 'text'.
  60. """
  61. if self.use_main_ns:
  62. self.namespace = __main__.__dict__
  63. if state == 0:
  64. if "." in text:
  65. self.matches = self.attr_matches(text)
  66. else:
  67. self.matches = self.global_matches(text)
  68. try:
  69. return self.matches[state]
  70. except IndexError:
  71. return None
  72. def global_matches(self, text):
  73. """Compute matches when text is a simple name.
  74. Return a list of all keywords, built-in functions and names currently
  75. defined in self.namespace that match.
  76. """
  77. import keyword
  78. matches = []
  79. n = len(text)
  80. for list in [keyword.kwlist,
  81. __builtin__.__dict__,
  82. self.namespace]:
  83. for word in list:
  84. if word[:n] == text and word != "__builtins__":
  85. matches.append(word)
  86. return matches
  87. def attr_matches(self, text):
  88. """Compute matches when text contains a dot.
  89. Assuming the text is of the form NAME.NAME....[NAME], and is
  90. evaluatable in self.namespace, it will be evaluated and its attributes
  91. (as revealed by dir()) are used as possible completions. (For class
  92. instances, class members are also considered.)
  93. WARNING: this can still invoke arbitrary C code, if an object
  94. with a __getattr__ hook is evaluated.
  95. """
  96. import re
  97. m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
  98. if not m:
  99. return
  100. expr, attr = m.group(1, 3)
  101. object = eval(expr, self.namespace)
  102. words = dir(object)
  103. if hasattr(object,'__class__'):
  104. words.append('__class__')
  105. words = words + get_class_members(object.__class__)
  106. matches = []
  107. n = len(attr)
  108. for word in words:
  109. if word[:n] == attr and word != "__builtins__":
  110. matches.append("%s.%s" % (expr, word))
  111. return matches
  112. def get_class_members(klass):
  113. ret = dir(klass)
  114. if hasattr(klass,'__bases__'):
  115. for base in klass.__bases__:
  116. ret = ret + get_class_members(base)
  117. return ret
  118. readline.set_completer(Completer().complete)