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 pathrepl.py
More file actions
2246 lines (1963 loc) · 82.8 KB
/
repl.py
File metadata and controls
2246 lines (1963 loc) · 82.8 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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
importcontextlib
importerrno
importitertools
importlogging
importos
importre
importsignal
importsubprocess
importsys
importtempfile
importtime
importunicodedata
fromenumimportEnum
fromtypesimportFrameType,TracebackType
fromtypingimport (
Any,
Literal,
)
fromcollections.abcimportIterable,Sequence
importgreenlet
fromcurtsiesimport (
FSArray,
fmtstr,
FmtStr,
Termmode,
fmtfuncs,
events,
__version__ascurtsies_version,
)
fromcurtsies.configfile_keynamesimportkeymapaskey_dispatch
fromcurtsies.inputimportis_main_thread
fromcurtsies.windowimportCursorAwareWindow
fromcwcwidthimportwcswidth
frompygmentsimportformataspygformat
frompygments.formattersimportTerminalFormatter
frompygments.lexersimportPython3Lexer
from .importeventsasbpythonevents,sitefix,replpainteraspaint
from ..configimportConfig
from .coderunnerimport (
CodeRunner,
FakeOutput,
)
from .filewatchimportModuleChangedEventHandler
from .interactionimportStatusBar
from .interpreterimport (
Interp,
code_finished_will_parse,
)
from .manual_readlineimport (
edit_keys,
cursor_on_closing_char_pair,
AbstractEdits,
)
from .parseimportparseasbpythonparse,func_for_letter,color_for_letter
from .preprocessimportpreprocess
from ..import__version__
from ..configimportgetpreferredencoding
from ..formatterimportBPythonFormatter
from ..pagerimportget_pager_command
from ..replimport (
Repl,
SourceNotFound,
)
from ..translationsimport_
from ..lineimportCHARACTER_PAIR_MAP
logger=logging.getLogger(__name__)
INCONSISTENT_HISTORY_MSG="#<---History inconsistent with output shown--->"
CONTIGUITY_BROKEN_MSG="#<---History contiguity broken by rewind--->"
EXAMPLE_CONFIG_URL="https://raw.githubusercontent.com/bpython/bpython/master/bpython/sample-config"
EDIT_SESSION_HEADER="""### current bpython session - make changes and save to reevaluate session.
### lines beginning with ### will be ignored.
### To return to bpython without reevaluating make no changes to this file
### or save an empty file.
"""
# more than this many events will be assumed to be a true paste event,
# i.e. control characters like '<Ctrl-a>' will be stripped
MAX_EVENTS_POSSIBLY_NOT_PASTE=20
classSearchMode(Enum):
NO_SEARCH=0
INCREMENTAL_SEARCH=1
REVERSE_INCREMENTAL_SEARCH=2
classLineType(Enum):
"""Used when adding a tuple to all_logical_lines, to get input / output values
having to actually type/know the strings"""
INPUT="input"
OUTPUT="output"
classFakeStdin:
"""The stdin object user code will reference
In user code, sys.stdin.read() asks the user for interactive input,
so this class returns control to the UI to get that input."""
def__init__(
self,
coderunner:CodeRunner,
repl:"BaseRepl",
configured_edit_keys:AbstractEdits|None=None,
):
self.coderunner=coderunner
self.repl=repl
self.has_focus=False# whether FakeStdin receives keypress events
self.current_line=""
self.cursor_offset=0
self.old_num_lines=0
self.readline_results:list[str]= []
ifconfigured_edit_keysisnotNone:
self.rl_char_sequences=configured_edit_keys
else:
self.rl_char_sequences=edit_keys
defprocess_event(self,e:events.Event|str)->None:
assertself.has_focus
logger.debug("fake input processing event %r",e)
ifisinstance(e,events.Event):
ifisinstance(e,events.PasteEvent):
foreeine.events:
ifeenotinself.rl_char_sequences:
self.add_input_character(ee)
elifisinstance(e,events.SigIntEvent):
self.coderunner.sigint_happened_in_main_context=True
self.has_focus=False
self.current_line=""
self.cursor_offset=0
self.repl.run_code_and_maybe_finish()
elifeinself.rl_char_sequences:
self.cursor_offset,self.current_line=self.rl_char_sequences[e](
self.cursor_offset,self.current_line
)
elife=="<Ctrl-d>":
ifnotlen(self.current_line):
self.repl.send_to_stdin("\n")
self.has_focus=False
self.current_line=""
self.cursor_offset=0
self.repl.run_code_and_maybe_finish(for_code="")
elifein ("\n","\r","<Ctrl-j>","<Ctrl-m>"):
line=f"{self.current_line}\n"
self.repl.send_to_stdin(line)
self.has_focus=False
self.current_line=""
self.cursor_offset=0
self.repl.run_code_and_maybe_finish(for_code=line)
elife!="<ESC>":# add normal character
self.add_input_character(e)
ifnotself.current_line.endswith(("\n","\r")):
self.repl.send_to_stdin(self.current_line)
defadd_input_character(self,e:str)->None:
ife=="<SPACE>":
e=" "
ife.startswith("<")ande.endswith(">"):
return
assertlen(e)==1,"added multiple characters: %r"%e
logger.debug("adding normal char %r to current line",e)
self.current_line= (
self.current_line[:self.cursor_offset]
+e
+self.current_line[self.cursor_offset :]
)
self.cursor_offset+=1
defreadline(self,size:int=-1)->str:
ifnotisinstance(size,int):
raiseTypeError(
f"'{type(size).__name__}' object cannot be interpreted as an integer"
)
elifsize==0:
return""
self.has_focus=True
self.repl.send_to_stdin(self.current_line)
value=self.coderunner.request_from_main_context()
assertisinstance(value,str)
self.readline_results.append(value)
returnvalueifsize<=-1elsevalue[:size]
defreadlines(self,size:int|None=-1)->list[str]:
ifsizeisNone:
# the default readlines implementation also accepts None
size=-1
ifnotisinstance(size,int):
raiseTypeError("argument should be integer or None, not 'str'")
ifsize<=0:
# read as much as we can
returnlist(iter(self.readline,""))
lines= []
whilesize>0:
line=self.readline()
lines.append(line)
size-=len(line)
returnlines
def__iter__(self):
returniter(self.readlines())
defisatty(self)->bool:
returnTrue
defflush(self)->None:
"""Flush the internal buffer. This is a no-op. Flushing stdin
doesn't make any sense anyway."""
defwrite(self,value):
# XXX IPython expects sys.stdin.write to exist, there will no doubt be
# others, so here's a hack to keep them happy
raiseOSError(errno.EBADF,"sys.stdin is read-only")
defclose(self)->None:
# hack to make closing stdin a nop
# This is useful for multiprocessing.Process, which does work
# for the most part, although output from other processes is
# discarded.
pass
@property
defencoding(self)->str:
# `encoding` is new in py39
returnsys.__stdin__.encoding# type: ignore
# TODO write a read() method?
classReevaluateFakeStdin:
"""Stdin mock used during reevaluation (undo) so raw_inputs don't have to
be reentered"""
def__init__(self,fakestdin:FakeStdin,repl:"BaseRepl"):
self.fakestdin=fakestdin
self.repl=repl
self.readline_results=fakestdin.readline_results[:]
defreadline(self):
ifself.readline_results:
value=self.readline_results.pop(0)
else:
value="no saved input available"
self.repl.send_to_stdouterr(value)
returnvalue
classImportLoader:
"""Wrapper for module loaders to watch their paths with watchdog."""
def__init__(self,watcher,loader):
self.watcher=watcher
self.loader=loader
def__getattr__(self,name):
ifname=="create_module"andhasattr(self.loader,name):
returnself._create_module
returngetattr(self.loader,name)
def_create_module(self,spec):
module_object=self.loader.create_module(spec)
if (
getattr(spec,"origin",None)isnotNone
andspec.origin!="builtin"
):
self.watcher.track_module(spec.origin)
returnmodule_object
classImportFinder:
"""Wrapper for finders in sys.meta_path to wrap all loaders with ImportLoader."""
def__init__(self,watcher,finder):
self.watcher=watcher
self.finder=finder
def__getattr__(self,name):
ifname=="find_spec"andhasattr(self.finder,name):
returnself._find_spec
returngetattr(self.finder,name)
def_find_spec(self,fullname,path,target=None):
# Attempt to find the spec
spec=self.finder.find_spec(fullname,path,target)
ifspecisnotNone:
ifgetattr(spec,"loader",None)isnotNone:
# Patch the loader to enable reloading
spec.loader=ImportLoader(self.watcher,spec.loader)
returnspec
def_process_ps(ps,default_ps:str):
"""Replace ps1/ps2 with the default if the user specified value contains control characters."""
ifnotisinstance(ps,str):
returnps
returnpsifwcswidth(ps)>=0elsedefault_ps
classBaseRepl(Repl):
"""Python Repl
Reacts to events like
- terminal dimensions and change events
- keystrokes
Behavior altered by
- number of scroll downs that were necessary to render array after each
display
- initial cursor position
outputs:
- 2D array to be rendered
BaseRepl is mostly view-independent state of Repl - but self.width and
self.height are important for figuring out how to wrap lines for example.
Usually self.width and self.height should be set by receiving a window
resize event, not manually set to anything - as long as the first event
received is a window resize event, this works fine.
Subclasses are responsible for implementing several methods.
"""
def__init__(
self,
config:Config,
window:CursorAwareWindow,
locals_:dict[str,Any]|None=None,
banner:str|None=None,
interp:Interp|None=None,
orig_tcattrs:list[Any]|None=None,
):
"""
locals_ is a mapping of locals to pass into the interpreter
config is a bpython config.Struct with config attributes
banner is a string to display briefly in the status bar
interp is an interpreter instance to use
original terminal state, useful for shelling out with normal terminal
"""
logger.debug("starting init")
self.window=window
# If creating a new interpreter on undo would be unsafe because initial
# state was passed in
self.weak_rewind=bool(locals_orinterp)
ifinterpisNone:
interp=Interp(locals=locals_)
interp.write=self.send_to_stdouterr# type: ignore
ifconfig.cli_suggestion_width<=0orconfig.cli_suggestion_width>1:
config.cli_suggestion_width=1
self.reevaluating=False
self.fake_refresh_requested=False
self.status_bar=StatusBar(
config,
"",
request_refresh=self.request_refresh,
schedule_refresh=self.schedule_refresh,
)
self.edit_keys=edit_keys.mapping_with_config(config,key_dispatch)
logger.debug("starting parent init")
# interp is a subclass of repl.Interpreter, so it definitely,
# implements the methods of Interpreter!
super().__init__(interp,config)
self.formatter=BPythonFormatter(config.color_scheme)
# overwriting what bpython.Repl put there
# interact is called to interact with the status bar,
# so we're just using the same object
self.interact=self.status_bar
# logical line currently being edited, without ps1 (usually '>>> ')
self._current_line=""
# current line of output - stdout and stdin go here
self.current_stdouterr_line:str|FmtStr=""
# this is every line that's been displayed (input and output)
# as with formatting applied. Logical lines that exceeded the terminal width
# at the time of output are split across multiple entries in this list.
self.display_lines:list[FmtStr]= []
# this is every line that's been executed; it gets smaller on rewind
self.history= []
# This is every logical line that's been displayed, both input and output.
# Like self.history, lines are unwrapped, uncolored, and without prompt.
# Entries are tuples, where
# - the first element the line (string, not fmtsr)
# - the second element is one of 2 global constants: "input" or "output"
# (use LineType.INPUT or LineType.OUTPUT to avoid typing these strings)
self.all_logical_lines:list[tuple[str,LineType]]= []
# formatted version of lines in the buffer kept around so we can
# unhighlight parens using self.reprint_line as called by bpython.Repl
self.display_buffer:list[FmtStr]= []
# how many times display has been scrolled down
# because there wasn't room to display everything
self.scroll_offset=0
# cursor position relative to start of current_line, 0 is first char
self._cursor_offset=0
self.orig_tcattrs:list[Any]|None=orig_tcattrs
self.coderunner=CodeRunner(self.interp,self.request_refresh)
# filenos match the backing device for libs that expect it,
# but writing to them will do weird things to the display
self.stdout=FakeOutput(
self.coderunner,
self.send_to_stdouterr,
real_fileobj=sys.__stdout__,
)
self.stderr=FakeOutput(
self.coderunner,
self.send_to_stdouterr,
real_fileobj=sys.__stderr__,
)
self.stdin=FakeStdin(self.coderunner,self,self.edit_keys)
# next paint should clear screen
self.request_paint_to_clear_screen=False
self.request_paint_to_pad_bottom=0
# offscreen command yields results different from scrollback buffer
self.inconsistent_history=False
# history error message has already been displayed
self.history_already_messed_up=False
# some commands act differently based on the prev event
# this list doesn't include instances of event.Event,
# only keypress-type events (no refresh screen events etc.)
self.last_events:list[str|None]= [None]*50
# displays prev events in a column on the right hand side
self.presentation_mode=False
self.paste_mode=False
self.current_match=None
self.list_win_visible=False
# whether auto reloading active
self.watching_files=config.default_autoreload
self.incr_search_mode=SearchMode.NO_SEARCH
self.incr_search_target=""
self.original_modules=set(sys.modules.keys())
# as long as the first event received is a window resize event,
# this works fine...
try:
self.width,self.height=os.get_terminal_size()
exceptOSError:
# this case will trigger during unit tests when stdout is redirected
self.width=-1
self.height=-1
self.status_bar.message(banner)
self.watcher=ModuleChangedEventHandler([],self.request_reload)
ifself.watcherandconfig.default_autoreload:
self.watcher.activate()
# The methods below should be overridden, but the default implementations
# below can be used as well.
defget_cursor_vertical_diff(self)->int:
"""Return how the cursor moved due to a window size change"""
return0
defget_top_usable_line(self)->int:
"""Return the top line of display that can be rewritten"""
return0
defget_term_hw(self)->tuple[int,int]:
"""Returns the current width and height of the display area."""
return (50,10)
def_schedule_refresh(self,when:float):
"""Arrange for the bpython display to be refreshed soon.
This method will be called when the Repl wants the display to be
refreshed at a known point in the future, and as such it should
interrupt a pending request to the user for input.
Because the worst-case effect of not refreshing
is only having an out of date UI until the user enters input, a
default NOP implementation is provided."""
# The methods below must be overridden in subclasses.
def_request_refresh(self):
"""Arrange for the bpython display to be refreshed soon.
This method will be called when the Repl wants to refresh the display,
but wants control returned to it afterwards. (it is assumed that simply
returning from process_event will cause an event refresh)
The very next event received by process_event should be a
RefreshRequestEvent."""
raiseNotImplementedError
def_request_reload(self,files_modified:Sequence[str])->None:
"""Like request_refresh, but for reload requests events."""
raiseNotImplementedError
defrequest_undo(self,n=1):
"""Like request_refresh, but for undo request events."""
raiseNotImplementedError
defon_suspend(self):
"""Will be called on sigtstp.
Do whatever cleanup would allow the user to use other programs."""
raiseNotImplementedError
defafter_suspend(self):
"""Will be called when process foregrounded after suspend.
See to it that process_event is called with None to trigger a refresh
if not in the middle of a process_event call when suspend happened."""
raiseNotImplementedError
# end methods that should be overridden in subclass
defrequest_refresh(self):
"""Request that the bpython display to be refreshed soon."""
ifself.reevaluatingorself.paste_mode:
self.fake_refresh_requested=True
else:
self._request_refresh()
defrequest_reload(self,files_modified:Sequence[str]= ())->None:
"""Request that a ReloadEvent be passed next into process_event"""
ifself.watching_files:
self._request_reload(files_modified)
defschedule_refresh(self,when:float=0)->None:
"""Schedule a ScheduledRefreshRequestEvent for when.
Such a event should interrupt if blocked waiting for keyboard input"""
ifself.reevaluatingorself.paste_mode:
self.fake_refresh_requested=True
else:
self._schedule_refresh(when=when)
def__enter__(self):
self.orig_stdout=sys.stdout
self.orig_stderr=sys.stderr
self.orig_stdin=sys.stdin
sys.stdout=self.stdout
sys.stderr=self.stderr
sys.stdin=self.stdin
self.orig_sigwinch_handler=signal.getsignal(signal.SIGWINCH)
self.orig_sigtstp_handler=signal.getsignal(signal.SIGTSTP)
ifis_main_thread():
# This turns off resize detection and ctrl-z suspension.
signal.signal(signal.SIGWINCH,self.sigwinch_handler)
signal.signal(signal.SIGTSTP,self.sigtstp_handler)
self.orig_meta_path=sys.meta_path
ifself.watcher:
meta_path= []
forfinderinsys.meta_path:
meta_path.append(ImportFinder(self.watcher,finder))
sys.meta_path=meta_path
sitefix.monkeypatch_quit()
returnself
def__exit__(
self,
exc_type:type[BaseException]|None,
exc_val:BaseException|None,
exc_tb:TracebackType|None,
)->Literal[False]:
sys.stdin=self.orig_stdin
sys.stdout=self.orig_stdout
sys.stderr=self.orig_stderr
ifis_main_thread():
# This turns off resize detection and ctrl-z suspension.
signal.signal(signal.SIGWINCH,self.orig_sigwinch_handler)
signal.signal(signal.SIGTSTP,self.orig_sigtstp_handler)
sys.meta_path=self.orig_meta_path
returnFalse
defsigwinch_handler(self,signum:int,frame:FrameType|None)->None:
old_rows,old_columns=self.height,self.width
self.height,self.width=self.get_term_hw()
cursor_dy=self.get_cursor_vertical_diff()
self.scroll_offset-=cursor_dy
logger.info(
"sigwinch! Changed from %r to %r",
(old_rows,old_columns),
(self.height,self.width),
)
logger.info(
"decreasing scroll offset by %d to %d",
cursor_dy,
self.scroll_offset,
)
defsigtstp_handler(self,signum:int,frame:FrameType|None)->None:
self.scroll_offset=len(self.lines_for_display)
self.__exit__(None,None,None)
self.on_suspend()
os.kill(os.getpid(),signal.SIGTSTP)
self.after_suspend()
self.__enter__()
defclean_up_current_line_for_exit(self):
"""Called when trying to exit to prep for final paint"""
logger.debug("unhighlighting paren for exit")
self.cursor_offset=-1
self.unhighlight_paren()
# Event handling
defprocess_event(self,e:events.Event|str)->bool|None:
"""Returns True if shutting down, otherwise returns None.
Mostly mutates state of Repl object"""
logger.debug("processing event %r",e)
ifisinstance(e,events.Event):
returnself.process_control_event(e)
else:
self.last_events.append(e)
self.last_events.pop(0)
self.process_key_event(e)
returnNone
defprocess_control_event(self,e:events.Event)->bool|None:
ifisinstance(e,bpythonevents.ScheduledRefreshRequestEvent):
# This is a scheduled refresh - it's really just a refresh (so nop)
pass
elifisinstance(e,bpythonevents.RefreshRequestEvent):
logger.info("received ASAP refresh request event")
ifself.status_bar.has_focus:
self.status_bar.process_event(e)
else:
assertself.coderunner.code_is_waiting
self.run_code_and_maybe_finish()
elifself.status_bar.has_focus:
self.status_bar.process_event(e)
# handles paste events for both stdin and repl
elifisinstance(e,events.PasteEvent):
ctrl_char=compress_paste_event(e)
ifctrl_charisnotNone:
returnself.process_event(ctrl_char)
withself.in_paste_mode():
# Might not really be a paste, UI might just be lagging
iflen(e.events)<=MAX_EVENTS_POSSIBLY_NOT_PASTEandany(
notis_simple_event(ee)foreeine.events
):
foreeine.events:
ifself.stdin.has_focus:
self.stdin.process_event(ee)
else:
self.process_event(ee)
else:
simple_events=just_simple_events(e.events)
source=preprocess(
"".join(simple_events),self.interp.compile
)
foreeinsource:
ifself.stdin.has_focus:
self.stdin.process_event(ee)
else:
self.process_simple_keypress(ee)
elifisinstance(e,bpythonevents.RunStartupFileEvent):
try:
self.startup()
exceptOSErroraserr:
self.status_bar.message(
_("Executing PYTHONSTARTUP failed: %s")% (err,)
)
elifisinstance(e,bpythonevents.UndoEvent):
self.undo(n=e.n)
elifself.stdin.has_focus:
self.stdin.process_event(e)
elifisinstance(e,events.SigIntEvent):
logger.debug("received sigint event")
self.keyboard_interrupt()
elifisinstance(e,bpythonevents.ReloadEvent):
ifself.watching_files:
self.clear_modules_and_reevaluate()
self.status_bar.message(
_("Reloaded at %s because %s modified.")
% (time.strftime("%X")," & ".join(e.files_modified))
)
else:
raiseValueError("Don't know how to handle event type: %r"%e)
returnNone
defprocess_key_event(self,e:str)->None:
# To find the curtsies name for a keypress, try
# python -m curtsies.events
ifself.status_bar.has_focus:
returnself.status_bar.process_event(e)
ifself.stdin.has_focus:
returnself.stdin.process_event(e)
if (
e
in (
key_dispatch[self.config.right_key]
+key_dispatch[self.config.end_of_line_key]
+ ("<RIGHT>",)
)
andself.config.curtsies_right_arrow_completion
andself.cursor_offset==len(self.current_line)
# if at end of current line and user presses RIGHT (to autocomplete)
):
# then autocomplete
self.current_line+=self.current_suggestion
self.cursor_offset=len(self.current_line)
elifein ("<UP>",)+key_dispatch[self.config.up_one_line_key]:
self.up_one_line()
elifein ("<DOWN>",)+key_dispatch[self.config.down_one_line_key]:
self.down_one_line()
elife=="<Ctrl-d>":
self.on_control_d()
elife=="<Ctrl-o>":
self.operate_and_get_next()
elife=="<Esc+.>":
self.get_last_word()
elifeinkey_dispatch[self.config.reverse_incremental_search_key]:
self.incremental_search(reverse=True)
elifeinkey_dispatch[self.config.incremental_search_key]:
self.incremental_search()
elif (
ein (("<BACKSPACE>",)+key_dispatch[self.config.backspace_key])
andself.incr_search_mode!=SearchMode.NO_SEARCH
):
self.add_to_incremental_search(self,backspace=True)
elifeinself.edit_keys.cut_buffer_edits:
self.readline_kill(e)
elifeinself.edit_keys.simple_edits:
self.cursor_offset,self.current_line=self.edit_keys.call(
e,
cursor_offset=self.cursor_offset,
line=self.current_line,
cut_buffer=self.cut_buffer,
)
elifeinkey_dispatch[self.config.cut_to_buffer_key]:
self.cut_to_buffer()
elifeinkey_dispatch[self.config.reimport_key]:
self.clear_modules_and_reevaluate()
elifeinkey_dispatch[self.config.toggle_file_watch_key]:
self.toggle_file_watch()
elifeinkey_dispatch[self.config.clear_screen_key]:
self.request_paint_to_clear_screen=True
elifeinkey_dispatch[self.config.show_source_key]:
self.show_source()
elifeinkey_dispatch[self.config.help_key]:
self.pager(self.help_text())
elifeinkey_dispatch[self.config.exit_key]:
raiseSystemExit()
elifein ("\n","\r","<PADENTER>","<Ctrl-j>","<Ctrl-m>"):
self.on_enter()
elife=="<TAB>":# tab
self.on_tab()
elife=="<Shift-TAB>":
self.on_tab(back=True)
elifeinkey_dispatch[self.config.undo_key]:# ctrl-r for undo
self.prompt_undo()
elifeinkey_dispatch[self.config.redo_key]:# ctrl-g for redo
self.redo()
elifeinkey_dispatch[self.config.save_key]:# ctrl-s for save
greenlet.greenlet(self.write2file).switch()
elifeinkey_dispatch[self.config.pastebin_key]:# F8 for pastebin
greenlet.greenlet(self.pastebin).switch()
elifeinkey_dispatch[self.config.copy_clipboard_key]:
greenlet.greenlet(self.copy2clipboard).switch()
elifeinkey_dispatch[self.config.external_editor_key]:
self.send_session_to_external_editor()
elifeinkey_dispatch[self.config.edit_config_key]:
greenlet.greenlet(self.edit_config).switch()
# TODO add PAD keys hack as in bpython.cli
elifeinkey_dispatch[self.config.edit_current_block_key]:
self.send_current_block_to_external_editor()
elife=="<ESC>":
self.incr_search_mode=SearchMode.NO_SEARCH
elife=="<SPACE>":
self.add_normal_character(" ")
elifeinCHARACTER_PAIR_MAP.keys():
ifein ["'",'"']:
ifself.is_closing_quote(e):
self.insert_char_pair_end(e)
else:
self.insert_char_pair_start(e)
else:
self.insert_char_pair_start(e)
elifeinCHARACTER_PAIR_MAP.values():
self.insert_char_pair_end(e)
else:
self.add_normal_character(e)
defis_closing_quote(self,e:str)->bool:
char_count=self._current_line.count(e)
return (
char_count%2==0
andcursor_on_closing_char_pair(
self._cursor_offset,self._current_line,e
)[0]
)
definsert_char_pair_start(self,e):
"""Accepts character which is a part of CHARACTER_PAIR_MAP
like brackets and quotes, and appends it to the line with
an appropriate character pair ending. Closing character can only be inserted
when the next character is either a closing character or a space
e.x. if you type "(" (lparen) , this will insert "()"
into the line
"""
self.add_normal_character(e)
ifself.config.brackets_completion:
start_of_line=len(self._current_line)==1
end_of_line=len(self._current_line)==self._cursor_offset
can_lookup_next=len(self._current_line)>self._cursor_offset
next_char= (
None
ifnotcan_lookup_next
elseself._current_line[self._cursor_offset]
)
if (
start_of_line
orend_of_line
or (next_charisnotNoneandnext_charin"})] ")
):
self.add_normal_character(
CHARACTER_PAIR_MAP[e],narrow_search=False
)
self._cursor_offset-=1
definsert_char_pair_end(self,e):
"""Accepts character which is a part of CHARACTER_PAIR_MAP
like brackets and quotes, and checks whether it should be
inserted to the line or overwritten
e.x. if you type ")" (rparen) , and your cursor is directly
above another ")" (rparen) in the cmd, this will just skip
it and move the cursor.
If there is no same character underneath the cursor, the
character will be printed/appended to the line
"""
ifself.config.brackets_completion:
ifself.cursor_offset<len(self._current_line):
ifself._current_line[self.cursor_offset]==e:
self.cursor_offset+=1
return
self.add_normal_character(e)
defget_last_word(self):
previous_word=_last_word(self.rl_history.entry)
word=_last_word(self.rl_history.back())
line=self.current_line
self._set_current_line(
line[:len(line)-len(previous_word)]+word,
reset_rl_history=False,
)
self._set_cursor_offset(
self.cursor_offset-len(previous_word)+len(word),
reset_rl_history=False,
)
defincremental_search(self,reverse=False,include_current=False):
ifself.incr_search_mode==SearchMode.NO_SEARCH:
self.rl_history.enter(self.current_line)
self.incr_search_target=""
else:
ifself.incr_search_target:
line= (
self.rl_history.back(
False,
search=True,
target=self.incr_search_target,
include_current=include_current,
)
ifreverse
elseself.rl_history.forward(
False,
search=True,
target=self.incr_search_target,
include_current=include_current,
)
)
self._set_current_line(
line,reset_rl_history=False,clear_special_mode=False
)
self._set_cursor_offset(
len(self.current_line),
reset_rl_history=False,
clear_special_mode=False,
)
ifreverse:
self.incr_search_mode=SearchMode.REVERSE_INCREMENTAL_SEARCH
else:
self.incr_search_mode=SearchMode.INCREMENTAL_SEARCH
defreadline_kill(self,e):
func=self.edit_keys[e]
self.cursor_offset,self.current_line,cut=func(
self.cursor_offset,self.current_line
)
ifself.last_events[-2]==e:# consecutive kill commands accumulative
iffunc.kills=="ahead":
self.cut_buffer+=cut
eliffunc.kills=="behind":
self.cut_buffer=cut+self.cut_buffer
else:
raiseValueError("cut value other than 'ahead' or 'behind'")
else:
self.cut_buffer=cut
defon_enter(self,new_code=True,reset_rl_history=True):
# so the cursor isn't touching a paren TODO: necessary?
ifnew_code:
self.redo_stack= []
self._set_cursor_offset(-1,update_completion=False)
ifreset_rl_history:
self.rl_history.reset()
self.history.append(self.current_line)
self.all_logical_lines.append((self.current_line,LineType.INPUT))
self.push(self.current_line,insert_into_history=new_code)
defon_tab(self,back=False):
"""Do something on tab key
taken from bpython.cli
Does one of the following:
1) add space to move up to the next %4==0 column
2) complete the current word with characters common to all completions
3) select the first or last match
4) select the next or previous match if already have a match
"""
defonly_whitespace_left_of_cursor():
"""returns true if all characters before cursor are whitespace"""
returnnotself.current_line[:self.cursor_offset].strip()
logger.debug("self.matches_iter.matches: %r",self.matches_iter.matches)
ifonly_whitespace_left_of_cursor():
front_ws=len(self.current_line[:self.cursor_offset])-len(
self.current_line[:self.cursor_offset].lstrip()
)
to_add=4- (front_ws%self.config.tab_length)
forunusedinrange(to_add):
self.add_normal_character(" ")
return
# if cursor on closing character from pair,
# moves cursor behind it on tab
# ? should we leave it here as default?
ifself.config.brackets_completion:
on_closing_char,_=cursor_on_closing_char_pair(
self._cursor_offset,self._current_line
)
ifon_closing_char:
self._cursor_offset+=1
# run complete() if we don't already have matches
iflen(self.matches_iter.matches)==0:
self.list_win_visible=self.complete(tab=True)
# 3. check to see if we can expand the current word
ifself.matches_iter.is_cseq():
cursor_and_line=self.matches_iter.substitute_cseq()
self._cursor_offset,self._current_line=cursor_and_line
# using _current_line so we don't trigger a completion reset
ifnotself.matches_iter.matches:
self.list_win_visible=self.complete()
elifself.matches_iter.matches:
self.current_match= (