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