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 pathreadline.py
More file actions
Latest commit
649 lines (546 loc) · 22.4 KB
/
Copy pathreadline.py
File metadata and controls
649 lines (546 loc) · 22.4 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
# Copyright 2000-2010 Michael Hudson-Doyle <micahel@gmail.com>
# Alex Gaynor
# Antonio Cuni
# Armin Rigo
# Holger Krekel
#
# 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.
"""A compatibility wrapper reimplementing the 'readline' standard module
on top of pyrepl. Not all functionalities are supported. Contains
extensions for multiline input.
"""
from __future__ importannotations
importwarnings
fromdataclassesimportdataclass, field
importos
fromsiteimportgethistoryfile
importsys
fromrlcompleterimportCompleterasRLCompleter
from . importcommands, historical_reader
from .completing_readerimportCompletingReader, stripcolor
from .consoleimportConsoleasConsoleType
from ._module_completerimportModuleCompleter, make_default_module_completer
from .fancycompleterimportCompleterasFancyCompleter, colorize_matches
Console: type[ConsoleType]
_error: tuple[type[Exception], ...] |type[Exception]
ifos.name=="nt":
from .windows_consoleimportWindowsConsoleasConsole, _error
else:
from .unix_consoleimportUnixConsoleasConsole, _error
ENCODING=sys.getdefaultencoding() or"latin1"
# types
Command=commands.Command
fromcollections.abcimportCallable, Collection
from .typesimportCallback, Completer, KeySpec, CommandName, CompletionAction
TYPE_CHECKING=False
ifTYPE_CHECKING:
fromtypingimportAny, Mapping
MoreLinesCallable=Callable[[str], bool]
__all__= [
"add_history",
"clear_history",
"get_begidx",
"get_completer",
"get_completer_delims",
"get_current_history_length",
"get_endidx",
"get_history_item",
"get_history_length",
"get_line_buffer",
"insert_text",
"parse_and_bind",
"read_history_file",
# "read_init_file",
# "redisplay",
"remove_history_item",
"replace_history_item",
"set_auto_history",
"set_completer",
"set_completer_delims",
"set_history_length",
# "set_pre_input_hook",
"set_startup_hook",
"write_history_file",
"append_history_file",
# ---- multiline extensions ----
"multiline_input",
]
# ____________________________________________________________
@dataclass
classReadlineConfig:
readline_completer: Completer|None=None
completer_delims: frozenset[str] =frozenset(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?")
module_completer: ModuleCompleter=field(default_factory=make_default_module_completer)
colorize_completions: Callable[[list[str], list[Any]], list[str]] |None=None
@dataclass(kw_only=True)
classReadlineAlikeReader(historical_reader.HistoricalReader, CompletingReader):
# Class fields
assume_immutable_completions=False
use_brackets=False
sort_in_column=True
# Instance fields
config: ReadlineConfig
more_lines: MoreLinesCallable|None=None
last_used_indentation: str|None=None
def__post_init__(self) ->None:
super().__post_init__()
self.commands["maybe_accept"] =maybe_accept
self.commands["maybe-accept"] =maybe_accept
self.commands["backspace_dedent"] =backspace_dedent
self.commands["backspace-dedent"] =backspace_dedent
deferror(self, msg: str="none") ->None:
pass# don't show error messages by default
defget_stem(self) ->str:
b=self.buffer
p=self.pos-1
completer_delims=self.config.completer_delims
whilep>=0andb[p] notincompleter_delims:
p-=1
return"".join(b[p+1 : self.pos])
defget_completions(self, stem: str) ->tuple[list[str], CompletionAction|None]:
module_completions=self.get_module_completions()
ifmodule_completionsisnotNone:
returnmodule_completions
iflen(stem) ==0andself.more_linesisnotNone:
b=self.buffer
p=self.pos
whilep>0andb[p-1] !="\n":
p-=1
num_spaces=4- ((self.pos-p) %4)
return [" "*num_spaces], None
result= []
function=self.config.readline_completer
iffunctionisnotNone:
try:
stem=str(stem) # rlcompleter.py seems to not like unicode
exceptUnicodeEncodeError:
pass# but feed unicode anyway if we have no choice
state=0
whileTrue:
try:
next=function(stem, state)
exceptException:
break
ifnotisinstance(next, str):
break
result.append(next)
state+=1
# Emulate readline's sorting using the visible text rather than
# the raw ANSI escape sequences used for colorized matches.
result.sort(key=stripcolor)
returnresult, None
defget_module_completions(self) ->tuple[list[str], CompletionAction|None] |None:
line=stripcolor(self.get_line())
colorize_completions=self.config.colorize_completions
result=self.config.module_completer.get_completions(
line, include_values=bool(colorize_completions)
)
ifresultisNone:
returnNone
names, values, action=result
ifcolorize_completions:
names=colorize_completions(names, values)
returnnames, action
defget_trimmed_history(self, maxlength: int) ->list[str]:
ifmaxlength>=0:
cut=len(self.history) -maxlength
ifcut<0:
cut=0
else:
cut=0
returnself.history[cut:]
defupdate_last_used_indentation(self) ->None:
indentation=_get_first_indentation(self.buffer)
ifindentationisnotNone:
self.last_used_indentation=indentation
# --- simplified support for reading multiline Python statements ---
defcollect_keymap(self) ->tuple[tuple[KeySpec, CommandName], ...]:
returnsuper().collect_keymap() + (
(r"\n", "maybe-accept"),
(r"\<backspace>", "backspace-dedent"),
)
defafter_command(self, cmd: Command) ->None:
super().after_command(cmd)
ifself.more_linesisNone:
# Force single-line input if we are in raw_input() mode.
# Although there is no direct way to add a \n in this mode,
# multiline buffers can still show up using various
# commands, e.g. navigating the history.
try:
index=self.buffer.index("\n")
exceptValueError:
pass
else:
self.buffer=self.buffer[:index]
ifself.pos>len(self.buffer):
self.pos=len(self.buffer)
defset_auto_history(_should_auto_add_history: bool) ->None:
"""Enable or disable automatic history"""
historical_reader.should_auto_add_history=bool(_should_auto_add_history)
def_get_this_line_indent(buffer: list[str], pos: int) ->int:
indent=0
whilepos>0andbuffer[pos-1] in" \t":
indent+=1
pos-=1
ifpos>0andbuffer[pos-1] =="\n":
returnindent
return0
def_get_previous_line_indent(buffer: list[str], pos: int) ->tuple[int, int|None]:
prevlinestart=pos
whileprevlinestart>0andbuffer[prevlinestart-1] !="\n":
prevlinestart-=1
prevlinetext=prevlinestart
whileprevlinetext<posandbuffer[prevlinetext] in" \t":
prevlinetext+=1
ifprevlinetext==pos:
indent=None
else:
indent=prevlinetext-prevlinestart
returnprevlinestart, indent
def_get_first_indentation(buffer: list[str]) ->str|None:
indented_line_start=None
foriinrange(len(buffer)):
if (i<len(buffer) -1
andbuffer[i] =="\n"
andbuffer[i+1] in" \t"
):
indented_line_start=i+1
elifindented_line_startisnotNoneandbuffer[i] notin" \t\n":
return''.join(buffer[indented_line_start : i])
returnNone
def_should_auto_indent(buffer: list[str], pos: int) ->bool:
# check if last character before "pos" is a colon, ignoring
# whitespaces and comments.
last_char=None
whilepos>0:
pos-=1
iflast_charisNone:
ifbuffer[pos] notin" \t\n#": # ignore whitespaces and comments
last_char=buffer[pos]
else:
# even if we found a non-whitespace character before
# original pos, we keep going back until newline is reached
# to make sure we ignore comments
ifbuffer[pos] =="\n":
break
ifbuffer[pos] =="#":
last_char=None
returnlast_char==":"
classmaybe_accept(commands.Command):
defdo(self) ->None:
r: ReadlineAlikeReader
r=self.reader# type: ignore[assignment]
r.invalidate_overlay() # hide completion menu, if visible
# if there are already several lines and the cursor
# is not on the last one, always insert a new \n.
text=r.get_unicode()
if"\n"inr.buffer[r.pos :] or (
r.more_linesisnotNoneandr.more_lines(text)
):
def_newline_before_pos():
before_idx=r.pos-1
whilebefore_idx>0andtext[before_idx].isspace():
before_idx-=1
returntext[before_idx : r.pos].count("\n") >0
# if there's already a new line before the cursor then
# even if the cursor is followed by whitespace, we assume
# the user is trying to terminate the block
if_newline_before_pos() andtext[r.pos:].isspace():
self.finish=True
return
# auto-indent the next line like the previous line
prevlinestart, indent=_get_previous_line_indent(r.buffer, r.pos)
r.insert("\n")
ifnotself.reader.paste_mode:
ifindent:
foriinrange(prevlinestart, prevlinestart+indent):
r.insert(r.buffer[i])
r.update_last_used_indentation()
if_should_auto_indent(r.buffer, r.pos):
ifr.last_used_indentationisnotNone:
indentation=r.last_used_indentation
else:
# default
indentation=" "*4
r.insert(indentation)
elifnotself.reader.paste_mode:
self.finish=True
else:
r.insert("\n")
classbackspace_dedent(commands.Command):
defdo(self) ->None:
r=self.reader
b=r.buffer
ifr.pos>0:
repeat=1
ifb[r.pos-1] !="\n":
indent=_get_this_line_indent(b, r.pos)
ifindent>0:
ls=r.pos-indent
whilels>0:
ls, pi=_get_previous_line_indent(b, ls-1)
ifpiisnotNoneandpi<indent:
repeat=indent-pi
break
r.pos-=repeat
delb[r.pos : r.pos+repeat]
r.invalidate_buffer(r.pos)
else:
self.reader.error("can't backspace at start")
# ____________________________________________________________
@dataclass(slots=True)
class_ReadlineWrapper:
f_in: int=-1
f_out: int=-1
reader: ReadlineAlikeReader|None=field(default=None, repr=False)
saved_history_length: int=-1
startup_hook: Callback|None=None
config: ReadlineConfig=field(default_factory=ReadlineConfig, repr=False)
def__post_init__(self) ->None:
ifself.f_in==-1:
self.f_in=os.dup(0)
ifself.f_out==-1:
self.f_out=os.dup(1)
defget_reader(self) ->ReadlineAlikeReader:
ifself.readerisNone:
console=Console(self.f_in, self.f_out, encoding=ENCODING)
self.reader=ReadlineAlikeReader(console=console, config=self.config)
returnself.reader
definput(self, prompt: object="") ->str:
try:
reader=self.get_reader()
except_error:
assertraw_inputisnotNone
returnraw_input(prompt)
prompt_str=str(prompt)
reader.ps1=prompt_str
sys.audit("builtins.input", prompt_str)
result=reader.readline(startup_hook=self.startup_hook)
sys.audit("builtins.input/result", result)
returnresult
defmultiline_input(self, more_lines: MoreLinesCallable, ps1: str, ps2: str) ->str:
"""Read an input on possibly multiple lines, asking for more
lines as long as 'more_lines(unicodetext)' returns an object whose
boolean value is true.
"""
reader=self.get_reader()
saved=reader.more_lines
try:
reader.more_lines=more_lines
reader.ps1=ps1
reader.ps2=ps1
reader.ps3=ps2
reader.ps4=""
withwarnings.catch_warnings(action="ignore"):
returnreader.readline()
finally:
reader.more_lines=saved
reader.paste_mode=False
defparse_and_bind(self, string: str) ->None:
pass# XXX we don't support parsing GNU-readline-style init files
defset_completer(self, function: Completer|None=None) ->None:
self.config.readline_completer=function
defget_completer(self) ->Completer|None:
returnself.config.readline_completer
defset_completer_delims(self, delimiters: Collection[str]) ->None:
self.config.completer_delims=frozenset(delimiters)
defget_completer_delims(self) ->str:
return"".join(sorted(self.config.completer_delims))
def_histline(self, line: str, *, sanitize_nuls: bool=False) ->str:
line=line.rstrip("\n")
if"\0"inline:
ifnotsanitize_nuls:
raiseValueError("embedded null character")
line=line.replace("\0", "")
returnline
defget_history_length(self) ->int:
returnself.saved_history_length
defset_history_length(self, length: int) ->None:
self.saved_history_length=length
defget_current_history_length(self) ->int:
returnlen(self.get_reader().history)
defread_history_file(self, filename: str=gethistoryfile()) ->None:
# multiline extension (really a hack) for the end of lines that
# are actually continuations inside a single multiline_input()
# history item: we use \r\n instead of just \n. If the history
# file is passed to GNU readline, the extra \r are just ignored.
history=self.get_reader().history
withopen(os.path.expanduser(filename), 'rb') asf:
is_editline=f.readline().startswith(b"_HiStOrY_V2_")
ifis_editline:
encoding="unicode-escape"
else:
f.seek(0)
encoding="utf-8"
lines= [line.decode(encoding, errors='replace') forlineinf.read().split(b'\n')]
buffer= []
forlineinlines:
ifline.endswith("\r"):
buffer.append(line+'\n')
else:
line=self._histline(line, sanitize_nuls=True)
ifbuffer:
line=self._histline(
"".join(buffer).replace("\r", "") +line,
sanitize_nuls=True,
)
delbuffer[:]
ifline:
history.append(line)
self.set_history_length(self.get_current_history_length())
defwrite_history_file(self, filename: str=gethistoryfile()) ->None:
maxlength=self.saved_history_length
history=self.get_reader().get_trimmed_history(maxlength)
f=open(os.path.expanduser(filename), "w",
encoding="utf-8", newline="\n")
withf:
forentryinhistory:
entry=entry.replace("\n", "\r\n") # multiline history support
f.write(entry+"\n")
defappend_history_file(self, filename: str=gethistoryfile()) ->None:
reader=self.get_reader()
saved_length=self.get_history_length()
length=self.get_current_history_length() -saved_length
history=reader.get_trimmed_history(length)
f=open(os.path.expanduser(filename), "a",
encoding="utf-8", newline="\n")
withf:
forentryinhistory:
entry=entry.replace("\n", "\r\n") # multiline history support
f.write(entry+"\n")
self.set_history_length(saved_length+length)
defclear_history(self) ->None:
delself.get_reader().history[:]
defget_history_item(self, index: int) ->str|None:
history=self.get_reader().history
if1<=index<=len(history):
returnhistory[index-1]
else:
returnNone# like readline.c
defremove_history_item(self, index: int) ->None:
history=self.get_reader().history
if0<=index<len(history):
delhistory[index]
else:
raiseValueError("No history item at position %d"%index)
# like readline.c
defreplace_history_item(self, index: int, line: str) ->None:
history=self.get_reader().history
if0<=index<len(history):
history[index] =self._histline(line)
else:
raiseValueError("No history item at position %d"%index)
# like readline.c
defadd_history(self, line: str) ->None:
self.get_reader().history.append(self._histline(line))
defset_startup_hook(self, function: Callback|None=None) ->None:
self.startup_hook=function
defget_line_buffer(self) ->str:
returnself.get_reader().get_unicode()
def_get_idxs(self) ->tuple[int, int]:
start=cursor=self.get_reader().pos
buf=self.get_line_buffer()
foriinrange(cursor-1, -1, -1):
ifbuf[i] inself.get_completer_delims():
break
start=i
returnstart, cursor
defget_begidx(self) ->int:
returnself._get_idxs()[0]
defget_endidx(self) ->int:
returnself._get_idxs()[1]
definsert_text(self, text: str) ->None:
self.get_reader().insert(text)
_wrapper=_ReadlineWrapper()
# ____________________________________________________________
# Public API
parse_and_bind=_wrapper.parse_and_bind
set_completer=_wrapper.set_completer
get_completer=_wrapper.get_completer
set_completer_delims=_wrapper.set_completer_delims
get_completer_delims=_wrapper.get_completer_delims
get_history_length=_wrapper.get_history_length
set_history_length=_wrapper.set_history_length
get_current_history_length=_wrapper.get_current_history_length
read_history_file=_wrapper.read_history_file
write_history_file=_wrapper.write_history_file
append_history_file=_wrapper.append_history_file
clear_history=_wrapper.clear_history
get_history_item=_wrapper.get_history_item
remove_history_item=_wrapper.remove_history_item
replace_history_item=_wrapper.replace_history_item
add_history=_wrapper.add_history
set_startup_hook=_wrapper.set_startup_hook
get_line_buffer=_wrapper.get_line_buffer
get_begidx=_wrapper.get_begidx
get_endidx=_wrapper.get_endidx
insert_text=_wrapper.insert_text
# Extension
multiline_input=_wrapper.multiline_input
# Internal hook
_get_reader=_wrapper.get_reader
# ____________________________________________________________
# Stubs
def_make_stub(_name: str, _ret: object) ->None:
defstub(*args: object, **kwds: object) ->None:
importwarnings
warnings.warn("readline.%s() not implemented"%_name, stacklevel=2)
stub.__name__=_name
globals()[_name] =stub
for_name, _retin [
("read_init_file", None),
("redisplay", None),
("set_pre_input_hook", None),
]:
assert_namenotinglobals(), _name
_make_stub(_name, _ret)
# ____________________________________________________________
def_setup(namespace: Mapping[str, Any]) ->None:
globalraw_input
ifraw_inputisnotNone:
return# don't run _setup twice
try:
f_in=sys.stdin.fileno()
f_out=sys.stdout.fileno()
except (AttributeError, ValueError):
return
ifnotos.isatty(f_in) ornotos.isatty(f_out):
return
_wrapper.f_in=f_in
_wrapper.f_out=f_out
# set up namespace in rlcompleter, which requires it to be a bona fide dict
ifnotisinstance(namespace, dict):
namespace=dict(namespace)
use_basic_completer= (
notsys.flags.ignore_environment
andos.getenv("PYTHON_BASIC_COMPLETER")
)
completer_cls=RLCompleterifuse_basic_completerelseFancyCompleter
completer=completer_cls(namespace)
_wrapper.config.readline_completer=completer.complete
ifisinstance(completer, FancyCompleter) andcompleter.use_colors:
theme=completer.theme
def_colorize(names: list[str], values: list[object]) ->list[str]:
returncolorize_matches(names, values, theme)
_wrapper.config.colorize_completions=_colorize
_wrapper.config.module_completer=ModuleCompleter(namespace)
# this is not really what readline.c does. Better than nothing I guess
importbuiltins
raw_input=builtins.input
builtins.input=_wrapper.input
raw_input: Callable[[object], str] |None=None