PyXR

c:\python24\lib \ rlcompleter.py



0001 """Word completion for GNU readline 2.0.
0002 
0003 This requires the latest extension to the readline module. The completer
0004 completes keywords, built-ins and globals in a selectable namespace (which
0005 defaults to __main__); when completing NAME.NAME..., it evaluates (!) the
0006 expression up to the last dot and completes its attributes.
0007 
0008 It's very cool to do "import sys" type "sys.", hit the
0009 completion key (twice), and see the list of names defined by the
0010 sys module!
0011 
0012 Tip: to use the tab key as the completion key, call
0013 
0014     readline.parse_and_bind("tab: complete")
0015 
0016 Notes:
0017 
0018 - Exceptions raised by the completer function are *ignored* (and
0019 generally cause the completion to fail).  This is a feature -- since
0020 readline sets the tty device in raw (or cbreak) mode, printing a
0021 traceback wouldn't work well without some complicated hoopla to save,
0022 reset and restore the tty state.
0023 
0024 - The evaluation of the NAME.NAME... form may cause arbitrary
0025 application defined code to be executed if an object with a
0026 __getattr__ hook is found.  Since it is the responsibility of the
0027 application (or the user) to enable this feature, I consider this an
0028 acceptable risk.  More complicated expressions (e.g. function calls or
0029 indexing operations) are *not* evaluated.
0030 
0031 - GNU readline is also used by the built-in functions input() and
0032 raw_input(), and thus these also benefit/suffer from the completer
0033 features.  Clearly an interactive application can benefit by
0034 specifying its own completer function and using raw_input() for all
0035 its input.
0036 
0037 - When the original stdin is not a tty device, GNU readline is never
0038 used, and this module (and the readline module) are silently inactive.
0039 
0040 """
0041 
0042 import readline
0043 import __builtin__
0044 import __main__
0045 
0046 __all__ = ["Completer"]
0047 
0048 class Completer:
0049     def __init__(self, namespace = None):
0050         """Create a new completer for the command line.
0051 
0052         Completer([namespace]) -> completer instance.
0053 
0054         If unspecified, the default namespace where completions are performed
0055         is __main__ (technically, __main__.__dict__). Namespaces should be
0056         given as dictionaries.
0057 
0058         Completer instances should be used as the completion mechanism of
0059         readline via the set_completer() call:
0060 
0061         readline.set_completer(Completer(my_namespace).complete)
0062         """
0063 
0064         if namespace and not isinstance(namespace, dict):
0065             raise TypeError,'namespace must be a dictionary'
0066 
0067         # Don't bind to namespace quite yet, but flag whether the user wants a
0068         # specific namespace or to use __main__.__dict__. This will allow us
0069         # to bind to __main__.__dict__ at completion time, not now.
0070         if namespace is None:
0071             self.use_main_ns = 1
0072         else:
0073             self.use_main_ns = 0
0074             self.namespace = namespace
0075 
0076     def complete(self, text, state):
0077         """Return the next possible completion for 'text'.
0078 
0079         This is called successively with state == 0, 1, 2, ... until it
0080         returns None.  The completion should begin with 'text'.
0081 
0082         """
0083         if self.use_main_ns:
0084             self.namespace = __main__.__dict__
0085 
0086         if state == 0:
0087             if "." in text:
0088                 self.matches = self.attr_matches(text)
0089             else:
0090                 self.matches = self.global_matches(text)
0091         try:
0092             return self.matches[state]
0093         except IndexError:
0094             return None
0095 
0096     def global_matches(self, text):
0097         """Compute matches when text is a simple name.
0098 
0099         Return a list of all keywords, built-in functions and names currently
0100         defined in self.namespace that match.
0101 
0102         """
0103         import keyword
0104         matches = []
0105         n = len(text)
0106         for list in [keyword.kwlist,
0107                      __builtin__.__dict__,
0108                      self.namespace]:
0109             for word in list:
0110                 if word[:n] == text and word != "__builtins__":
0111                     matches.append(word)
0112         return matches
0113 
0114     def attr_matches(self, text):
0115         """Compute matches when text contains a dot.
0116 
0117         Assuming the text is of the form NAME.NAME....[NAME], and is
0118         evaluatable in self.namespace, it will be evaluated and its attributes
0119         (as revealed by dir()) are used as possible completions.  (For class
0120         instances, class members are also considered.)
0121 
0122         WARNING: this can still invoke arbitrary C code, if an object
0123         with a __getattr__ hook is evaluated.
0124 
0125         """
0126         import re
0127         m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
0128         if not m:
0129             return
0130         expr, attr = m.group(1, 3)
0131         object = eval(expr, self.namespace)
0132         words = dir(object)
0133         if hasattr(object,'__class__'):
0134             words.append('__class__')
0135             words = words + get_class_members(object.__class__)
0136         matches = []
0137         n = len(attr)
0138         for word in words:
0139             if word[:n] == attr and word != "__builtins__":
0140                 matches.append("%s.%s" % (expr, word))
0141         return matches
0142 
0143 def get_class_members(klass):
0144     ret = dir(klass)
0145     if hasattr(klass,'__bases__'):
0146         for base in klass.__bases__:
0147             ret = ret + get_class_members(base)
0148     return ret
0149 
0150 readline.set_completer(Completer().complete)
0151 

Generated by PyXR 0.9.4
SourceForge.net Logo