src/eric7/DebugClients/Python/FlexCompleter.py

branch
eric7
changeset 9209
b99e7fd55fd3
parent 8312
800c432b34c8
child 9221
bf71ee032bb4
equal deleted inserted replaced
9208:3fc8dfeb6ebe 9209:b99e7fd55fd3
1 # -*- coding: utf-8 -*-
2
3 """
4 Word completion for the eric shell.
5
6 <h4>NOTE for eric 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 eric
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:
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 callable(val):
125 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 seen = {"__builtins__"}
139 n = len(text)
140 for word in keyword.kwlist:
141 if word[:n] == text:
142 seen.add(word)
143 if word in {'finally', 'try'}:
144 word += ':'
145 elif word not in {'False', 'None', 'True',
146 'break', 'continue', 'pass',
147 'else'}:
148 word += ' '
149 matches.append(word)
150 for nspace in [self.namespace, builtins.__dict__]:
151 for word, val in nspace.items():
152 if word[:n] == text and word not in seen:
153 seen.add(word)
154 matches.append(self._callable_postfix(val, word))
155 return matches
156
157 def attr_matches(self, text):
158 """
159 Public method to compute matches when text contains a dot.
160
161 Assuming the text is of the form NAME.NAME....[NAME], and is
162 evaluatable in self.namespace, it will be evaluated and its attributes
163 (as revealed by dir()) are used as possible completions. (For class
164 instances, class members are are also considered.)
165
166 <b>WARNING</b>: this can still invoke arbitrary C code, if an object
167 with a __getattr__ hook is evaluated.
168
169 @param text The text to be completed. (string)
170 @return A list of all matches.
171 """
172 import re
173
174 m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
175 if not m:
176 return []
177 expr, attr = m.group(1, 3)
178 try:
179 thisobject = eval(expr, self.namespace) # secok
180 except Exception:
181 return []
182
183 # get the content of the object, except __builtins__
184 words = set(dir(thisobject))
185 words.discard("__builtins__")
186
187 if hasattr(object, '__class__'):
188 words.add('__class__')
189 words.update(get_class_members(thisobject.__class__))
190 matches = []
191 n = len(attr)
192 if attr == '':
193 noprefix = '_'
194 elif attr == '_':
195 noprefix = '__'
196 else:
197 noprefix = None
198 while True:
199 for word in words:
200 if (word[:n] == attr and
201 not (noprefix and word[:n + 1] == noprefix)):
202 match = "{0}.{1}".format(expr, word)
203 try:
204 val = getattr(thisobject, word)
205 except Exception: # secok
206 pass # Include even if attribute not set
207 else:
208 match = self._callable_postfix(val, match)
209 matches.append(match)
210 if matches or not noprefix:
211 break
212 noprefix = '__' if noprefix == '_' else None
213 matches.sort()
214 return matches
215
216
217 def get_class_members(klass):
218 """
219 Module function to retrieve the class members.
220
221 @param klass The class object to be analysed.
222 @return A list of all names defined in the class.
223 """
224 ret = dir(klass)
225 if hasattr(klass, '__bases__'):
226 for base in klass.__bases__:
227 ret += get_class_members(base)
228 return ret
229
230 #
231 # eflag: noqa = M111

eric ide

mercurial