-
-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathautocomplete.py
More file actions
407 lines (362 loc) · 15.2 KB
/
autocomplete.py
File metadata and controls
407 lines (362 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# The MIT License
#
# Copyright (c) 2009-2012 the bpython authors.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from __future__ import with_statement
import __builtin__
import __main__
import rlcompleter
import line as lineparts
import re
import os
from glob import glob
from bpython import inspection
from bpython import importcompletion
from bpython._py3compat import py3
# Needed for special handling of __abstractmethods__
# abc only exists since 2.6, so check both that it exists and that it's
# the one we're expecting
try:
import abc
abc.ABCMeta
has_abc = True
except (ImportError, AttributeError):
has_abc = False
# Autocomplete modes
SIMPLE = 'simple'
SUBSTRING = 'substring'
FUZZY = 'fuzzy'
MAGIC_METHODS = ["__%s__" % s for s in [
"init", "repr", "str", "lt", "le", "eq", "ne", "gt", "ge", "cmp", "hash",
"nonzero", "unicode", "getattr", "setattr", "get", "set","call", "len",
"getitem", "setitem", "iter", "reversed", "contains", "add", "sub", "mul",
"floordiv", "mod", "divmod", "pow", "lshift", "rshift", "and", "xor", "or",
"div", "truediv", "neg", "pos", "abs", "invert", "complex", "int", "float",
"oct", "hex", "index", "coerce", "enter", "exit"]]
def get_completer(cursor_offset, current_line, locals_, argspec, full_code, mode, complete_magic_methods):
"""Returns a list of matches and a class for what kind of completion is happening
If no completion type is relevant, returns None, None
argspec is an output of inspect.getargspec
"""
kwargs = {'locals_':locals_, 'argspec':argspec, 'full_code':full_code,
'mode':mode, 'complete_magic_methods':complete_magic_methods}
# mutually exclusive if matches: If one of these returns [], try the next one
for completer in [DictKeyCompletion]:
matches = completer.matches(cursor_offset, current_line, **kwargs)
if matches:
return sorted(set(matches)), completer
# mutually exclusive matchers: if one returns [], don't go on
for completer in [StringLiteralAttrCompletion, ImportCompletion,
FilenameCompletion, MagicMethodCompletion, GlobalCompletion]:
matches = completer.matches(cursor_offset, current_line, **kwargs)
if matches is not None:
return sorted(set(matches)), completer
matches = AttrCompletion.matches(cursor_offset, current_line, **kwargs)
# cumulative completions - try them all
# They all use current_word replacement and formatting
current_word_matches = []
for completer in [AttrCompletion, ParameterNameCompletion]:
matches = completer.matches(cursor_offset, current_line, **kwargs)
if matches is not None:
current_word_matches.extend(matches)
if len(current_word_matches) == 0:
return None, None
return sorted(set(current_word_matches)), AttrCompletion
class BaseCompletionType(object):
"""Describes different completion types"""
def matches(cls, cursor_offset, line, **kwargs):
"""Returns a list of possible matches given a line and cursor, or None
if this completion type isn't applicable.
ie, import completion doesn't make sense if there cursor isn't after
an import or from statement
Completion types are used to:
* `locate(cur, line)` their target word to replace given a line and cursor
* find `matches(cur, line)` that might replace that word
* `format(match)` matches to be displayed to the user
* determine whether suggestions should be `shown_before_tab`
* `substitute(cur, line, match)` in a match for what's found with `target`
"""
raise NotImplementedError
def locate(cls, cursor_offset, line):
"""Returns a start, stop, and word given a line and cursor, or None
if no target for this type of completion is found under the cursor"""
raise NotImplementedError
@classmethod
def format(cls, word):
return word
shown_before_tab = True # whether suggestions should be shown before the
# user hits tab, or only once that has happened
def substitute(cls, cursor_offset, line, match):
"""Returns a cursor offset and line with match swapped in"""
start, end, word = cls.locate(cursor_offset, line)
result = start + len(match), line[:start] + match + line[end:]
return result
class ImportCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, current_line, **kwargs):
return importcompletion.complete(cursor_offset, current_line)
locate = staticmethod(lineparts.current_word)
@classmethod
def format(cls, name):
return name.rstrip('.').rsplit('.')[-1]
class FilenameCompletion(BaseCompletionType):
shown_before_tab = False
@classmethod
def matches(cls, cursor_offset, current_line, **kwargs):
cs = lineparts.current_string(cursor_offset, current_line)
if cs is None:
return None
start, end, text = cs
matches = []
username = text.split(os.path.sep, 1)[0]
user_dir = os.path.expanduser(username)
for filename in glob(os.path.expanduser(text + '*')):
if os.path.isdir(filename):
filename += os.path.sep
if text.startswith('~'):
filename = username + filename[len(user_dir):]
matches.append(filename)
return matches
locate = staticmethod(lineparts.current_string)
@classmethod
def format(cls, filename):
filename.rstrip(os.sep).rsplit(os.sep)[-1]
if os.sep in filename[:-1]:
return filename[filename.rindex(os.sep, 0, -1)+1:]
else:
return filename
class AttrCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, line, locals_, mode, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
text = r[2]
if locals_ is None:
locals_ = __main__.__dict__
assert '.' in text
for i in range(1, len(text) + 1):
if text[-i] == '[':
i -= 1
break
methodtext = text[-i:]
matches = [''.join([text[:-i], m]) for m in
attr_matches(methodtext, locals_, mode)]
#TODO add open paren for methods via _callable_prefix (or decide not to)
# unless the first character is a _ filter out all attributes starting with a _
if not text.split('.')[-1].startswith('_'):
matches = [match for match in matches
if not match.split('.')[-1].startswith('_')]
return matches
locate = staticmethod(lineparts.current_dotted_attribute)
@classmethod
def format(cls, name):
return name.rstrip('.').rsplit('.')[-1]
class DictKeyCompletion(BaseCompletionType):
locate = staticmethod(lineparts.current_dict_key)
@classmethod
def matches(cls, cursor_offset, line, locals_, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, orig = r
_, _, dexpr = lineparts.current_dict(cursor_offset, line)
obj = safe_eval(dexpr, locals_)
if obj is SafeEvalFailed:
return []
if obj and isinstance(obj, type({})) and obj.keys():
return ["{!r}]".format(k) for k in obj.keys() if repr(k).startswith(orig)]
else:
return []
@classmethod
def format(cls, match):
return match[:-1]
class MagicMethodCompletion(BaseCompletionType):
locate = staticmethod(lineparts.current_method_definition_name)
@classmethod
def matches(cls, cursor_offset, line, full_code, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
if 'class' not in full_code:
return None
start, end, word = r
return [name for name in MAGIC_METHODS if name.startswith(word)]
class GlobalCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, line, locals_, mode, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, word = r
return global_matches(word, locals_, mode)
locate = staticmethod(lineparts.current_single_word)
class ParameterNameCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, line, argspec, **kwargs):
if not argspec:
return None
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, word = r
if argspec:
matches = [name + '=' for name in argspec[1][0]
if isinstance(name, basestring) and name.startswith(word)]
if py3:
matches.extend(name + '=' for name in argspec[1][4]
if name.startswith(word))
return matches
locate = staticmethod(lineparts.current_word)
class MagicMethodCompletion(BaseCompletionType):
locate = staticmethod(lineparts.current_method_definition_name)
@classmethod
def matches(cls, cursor_offset, line, full_code, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
if 'class' not in full_code:
return None
start, end, word = r
return [name for name in MAGIC_METHODS if name.startswith(word)]
class GlobalCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, line, locals_, mode, **kwargs):
"""Compute matches when text is a simple name.
Return a list of all keywords, built-in functions and names currently
defined in self.namespace that match.
"""
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, text = r
hash = {}
n = len(text)
import keyword
for word in keyword.kwlist:
if method_match(word, n, text, mode):
hash[word] = 1
for nspace in [__builtin__.__dict__, locals_]:
for word, val in nspace.items():
if method_match(word, len(text), text, mode) and word != "__builtins__":
hash[_callable_postfix(val, word)] = 1
matches = hash.keys()
matches.sort()
return matches
locate = staticmethod(lineparts.current_single_word)
class ParameterNameCompletion(BaseCompletionType):
@classmethod
def matches(cls, cursor_offset, line, argspec, **kwargs):
if not argspec:
return None
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, word = r
if argspec:
matches = [name + '=' for name in argspec[1][0]
if isinstance(name, basestring) and name.startswith(word)]
if py3:
matches.extend(name + '=' for name in argspec[1][4]
if name.startswith(word))
return matches
locate = staticmethod(lineparts.current_word)
class StringLiteralAttrCompletion(BaseCompletionType):
locate = staticmethod(lineparts.current_string_literal_attr)
@classmethod
def matches(cls, cursor_offset, line, **kwargs):
r = cls.locate(cursor_offset, line)
if r is None:
return None
start, end, word = r
attrs = dir('')
matches = [att for att in attrs if att.startswith(word)]
if not word.startswith('_'):
return [match for match in matches if not match.startswith('_')]
return matches
class SafeEvalFailed(Exception):
"""If this object is returned, safe_eval failed"""
# Because every normal Python value is a possible return value of safe_eval
def safe_eval(expr, namespace):
"""Not all that safe, just catches some errors"""
if expr.isdigit():
# Special case: float literal, using attrs here will result in
# a SyntaxError
return SafeEvalFailed
try:
obj = eval(expr, namespace)
return obj
except (NameError, AttributeError) as e:
# If debugging safe_eval, raise this!
# raise e
return SafeEvalFailed
def attr_matches(text, namespace, autocomplete_mode):
"""Taken from rlcompleter.py and bent to my will.
"""
# Gna, Py 2.6's rlcompleter searches for __call__ inside the
# instance instead of the type, so we monkeypatch to prevent
# side-effects (__getattr__/__getattribute__)
m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
if not m:
return []
expr, attr = m.group(1, 3)
obj = safe_eval(expr, namespace)
if obj is SafeEvalFailed:
return []
with inspection.AttrCleaner(obj):
matches = attr_lookup(obj, expr, attr, autocomplete_mode)
return matches
def attr_lookup(obj, expr, attr, autocomplete_mode):
"""Second half of original attr_matches method factored out so it can
be wrapped in a safe try/finally block in case anything bad happens to
restore the original __getattribute__ method."""
words = dir(obj)
if hasattr(obj, '__class__'):
words.append('__class__')
words = words + rlcompleter.get_class_members(obj.__class__)
if has_abc and not isinstance(obj.__class__, abc.ABCMeta):
try:
words.remove('__abstractmethods__')
except ValueError:
pass
matches = []
n = len(attr)
for word in words:
if method_match(word, n, attr, autocomplete_mode) and word != "__builtins__":
matches.append("%s.%s" % (expr, word))
return matches
def _callable_postfix(value, word):
"""rlcompleter's _callable_postfix done right."""
with inspection.AttrCleaner(value):
if inspection.is_callable(value):
word += '('
return word
#TODO use method_match everywhere instead of startswith to implement other completion modes
# will also need to rewrite checking mode so cseq replace doesn't happen in frontends
def method_match(word, size, text, autocomplete_mode):
if autocomplete_mode == SIMPLE:
return word[:size] == text
elif autocomplete_mode == SUBSTRING:
s = r'.*%s.*' % text
return re.search(s, word)
else:
s = r'.*%s.*' % '.*'.join(list(text))
return re.search(s, word)