|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 """ |
|
4 Word completion for the eric6 shell. |
|
5 |
|
6 <h4>NOTE for eric6 variant</h4> |
|
7 |
|
8 This version is a re-implementation of rlcompleter |
|
9 as found in the Python3 library. It is modified to work with the eric6 |
|
10 debug clients. |
|
11 |
|
12 <h4>Original rlcompleter documentation</h4> |
|
13 |
|
14 This requires the latest extension to the readline module. The completer |
|
15 completes keywords, built-ins and globals in a selectable namespace (which |
|
16 defaults to __main__); when completing NAME.NAME..., it evaluates (!) the |
|
17 expression up to the last dot and completes its attributes. |
|
18 |
|
19 It's very cool to do "import sys" type "sys.", hit the |
|
20 completion key (twice), and see the list of names defined by the |
|
21 sys module! |
|
22 |
|
23 Tip: to use the tab key as the completion key, call |
|
24 |
|
25 readline.parse_and_bind("tab: complete") |
|
26 |
|
27 <b>Notes</b>: |
|
28 <ul> |
|
29 <li> |
|
30 Exceptions raised by the completer function are *ignored* (and |
|
31 generally cause the completion to fail). This is a feature -- since |
|
32 readline sets the tty device in raw (or cbreak) mode, printing a |
|
33 traceback wouldn't work well without some complicated hoopla to save, |
|
34 reset and restore the tty state. |
|
35 </li> |
|
36 <li> |
|
37 The evaluation of the NAME.NAME... form may cause arbitrary |
|
38 application defined code to be executed if an object with a |
|
39 __getattr__ hook is found. Since it is the responsibility of the |
|
40 application (or the user) to enable this feature, I consider this an |
|
41 acceptable risk. More complicated expressions (e.g. function calls or |
|
42 indexing operations) are *not* evaluated. |
|
43 </li> |
|
44 <li> |
|
45 When the original stdin is not a tty device, GNU readline is never |
|
46 used, and this module (and the readline module) are silently inactive. |
|
47 </li> |
|
48 </ul> |
|
49 """ |
|
50 |
|
51 import builtins |
|
52 import __main__ |
|
53 |
|
54 __all__ = ["Completer"] |
|
55 |
|
56 |
|
57 class Completer(object): |
|
58 """ |
|
59 Class implementing the command line completer object. |
|
60 """ |
|
61 def __init__(self, namespace=None): |
|
62 """ |
|
63 Constructor |
|
64 |
|
65 Completer([namespace]) -> completer instance. |
|
66 |
|
67 If unspecified, the default namespace where completions are performed |
|
68 is __main__ (technically, __main__.__dict__). Namespaces should be |
|
69 given as dictionaries. |
|
70 |
|
71 Completer instances should be used as the completion mechanism of |
|
72 readline via the set_completer() call: |
|
73 |
|
74 readline.set_completer(Completer(my_namespace).complete) |
|
75 |
|
76 @param namespace The namespace for the completer. |
|
77 @exception TypeError raised to indicate a wrong data structure of |
|
78 the namespace object |
|
79 """ |
|
80 if namespace and not isinstance(namespace, dict): |
|
81 raise TypeError('namespace must be a dictionary') |
|
82 |
|
83 # Don't bind to namespace quite yet, but flag whether the user wants a |
|
84 # specific namespace or to use __main__.__dict__. This will allow us |
|
85 # to bind to __main__.__dict__ at completion time, not now. |
|
86 if namespace is None: |
|
87 self.use_main_ns = True |
|
88 else: |
|
89 self.use_main_ns = False |
|
90 self.namespace = namespace |
|
91 |
|
92 def complete(self, text, state): |
|
93 """ |
|
94 Public method to return the next possible completion for 'text'. |
|
95 |
|
96 This is called successively with state == 0, 1, 2, ... until it |
|
97 returns None. The completion should begin with 'text'. |
|
98 |
|
99 @param text The text to be completed. (string) |
|
100 @param state The state of the completion. (integer) |
|
101 @return The possible completions as a list of strings. |
|
102 """ |
|
103 if self.use_main_ns: |
|
104 self.namespace = __main__.__dict__ |
|
105 |
|
106 if state == 0: |
|
107 if "." in text: |
|
108 self.matches = self.attr_matches(text) |
|
109 else: |
|
110 self.matches = self.global_matches(text) |
|
111 try: |
|
112 return self.matches[state] |
|
113 except IndexError: |
|
114 return None |
|
115 |
|
116 def _callable_postfix(self, val, word): |
|
117 """ |
|
118 Protected method to check for a callable. |
|
119 |
|
120 @param val value to check (object) |
|
121 @param word word to ammend (string) |
|
122 @return ammended word (string) |
|
123 """ |
|
124 if hasattr(val, '__call__'): |
|
125 word = word + "(" |
|
126 return word |
|
127 |
|
128 def global_matches(self, text): |
|
129 """ |
|
130 Public method to compute matches when text is a simple name. |
|
131 |
|
132 @param text The text to be completed. (string) |
|
133 @return A list of all keywords, built-in functions and names currently |
|
134 defined in self.namespace that match. |
|
135 """ |
|
136 import keyword |
|
137 matches = [] |
|
138 n = len(text) |
|
139 for word in keyword.kwlist: |
|
140 if word[:n] == text: |
|
141 matches.append(word) |
|
142 for nspace in [builtins.__dict__, self.namespace]: |
|
143 for word, val in nspace.items(): |
|
144 if word[:n] == text and word != "__builtins__": |
|
145 matches.append(self._callable_postfix(val, word)) |
|
146 return matches |
|
147 |
|
148 def attr_matches(self, text): |
|
149 """ |
|
150 Public method to compute matches when text contains a dot. |
|
151 |
|
152 Assuming the text is of the form NAME.NAME....[NAME], and is |
|
153 evaluatable in self.namespace, it will be evaluated and its attributes |
|
154 (as revealed by dir()) are used as possible completions. (For class |
|
155 instances, class members are are also considered.) |
|
156 |
|
157 <b>WARNING</b>: this can still invoke arbitrary C code, if an object |
|
158 with a __getattr__ hook is evaluated. |
|
159 |
|
160 @param text The text to be completed. (string) |
|
161 @return A list of all matches. |
|
162 """ |
|
163 import re |
|
164 |
|
165 # Another option, seems to work great. Catches things like ''.<tab> |
|
166 m = re.match(r"(\S+(\.\w+)*)\.(\w*)", text) |
|
167 |
|
168 if not m: |
|
169 return |
|
170 expr, attr = m.group(1, 3) |
|
171 try: |
|
172 thisobject = eval(expr, self.namespace) |
|
173 except Exception: |
|
174 return [] |
|
175 |
|
176 # get the content of the object, except __builtins__ |
|
177 words = dir(thisobject) |
|
178 if "__builtins__" in words: |
|
179 words.remove("__builtins__") |
|
180 |
|
181 if hasattr(object, '__class__'): |
|
182 words.append('__class__') |
|
183 words = words + get_class_members(object.__class__) |
|
184 matches = [] |
|
185 n = len(attr) |
|
186 for word in words: |
|
187 try: |
|
188 if word[:n] == attr and hasattr(thisobject, word): |
|
189 val = getattr(thisobject, word) |
|
190 word = self._callable_postfix( |
|
191 val, "{0}.{1}".format(expr, word)) |
|
192 matches.append(word) |
|
193 except Exception: |
|
194 # some badly behaved objects pollute dir() with non-strings, |
|
195 # which cause the completion to fail. This way we skip the |
|
196 # bad entries and can still continue processing the others. |
|
197 pass |
|
198 return matches |
|
199 |
|
200 |
|
201 def get_class_members(klass): |
|
202 """ |
|
203 Module function to retrieve the class members. |
|
204 |
|
205 @param klass The class object to be analysed. |
|
206 @return A list of all names defined in the class. |
|
207 """ |
|
208 ret = dir(klass) |
|
209 if hasattr(klass, '__bases__'): |
|
210 for base in klass.__bases__: |
|
211 ret = ret + get_class_members(base) |
|
212 return ret |
|
213 |
|
214 # |
|
215 # eflag: noqa = M702, M111 |