Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.2k
Expand file tree
/
Copy pathcompleting_reader.py
More file actions
Latest commit
332 lines (287 loc) · 11.2 KB
/
Copy pathcompleting_reader.py
File metadata and controls
332 lines (287 loc) · 11.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
# Copyright 2000-2010 Michael Hudson-Doyle <micahel@gmail.com>
# Antonio Cuni
#
# All Rights Reserved
#
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
#
# THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ importannotations
fromdataclassesimportdataclass, field
fromtypingimportTYPE_CHECKING
importre
from . importcommands, console, reader
from .renderimportRenderLine, ScreenOverlay
from .readerimportReader
# types
Command=commands.Command
ifTYPE_CHECKING:
from .typesimportCompletionAction, Keymap
defprefix(wordlist: list[str], j: int=0) ->str:
d= {}
i=j
try:
while1:
forwordinwordlist:
d[word[i]] =1
iflen(d) >1:
returnwordlist[0][j:i]
i+=1
d= {}
exceptIndexError:
returnwordlist[0][j:i]
return""
STRIPCOLOR_REGEX=re.compile(r"\x1B\[([0-9]{1,3}(;[0-9]{1,2})?)?[m|K]")
defstripcolor(s: str) ->str:
returnSTRIPCOLOR_REGEX.sub('', s)
defreal_len(s: str) ->int:
returnlen(stripcolor(s))
defleft_align(s: str, maxlen: int) ->str:
stripped=stripcolor(s)
iflen(stripped) >maxlen:
# too bad, we remove the color
returnstripped[:maxlen]
padding=maxlen-len(stripped)
returns+' '*padding
defbuild_menu(
cons: console.Console,
wordlist: list[str],
start: int,
use_brackets: bool,
sort_in_column: bool,
) ->tuple[list[str], int]:
ifuse_brackets:
item="[ %s ]"
padding=4
else:
item="%s "
padding=2
maxlen=min(max(map(real_len, wordlist)), cons.width-padding)
cols=int(cons.width/ (maxlen+padding))
rows=int((len(wordlist) -1)/cols+1)
ifsort_in_column:
# sort_in_column=False (default) sort_in_column=True
# A B C A D G
# D E F B E
# G C F
#
# "fill" the table with empty words, so we always have the same amount
# of rows for each column
missing=cols*rows-len(wordlist)
wordlist=wordlist+ ['']*missing
indexes= [(i%cols) *rows+i//colsforiinrange(len(wordlist))]
wordlist= [wordlist[i] foriinindexes]
menu= []
i=start
forrinrange(rows):
row= []
forcolinrange(cols):
row.append(item%left_align(wordlist[i], maxlen))
i+=1
ifi>=len(wordlist):
break
menu.append(''.join(row))
ifi>=len(wordlist):
i=0
break
ifr+5>cons.height:
menu.append(" %d more... "% (len(wordlist) -i))
break
returnmenu, i
# this gets somewhat user interface-y, and as a result the logic gets
# very convoluted.
#
# To summarise the summary of the summary:- people are a problem.
# -- The Hitch-Hikers Guide to the Galaxy, Episode 12
#### Desired behaviour of the completions commands.
# the considerations are:
# (1) how many completions are possible
# (2) whether the last command was a completion
# (3) if we can assume that the completer is going to return the same set of
# completions: this is controlled by the ``assume_immutable_completions``
# variable on the reader, which is True by default to match the historical
# behaviour of pyrepl, but e.g. False in the ReadlineAlikeReader to match
# more closely readline's semantics (this is needed e.g. by
# fancycompleter)
#
# if there's no possible completion, beep at the user and point this out.
# this is easy.
#
# if there's only one possible completion, stick it in. if the last thing
# user did was a completion, point out that he isn't getting anywhere, but
# only if the ``assume_immutable_completions`` is True.
#
# now it gets complicated.
#
# for the first press of a completion key:
# if there's a common prefix, stick it in.
# irrespective of whether anything got stuck in, if the word is now
# complete, show the "complete but not unique" message
# if there's no common prefix and if the word is not now complete,
# beep.
# common prefix -> yes no
# word complete \/
# yes "cbnu" "cbnu"
# no - beep
# for the second bang on the completion key
# there will necessarily be no common prefix
# show a menu of the choices.
# for subsequent bangs, rotate the menu around (if there are sufficient
# choices).
classcomplete(commands.Command):
defdo(self) ->None:
r: CompletingReader
r=self.reader# type: ignore[assignment]
last_is_completer=r.last_command_is(self.__class__)
ifr.cmpltn_action:
iflast_is_completer: # double-tab: execute action
msg=r.cmpltn_action[1]()
r.cmpltn_action=None# consumed
ifmsg:
r.msg=msg
r.cmpltn_message_visible=True
r.invalidate_message()
else: # other input since last tab: cancel action
r.cmpltn_action=None
immutable_completions=r.assume_immutable_completions
completions_unchangable=last_is_completerandimmutable_completions
stem=r.get_stem()
ifnotcompletions_unchangable:
r.cmpltn_menu_choices, r.cmpltn_action=r.get_completions(stem)
completions=r.cmpltn_menu_choices
ifnotcompletions:
ifnotr.cmpltn_action:
r.error("no matches")
eliflen(completions) ==1:
completion=stripcolor(completions[0])
ifcompletions_unchangableandlen(completion) ==len(stem):
r.msg="[ sole completion ]"
r.cmpltn_message_visible=True
r.invalidate_message()
r.insert(completion[len(stem):])
else:
clean_completions= [stripcolor(word) forwordincompletions]
p=prefix(clean_completions, len(stem))
ifp:
r.insert(p)
iflast_is_completer:
r.cmpltn_menu_visible=True
r.cmpltn_menu, r.cmpltn_menu_end=build_menu(
r.console, completions, r.cmpltn_menu_end,
r.use_brackets, r.sort_in_column)
ifr.msg:
r.msg=""
r.cmpltn_message_visible=False
r.invalidate_message()
r.invalidate_overlay()
elifnotr.cmpltn_menu_visible:
ifstem+pinclean_completions:
r.msg="[ complete but not unique ]"
r.cmpltn_message_visible=True
r.invalidate_message()
else:
r.msg="[ not unique ]"
r.cmpltn_message_visible=True
r.invalidate_message()
ifr.cmpltn_action:
ifr.msgandr.cmpltn_message_visible:
# There is already a message (eg. [ not unique ]) that
# would conflict for next tab: cancel action
r.cmpltn_action=None
else:
r.msg=r.cmpltn_action[0]
r.cmpltn_message_visible=True
r.invalidate_message()
classself_insert(commands.self_insert):
defdo(self) ->None:
r: CompletingReader
r=self.reader# type: ignore[assignment]
commands.self_insert.do(self)
ifr.cmpltn_menu_visible:
stem=r.get_stem()
iflen(stem) <1:
r.cmpltn_reset()
else:
completions= [wforwinr.cmpltn_menu_choices
ifstripcolor(w).startswith(stem)]
ifcompletions:
r.cmpltn_menu, r.cmpltn_menu_end=build_menu(
r.console, completions, 0,
r.use_brackets, r.sort_in_column)
r.invalidate_overlay()
else:
r.cmpltn_reset()
@dataclass
classCompletingReader(Reader):
"""Adds completion support"""
### Class variables
# see the comment for the complete command
assume_immutable_completions=True
use_brackets=True# display completions inside []
sort_in_column=False
### Instance variables
cmpltn_menu: list[str] =field(init=False)
cmpltn_menu_visible: bool=field(init=False)
cmpltn_message_visible: bool=field(init=False)
cmpltn_menu_end: int=field(init=False)
cmpltn_menu_choices: list[str] =field(init=False)
cmpltn_action: CompletionAction|None=field(init=False)
def__post_init__(self) ->None:
super().__post_init__()
self.cmpltn_reset()
forcin (complete, self_insert):
self.commands[c.__name__] =c
self.commands[c.__name__.replace('_', '-')] =c
defcollect_keymap(self) ->Keymap:
returnsuper().collect_keymap() + (
(r'\t', 'complete'),)
defafter_command(self, cmd: Command) ->None:
super().after_command(cmd)
ifnotisinstance(cmd, (complete, self_insert)):
self.cmpltn_reset()
defget_screen_overlays(self) ->tuple[ScreenOverlay, ...]:
ifnotself.cmpltn_menu_visible:
return ()
return (
ScreenOverlay(
self.lxy[1] +1,
tuple(RenderLine.from_rendered_text(line) forlineinself.cmpltn_menu),
insert=True,
),
)
deffinish(self) ->None:
super().finish()
self.cmpltn_reset()
defcmpltn_reset(self) ->None:
ifgetattr(self, "cmpltn_menu_visible", False):
self.invalidate_overlay()
self.cmpltn_menu= []
self.cmpltn_menu_visible=False
self.cmpltn_message_visible=False
self.cmpltn_menu_end=0
self.cmpltn_menu_choices= []
self.cmpltn_action=None
defget_stem(self) ->str:
st=self.syntax_table
SW=reader.SYNTAX_WORD
b=self.buffer
p=self.pos-1
whilep>=0andst.get(b[p], SW) ==SW:
p-=1
return''.join(b[p+1:self.pos])
defget_completions(self, stem: str) ->tuple[list[str], CompletionAction|None]:
return [], None
defget_line(self) ->str:
"""Return the current line until the cursor position."""
return''.join(self.buffer[:self.pos])