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