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