Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork252
Expand file tree
/
Copy pathautocomplete.py
More file actions
810 lines (688 loc) · 23.9 KB
/
autocomplete.py
File metadata and controls
810 lines (688 loc) · 23.9 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
# The MIT License
#
# Copyright (c) 2009-2015 the bpython authors.
# Copyright (c) 2015-2020 Sebastian Ramacher
#
# 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.
# To gradually migrate to mypy we aren't setting these globally yet
# mypy: disallow_untyped_defs=True
# mypy: disallow_untyped_calls=True
import__main__
importabc
importglob
importitertools
importkeyword
importlogging
importos
importre
importrlcompleter
importbuiltins
fromenumimportEnum
fromtypingimport (
Any,
Optional,
)
fromcollections.abcimportIterator,Sequence
from .importinspection
from .importlineaslineparts
from .lineimportLinePart
from .lazyreimportLazyReCompile
from .simpleevalimportsafe_eval,evaluate_current_expression,EvaluationError
from .importcompletionimportModuleGatherer
logger=logging.getLogger(__name__)
# Autocomplete modes
classAutocompleteModes(Enum):
NONE="none"
SIMPLE="simple"
SUBSTRING="substring"
FUZZY="fuzzy"
@classmethod
deffrom_string(cls,value:str)->Optional["AutocompleteModes"]:
ifvalue.upper()incls.__members__:
returncls.__members__[value.upper()]
returnNone
MAGIC_METHODS=tuple(
f"__{s}__"
forsin (
"new",
"init",
"del",
"repr",
"str",
"bytes",
"format",
"lt",
"le",
"eq",
"ne",
"gt",
"ge",
"hash",
"bool",
"getattr",
"getattribute",
"setattr",
"delattr",
"dir",
"get",
"set",
"delete",
"set_name",
"init_subclass",
"instancecheck",
"subclasscheck",
"class_getitem",
"call",
"len",
"length_hint",
"getitem",
"setitem",
"delitem",
"missing",
"iter",
"reversed",
"contains",
"add",
"sub",
"mul",
"matmul",
"truediv",
"floordiv",
"mod",
"divmod",
"pow",
"lshift",
"rshift",
"and",
"xor",
"or",
"radd",
"rsub",
"rmul",
"rmatmul",
"rtruediv",
"rfloordiv",
"rmod",
"rdivmod",
"rpow",
"rlshift",
"rrshift",
"rand",
"rxor",
"ror",
"iadd",
"isub",
"imul",
"imatmul",
"itruediv",
"ifloordiv",
"imod",
"ipow",
"ilshift",
"irshift",
"iand",
"ixor",
"ixor",
"neg",
"pos",
"abs",
"invert",
"complex",
"int",
"float",
"index",
"round",
"trunc",
"floor",
"ceil",
"enter",
"exit",
"await",
"aiter",
"anext",
"aenter",
"aexit",
)
)
KEYWORDS=frozenset(keyword.kwlist)
def_after_last_dot(name:str)->str:
returnname.rstrip(".").rsplit(".")[-1]
def_few_enough_underscores(current:str,match:str)->bool:
"""Returns whether match should be shown based on current
if current is _, True if match starts with 0 or 1 underscore
if current is __, True regardless of match
otherwise True if match does not start with any underscore
"""
ifcurrent.startswith("__"):
returnTrue
elifcurrent.startswith("_")andnotmatch.startswith("__"):
returnTrue
returnnotmatch.startswith("_")
def_method_match_none(word:str,size:int,text:str)->bool:
returnFalse
def_method_match_simple(word:str,size:int,text:str)->bool:
returnword[:size]==text
def_method_match_substring(word:str,size:int,text:str)->bool:
returntextinword
def_method_match_fuzzy(word:str,size:int,text:str)->bool:
s=r".*{}.*".format(".*".join(cforcintext))
returnre.search(s,word)isnotNone
_MODES_MAP= {
AutocompleteModes.NONE:_method_match_none,
AutocompleteModes.SIMPLE:_method_match_simple,
AutocompleteModes.SUBSTRING:_method_match_substring,
AutocompleteModes.FUZZY:_method_match_fuzzy,
}
classBaseCompletionType:
"""Describes different completion types"""
def__init__(
self,
shown_before_tab:bool=True,
mode:AutocompleteModes=AutocompleteModes.SIMPLE,
)->None:
self._shown_before_tab=shown_before_tab
self.method_match=_MODES_MAP[mode]
@abc.abstractmethod
defmatches(
self,cursor_offset:int,line:str,**kwargs:Any
)->set[str]|None:
"""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, so it ought to return None.
Completion types are used to:
* `locate(cur, line)` their initial 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`
"""
raiseNotImplementedError
@abc.abstractmethod
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
"""Returns a Linepart namedtuple instance or None given cursor and line
A Linepart namedtuple contains a start, stop, and word. None is
returned if no target for this type of completion is found under
the cursor."""
raiseNotImplementedError
defformat(self,word:str)->str:
returnword
defsubstitute(
self,cursor_offset:int,line:str,match:str
)->tuple[int,str]:
"""Returns a cursor offset and line with match swapped in"""
lpart=self.locate(cursor_offset,line)
assertlpart
offset=lpart.start+len(match)
changed_line=line[:lpart.start]+match+line[lpart.stop :]
returnoffset,changed_line
@property
defshown_before_tab(self)->bool:
"""Whether suggestions should be shown before the user hits tab, or only
once that has happened."""
returnself._shown_before_tab
classCumulativeCompleter(BaseCompletionType):
"""Returns combined matches from several completers"""
def__init__(
self,
completers:Sequence[BaseCompletionType],
mode:AutocompleteModes=AutocompleteModes.SIMPLE,
)->None:
ifnotcompleters:
raiseValueError(
"CumulativeCompleter requires at least one completer"
)
self._completers:Sequence[BaseCompletionType]=completers
super().__init__(True,mode)
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
forcompleterinself._completers:
return_value=completer.locate(cursor_offset,line)
ifreturn_valueisnotNone:
returnreturn_value
returnNone
defformat(self,word:str)->str:
returnself._completers[0].format(word)
defmatches(
self,cursor_offset:int,line:str,**kwargs:Any
)->set[str]|None:
return_value=None
all_matches=set()
forcompleterinself._completers:
matches=completer.matches(
cursor_offset=cursor_offset,line=line,**kwargs
)
ifmatchesisnotNone:
all_matches.update(matches)
return_value=all_matches
returnreturn_value
classImportCompletion(BaseCompletionType):
def__init__(
self,
module_gatherer:ModuleGatherer,
mode:AutocompleteModes=AutocompleteModes.SIMPLE,
):
super().__init__(False,mode)
self.module_gatherer=module_gatherer
defmatches(
self,cursor_offset:int,line:str,**kwargs:Any
)->set[str]|None:
returnself.module_gatherer.complete(cursor_offset,line)
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_word(cursor_offset,line)
defformat(self,word:str)->str:
return_after_last_dot(word)
def_safe_glob(pathname:str)->Iterator[str]:
returnglob.iglob(glob.escape(pathname)+"*")
classFilenameCompletion(BaseCompletionType):
def__init__(self,mode:AutocompleteModes=AutocompleteModes.SIMPLE):
super().__init__(False,mode)
defmatches(
self,cursor_offset:int,line:str,**kwargs:Any
)->set[str]|None:
cs=lineparts.current_string(cursor_offset,line)
ifcsisNone:
returnNone
matches=set()
username=cs.word.split(os.path.sep,1)[0]
user_dir=os.path.expanduser(username)
forfilenamein_safe_glob(os.path.expanduser(cs.word)):
ifos.path.isdir(filename):
filename+=os.path.sep
ifcs.word.startswith("~"):
filename=username+filename[len(user_dir) :]
matches.add(filename)
returnmatches
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_string(cursor_offset,line)
defformat(self,filename:str)->str:
ifos.sepinfilename[:-1]:
returnfilename[filename.rindex(os.sep,0,-1)+1 :]
else:
returnfilename
classAttrCompletion(BaseCompletionType):
attr_matches_re=LazyReCompile(r"(\w+(\.\w+)*)\.(\w*)")
defmatches(
self,
cursor_offset:int,
line:str,
*,
locals_:dict[str,Any]|None=None,
**kwargs:Any,
)->set[str]|None:
r=self.locate(cursor_offset,line)
ifrisNone:
returnNone
iflocals_isNone:# TODO add a note about why
locals_=__main__.__dict__
assert"."inr.word
i=r.word.rfind("[")+1
methodtext=r.word[i:]
matches= {
"".join([r.word[:i],m])
forminself.attr_matches(methodtext,locals_)
}
return {
m
forminmatches
if_few_enough_underscores(r.word.split(".")[-1],m.split(".")[-1])
}
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_dotted_attribute(cursor_offset,line)
defformat(self,word:str)->str:
return_after_last_dot(word)
defattr_matches(
self,text:str,namespace:dict[str,Any]
)->Iterator[str]:
"""Taken from rlcompleter.py and bent to my will."""
m=self.attr_matches_re.match(text)
ifnotm:
return (_for_in ())
expr,attr=m.group(1,3)
ifexpr.isdigit():
# Special case: float literal, using attrs here will result in
# a SyntaxError
return (_for_in ())
try:
obj=safe_eval(expr,namespace)
exceptEvaluationError:
return (_for_in ())
returnself.attr_lookup(obj,expr,attr)
defattr_lookup(self,obj:Any,expr:str,attr:str)->Iterator[str]:
"""Second half of attr_matches."""
words=self.list_attributes(obj)
ifinspection.hasattr_safe(obj,"__class__"):
words.append("__class__")
klass=inspection.getattr_safe(obj,"__class__")
words=words+rlcompleter.get_class_members(klass)
ifnotisinstance(klass,abc.ABCMeta):
try:
words.remove("__abstractmethods__")
exceptValueError:
pass
n=len(attr)
return (
f"{expr}.{word}"
forwordinwords
ifself.method_match(word,n,attr)andword!="__builtins__"
)
deflist_attributes(self,obj:Any)->list[str]:
# TODO: re-implement dir without AttrCleaner here
#
# Note: accessing `obj.__dir__` via `getattr_static` is not side-effect free.
withinspection.AttrCleaner(obj):
returndir(obj)
classDictKeyCompletion(BaseCompletionType):
defmatches(
self,
cursor_offset:int,
line:str,
*,
locals_:dict[str,Any]|None=None,
**kwargs:Any,
)->set[str]|None:
iflocals_isNone:
returnNone
r=self.locate(cursor_offset,line)
ifrisNone:
returnNone
current_dict_parts=lineparts.current_dict(cursor_offset,line)
ifcurrent_dict_partsisNone:
returnNone
dexpr=current_dict_parts.word
try:
obj=safe_eval(dexpr,locals_)
exceptEvaluationError:
returnNone
ifisinstance(obj,dict)andobj.keys():
matches= {
f"{k!r}]"forkinobj.keys()ifrepr(k).startswith(r.word)
}
returnmatchesifmatcheselseNone
else:
returnNone
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_dict_key(cursor_offset,line)
defformat(self,match:str)->str:
returnmatch[:-1]
classMagicMethodCompletion(BaseCompletionType):
defmatches(
self,
cursor_offset:int,
line:str,
*,
current_block:str|None=None,
complete_magic_methods:bool|None=None,
**kwargs:Any,
)->set[str]|None:
if (
current_blockisNone
orcomplete_magic_methodsisNone
ornotcomplete_magic_methods
):
returnNone
r=self.locate(cursor_offset,line)
ifrisNone:
returnNone
if"class"notincurrent_block:
returnNone
return {namefornameinMAGIC_METHODSifname.startswith(r.word)}
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_method_definition_name(cursor_offset,line)
classGlobalCompletion(BaseCompletionType):
defmatches(
self,
cursor_offset:int,
line:str,
*,
locals_:dict[str,Any]|None=None,
**kwargs:Any,
)->set[str]|None:
"""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.
"""
iflocals_isNone:
returnNone
r=self.locate(cursor_offset,line)
ifrisNone:
returnNone
n=len(r.word)
matches= {
wordforwordinKEYWORDSifself.method_match(word,n,r.word)
}
fornspacein (builtins.__dict__,locals_):
forword,valinnspace.items():
# if identifier isn't ascii, don't complete (syntax error)
ifwordisNone:
continue
if (
self.method_match(word,n,r.word)
andword!="__builtins__"
):
matches.add(_callable_postfix(val,word))
returnmatchesifmatcheselseNone
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_single_word(cursor_offset,line)
classParameterNameCompletion(BaseCompletionType):
defmatches(
self,
cursor_offset:int,
line:str,
*,
funcprops:inspection.FuncProps|None=None,
**kwargs:Any,
)->set[str]|None:
iffuncpropsisNone:
returnNone
r=self.locate(cursor_offset,line)
ifrisNone:
returnNone
matches= {
f"{name}="
fornameinfuncprops.argspec.args
ifisinstance(name,str)andname.startswith(r.word)
}
matches.update(
f"{name}="
fornameinfuncprops.argspec.kwonly
ifname.startswith(r.word)
)
returnmatchesifmatcheselseNone
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
r=lineparts.current_word(cursor_offset,line)
ifrandr.word[-1]=="(":
# if the word ends with a (, it's the parent word with an empty
# param. Return an empty word
returnlineparts.LinePart(r.stop,r.stop,"")
returnr
classExpressionAttributeCompletion(AttrCompletion):
# could replace attr completion as a more general case with some work
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnlineparts.current_expression_attribute(cursor_offset,line)
defmatches(
self,
cursor_offset:int,
line:str,
*,
locals_:dict[str,Any]|None=None,
**kwargs:Any,
)->set[str]|None:
iflocals_isNone:
locals_=__main__.__dict__
attr=self.locate(cursor_offset,line)
assertattr,"locate was already truthy for the same call"
try:
obj=evaluate_current_expression(cursor_offset,line,locals_)
exceptEvaluationError:
returnset()
# strips leading dot
matches= (m[1:]forminself.attr_lookup(obj,"",attr.word))
return {mforminmatchesif_few_enough_underscores(attr.word,m)}
try:
importjedi
exceptImportError:
classMultilineJediCompletion(BaseCompletionType):# type: ignore [no-redef]
defmatches(
self,cursor_offset:int,line:str,**kwargs:Any
)->set[str]|None:
returnNone
deflocate(self,cursor_offset:int,line:str)->LinePart|None:
returnNone
else:
classMultilineJediCompletion(BaseCompletionType):# type: ignore [no-redef]
_orig_start:int|None
defmatches(
self,
cursor_offset:int,
line:str,
*,
current_block:str|None=None,
history:list[str]|None=None,
**kwargs:Any,
)->set[str]|None:
if (
current_blockisNone
orhistoryisNone
or"\n"notincurrent_block
ornotlineparts.current_word(cursor_offset,line)
):
returnNone
assertcursor_offset<=len(line),"{!r} {!r}".format(
cursor_offset,
line,
)
combined_history="\n".join(itertools.chain(history, (line,)))
try:
script=jedi.Script(combined_history,path="fake.py")
completions=script.complete(
combined_history.count("\n")+1,cursor_offset
)
except (jedi.NotFoundError,IndexError,KeyError):
# IndexError for #483
# KeyError for #544
self._orig_start=None
returnNone
ifcompletions:
diff=len(completions[0].name)-len(completions[0].complete)
self._orig_start=cursor_offset-diff
else:
self._orig_start=None
returnNone
assertisinstance(self._orig_start,int)
matches= [c.nameforcincompletions]
ifany(
notm.lower().startswith(matches[0][0].lower())forminmatches
):
# Too general - giving completions starting with multiple
# letters
returnNone
else:
# case-sensitive matches only
first_letter=line[self._orig_start]
return {mforminmatchesifm.startswith(first_letter)}
deflocate(self,cursor_offset:int,line:str)->LinePart:
assertself._orig_startisnotNone
start=self._orig_start
end=cursor_offset
returnLinePart(start,end,line[start:end])
defget_completer(
completers:Sequence[BaseCompletionType],
cursor_offset:int,
line:str,
*,
locals_:dict[str,Any]|None=None,
argspec:inspection.FuncProps|None=None,
history:list[str]|None=None,
current_block:str|None=None,
complete_magic_methods:bool|None=None,
)->tuple[list[str],BaseCompletionType|None]:
"""Returns a list of matches and an applicable completer
If no matches available, returns a tuple of an empty list and None
cursor_offset is the current cursor column
line is a string of the current line
kwargs (all optional):
locals_ is a dictionary of the environment
argspec is an inspection.FuncProps instance for the current function where
the cursor is
current_block is the possibly multiline not-yet-evaluated block of
code which the current line is part of
complete_magic_methods is a bool of whether we ought to complete
double underscore methods like __len__ in method signatures
"""
def_cmpl_sort(x:str)->tuple[bool,str]:
"""
Function used to sort the matches.
"""
# put parameters above everything in completion
return (
x[-1]!="=",
x,
)
forcompleterincompleters:
try:
matches=completer.matches(
cursor_offset,
line,
locals_=locals_,
funcprops=argspec,
history=history,
current_block=current_block,
complete_magic_methods=complete_magic_methods,
)
exceptExceptionase:
# Instead of crashing the UI, log exceptions from autocompleters.
logger.debug(
"Completer %r failed with unhandled exception: %s",completer,e
)
continue
ifmatchesisnotNone:
returnsorted(matches,key=_cmpl_sort), (
completerifmatcheselseNone
)
return [],None
defget_default_completer(
mode:AutocompleteModes,module_gatherer:ModuleGatherer
)->tuple[BaseCompletionType, ...]:
return (
(
DictKeyCompletion(mode=mode),
ImportCompletion(module_gatherer,mode=mode),
FilenameCompletion(mode=mode),
MagicMethodCompletion(mode=mode),
MultilineJediCompletion(mode=mode),
CumulativeCompleter(
(
GlobalCompletion(mode=mode),
ParameterNameCompletion(mode=mode),
),
mode=mode,
),
AttrCompletion(mode=mode),
ExpressionAttributeCompletion(mode=mode),
)
ifmode!=AutocompleteModes.NONE
elsetuple()
)
def_callable_postfix(value:Any,word:str)->str:
"""rlcompleter's _callable_postfix done right."""
ifcallable(value):
word+="("
returnword