forked from bpython/bpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.py
More file actions
1801 lines (1529 loc) · 71.6 KB
/
repl.py
File metadata and controls
1801 lines (1529 loc) · 71.6 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
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import contextlib
import errno
import greenlet
import logging
import os
import re
import signal
import subprocess
import sys
import tempfile
import time
import unicodedata
from six.moves import range
from pygments import format
from bpython._py3compat import PythonLexer
from pygments.formatters import TerminalFormatter
import blessings
import curtsies
from curtsies import FSArray, fmtstr, FmtStr, Termmode
from curtsies import fmtfuncs
from curtsies import events
import bpython
from bpython.repl import Repl as BpythonRepl, SourceNotFound
from bpython.config import (Struct, loadini, default_config_path,
getpreferredencoding)
from bpython.formatter import BPythonFormatter
from bpython import autocomplete
from bpython.translations import _
from bpython._py3compat import py3
from bpython.pager import get_pager_command
from bpython.curtsiesfrontend import replpainter as paint
from bpython.curtsiesfrontend import sitefix
from bpython.curtsiesfrontend.coderunner import CodeRunner, FakeOutput
from bpython.curtsiesfrontend.filewatch import ModuleChangedEventHandler
from bpython.curtsiesfrontend.interaction import StatusBar
from bpython.curtsiesfrontend.manual_readline import edit_keys
from bpython.curtsiesfrontend import events as bpythonevents
from bpython.curtsiesfrontend.parse import parse as bpythonparse
from bpython.curtsiesfrontend.parse import func_for_letter, color_for_letter
from bpython.curtsiesfrontend.preprocess import preprocess
from bpython.curtsiesfrontend.interpreter import (Interp,
code_finished_will_parse)
from curtsies.configfile_keynames import keymap as key_dispatch
if not py3:
import imp
import pkgutil
logger = logging.getLogger(__name__)
INCONSISTENT_HISTORY_MSG = "#<---History inconsistent with output shown--->"
CONTIGUITY_BROKEN_MSG = "#<---History contiguity broken by rewind--->"
HELP_MESSAGE = """
Thanks for using bpython!
See http://bpython-interpreter.org/ for more information and
http://docs.bpython-interpreter.org/ for docs.
Please report issues at https://github.com/bpython/bpython/issues
Features:
Try using undo ({config.undo_key})!
Edit the current line ({config.edit_current_block_key}) or the entire session ({config.external_editor_key}) in an external editor. (currently {config.editor})
Save sessions ({config.save_key}) or post them to pastebins ({config.pastebin_key})! Current pastebin helper: {config.pastebin_helper}
Reload all modules and rerun session ({config.reimport_key}) to test out changes to a module.
Toggle auto-reload mode ({config.toggle_file_watch_key}) to re-execute the current session when a module you've imported is modified.
bpython -i your_script.py runs a file in interactive mode
bpython -t your_script.py pastes the contents of a file into the session
A config file at {config_file_location} customizes keys and behavior of bpython.
You can also set which pastebin helper and which external editor to use.
See {example_config_url} for an example config file.
Press {config.edit_config_key} to edit this config file.
"""
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
# This is needed for is_nop and should be removed once is_nop is fixed.
if py3:
unicode = str
class FakeStdin(object):
"""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, repl, configured_edit_keys=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 = []
if configured_edit_keys:
self.rl_char_sequences = configured_edit_keys
else:
self.rl_char_sequences = edit_keys
def process_event(self, e):
assert self.has_focus
logger.debug('fake input processing event %r', e)
if isinstance(e, events.PasteEvent):
for ee in e.events:
if ee not in self.rl_char_sequences:
self.add_input_character(ee)
elif e in self.rl_char_sequences:
self.cursor_offset, self.current_line = self.rl_char_sequences[e](
self.cursor_offset, self.current_line)
elif isinstance(e, events.SigIntEvent):
self.coderunner.sigint_happened_in_main_greenlet = True
self.has_focus = False
self.current_line = ''
self.cursor_offset = 0
self.repl.run_code_and_maybe_finish()
elif e in ("<Esc+.>",):
self.get_last_word()
elif e in ["<ESC>"]:
pass
elif e in ['<Ctrl-d>']:
if 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='')
else:
pass
elif e in ["\n", "\r", "<Ctrl-j>", "<Ctrl-m>"]:
line = self.current_line
self.repl.send_to_stdin(line + '\n')
self.has_focus = False
self.current_line = ''
self.cursor_offset = 0
self.repl.run_code_and_maybe_finish(for_code=line + '\n')
else: # add normal character
self.add_input_character(e)
if self.current_line.endswith(("\n", "\r")):
pass
else:
self.repl.send_to_stdin(self.current_line)
def add_input_character(self, e):
if e == '<SPACE>':
e = ' '
if e.startswith('<') and e.endswith('>'):
return
assert len(e) == 1, 'added multiple characters: %r' % e
logger.debug('adding normal char %r to current line', e)
c = e if py3 else e.encode('utf8')
self.current_line = (self.current_line[:self.cursor_offset] +
c +
self.current_line[self.cursor_offset:])
self.cursor_offset += 1
def readline(self):
self.has_focus = True
self.repl.send_to_stdin(self.current_line)
value = self.coderunner.request_from_main_greenlet()
self.readline_results.append(value)
return value
def readlines(self, size=-1):
return list(iter(self.readline, ''))
def __iter__(self):
return iter(self.readlines())
def isatty(self):
return True
def flush(self):
"""Flush the internal buffer. This is a no-op. Flushing stdin
doesn't make any sense anyway."""
def write(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
raise IOError(errno.EBADF, "sys.stdin is read-only")
def close(self):
# 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
def encoding(self):
return 'UTF8'
# TODO write a read() method?
class ReevaluateFakeStdin(object):
"""Stdin mock used during reevaluation (undo) so raw_inputs don't have to
be reentered"""
def __init__(self, fakestdin, repl):
self.fakestdin = fakestdin
self.repl = repl
self.readline_results = fakestdin.readline_results[:]
def readline(self):
if self.readline_results:
value = self.readline_results.pop(0)
else:
value = 'no saved input available'
self.repl.send_to_stdout(value)
return value
class ImportLoader(object):
def __init__(self, watcher, loader):
self.watcher = watcher
self.loader = loader
def load_module(self, name):
module = self.loader.load_module(name)
if hasattr(module, '__file__'):
self.watcher.track_module(module.__file__)
return module
if not py3:
# Remember that pkgutil.ImpLoader is an old style class.
class ImpImportLoader(pkgutil.ImpLoader):
def __init__(self, watcher, *args):
self.watcher = watcher
pkgutil.ImpLoader.__init__(self, *args)
def load_module(self, name):
module = pkgutil.ImpLoader.load_module(self, name)
if hasattr(module, '__file__'):
self.watcher.track_module(module.__file__)
return module
class ImportFinder(object):
def __init__(self, watcher, old_meta_path):
self.watcher = watcher
self.old_meta_path = old_meta_path
def find_module(self, fullname, path=None):
for finder in self.old_meta_path:
loader = finder.find_module(fullname, path)
if loader is not None:
return ImportLoader(self.watcher, loader)
if not py3:
# Python 2 does not have the default finders stored in
# sys.meta_path. Use imp to perform the actual importing.
try:
result = imp.find_module(fullname, path)
return ImpImportLoader(self.watcher, fullname, *result)
except ImportError:
return None
return None
class BaseRepl(BpythonRepl):
"""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,
locals_=None,
config=None,
banner=None,
interp=None,
orig_tcattrs=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")
if config is None:
config = Struct()
loadini(config, default_config_path())
# If creating a new interpreter on undo would be unsafe because initial
# state was passed in
self.weak_rewind = bool(locals_ or interp)
if interp is None:
interp = Interp(locals=locals_)
interp.write = self.send_to_stderr
if banner is None:
if config.help_key:
banner = (_('Welcome to bpython!') + ' ' +
_('Press <%s> for help.') % config.help_key)
else:
banner = None
# only one implemented currently
config.autocomplete_mode = autocomplete.SIMPLE
if config.cli_suggestion_width <= 0 or config.cli_suggestion_width > 1:
config.cli_suggestion_width = 1
self.reevaluating = False
self.fake_refresh_requested = False
self.status_bar = StatusBar('',
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")
super(BaseRepl, self).__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
# line currently being edited, without ps1 (usually '>>> ')
self._current_line = ''
# current line of output - stdout and stdin go here
self.current_stdouterr_line = ''
# lines separated whenever logical line
# length goes over what the terminal width
# was at the time of original output
self.display_lines = []
# this is every line that's been executed; it gets smaller on rewind
self.history = []
# 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 = []
# how many times display has been scrolled down
# because there wasn't room to display everything
self.scroll_offset = 0
# from the left, 0 means first char
self._cursor_offset = 0
self.orig_tcattrs = 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_stdout,
fileno=sys.__stdout__.fileno())
self.stderr = FakeOutput(self.coderunner, self.send_to_stderr,
fileno=sys.__stderr__.fileno())
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 bufffer
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 = [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
self.watching_files = False # whether auto reloading active
# 'reverse_incremental_search', 'incremental_search' or None
self.incr_search_mode = None
self.incr_search_target = ''
self.original_modules = set(sys.modules.keys())
self.width = None
self.height = None
self.status_bar.message(banner)
self.watcher = ModuleChangedEventHandler([], self.request_reload)
# The methods below should be overridden, but the default implementations
# below can be used as well.
def get_cursor_vertical_diff(self):
"""Return how the cursor moved due to a window size change"""
return 0
def get_top_usable_line(self):
"""Return the top line of display that can be rewritten"""
return 0
def get_term_hw(self):
"""Returns the current width and height of the display area."""
return (50, 10)
def _schedule_refresh(self, when='now'):
"""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."""
raise NotImplementedError
def _request_reload(self, files_modified=('?',)):
"""Like request_refresh, but for reload requests events."""
raise NotImplementedError
def request_undo(self, n=1):
"""Like request_refresh, but for undo request events."""
raise NotImplementedError
def on_suspend():
"""Will be called on sigtstp.
Do whatever cleanup would allow the user to use other programs."""
raise NotImplementedError
def after_suspend():
"""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."""
raise NotImplementedError
# end methods that should be overridden in subclass
def request_refresh(self):
"""Request that the bpython display to be refreshed soon."""
if self.reevaluating or self.paste_mode:
self.fake_refresh_requested = True
else:
self._request_refresh()
def request_reload(self, files_modified=()):
"""Request that a ReloadEvent be passed next into process_event"""
if self.watching_files:
self._request_reload(files_modified=files_modified)
def schedule_refresh(self, when='now'):
"""Schedule a ScheduledRefreshRequestEvent for when.
Such a event should interrupt if blockied waiting for keyboard input"""
if self.reevaluating or self.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)
signal.signal(signal.SIGWINCH, self.sigwinch_handler)
signal.signal(signal.SIGTSTP, self.sigtstp_handler)
self.orig_meta_path = sys.meta_path
if self.watcher:
sys.meta_path = [ImportFinder(self.watcher, self.orig_meta_path)]
sitefix.monkeypatch_quit()
return self
def __exit__(self, *args):
sys.stdin = self.orig_stdin
sys.stdout = self.orig_stdout
sys.stderr = self.orig_stderr
signal.signal(signal.SIGWINCH, self.orig_sigwinch_handler)
signal.signal(signal.SIGTSTP, self.orig_sigtstp_handler)
sys.meta_path = self.orig_meta_path
def sigwinch_handler(self, signum, frame):
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)
def sigtstp_handler(self, signum, frame):
self.scroll_offset = len(self.lines_for_display)
self.__exit__()
self.on_suspend()
os.kill(os.getpid(), signal.SIGTSTP)
self.after_suspend()
self.__enter__()
def clean_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
def process_event(self, e):
"""Returns True if shutting down, otherwise returns None.
Mostly mutates state of Repl object"""
logger.debug("processing event %r", e)
if isinstance(e, events.Event):
return self.process_control_event(e)
else:
self.last_events.append(e)
self.last_events.pop(0)
return self.process_key_event(e)
def process_control_event(self, e):
if isinstance(e, bpythonevents.ScheduledRefreshRequestEvent):
# This is a scheduled refresh - it's really just a refresh (so nop)
pass
elif isinstance(e, bpythonevents.RefreshRequestEvent):
logger.info('received ASAP refresh request event')
if self.status_bar.has_focus:
self.status_bar.process_event(e)
else:
assert self.coderunner.code_is_waiting
self.run_code_and_maybe_finish()
elif self.status_bar.has_focus:
return self.status_bar.process_event(e)
# handles paste events for both stdin and repl
elif isinstance(e, events.PasteEvent):
ctrl_char = compress_paste_event(e)
if ctrl_char is not None:
return self.process_event(ctrl_char)
with self.in_paste_mode():
# Might not really be a paste, UI might just be lagging
if (len(e.events) <= MAX_EVENTS_POSSIBLY_NOT_PASTE and
any(not is_simple_event(ee) for ee in e.events)):
for ee in e.events:
if self.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)
for ee in source:
if self.stdin.has_focus:
self.stdin.process_event(ee)
else:
self.process_simple_keypress(ee)
elif isinstance(e, bpythonevents.RunStartupFileEvent):
try:
self.startup()
except IOError as e:
self.status_bar.message(
_('Executing PYTHONSTARTUP failed: %s') % (e, ))
elif isinstance(e, bpythonevents.UndoEvent):
self.undo(n=e.n)
elif self.stdin.has_focus:
return self.stdin.process_event(e)
elif isinstance(e, events.SigIntEvent):
logger.debug('received sigint event')
self.keyboard_interrupt()
return
elif isinstance(e, bpythonevents.ReloadEvent):
if self.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:
raise ValueError("Don't know how to handle event type: %r" % e)
def process_key_event(self, e):
# To find the curtsies name for a keypress, try
# python -m curtsies.events
if self.status_bar.has_focus:
return self.status_bar.process_event(e)
if self.stdin.has_focus:
return self.stdin.process_event(e)
if (e in (key_dispatch[self.config.right_key] +
key_dispatch[self.config.end_of_line_key] +
("<RIGHT>",)) and
self.config.curtsies_right_arrow_completion and
self.cursor_offset == len(self.current_line)):
self.current_line += self.current_suggestion
self.cursor_offset = len(self.current_line)
elif e in ("<UP>",) + key_dispatch[self.config.up_one_line_key]:
self.up_one_line()
elif e in ("<DOWN>",) + key_dispatch[self.config.down_one_line_key]:
self.down_one_line()
elif e in ("<Ctrl-d>",):
self.on_control_d()
elif e in ("<Esc+.>",):
self.get_last_word()
elif e in key_dispatch[self.config.reverse_incremental_search_key]:
self.incremental_search(reverse=True)
elif e in key_dispatch[self.config.incremental_search_key]:
self.incremental_search()
elif (e in (("<BACKSPACE>",) +
key_dispatch[self.config.backspace_key]) and
self.incr_search_mode):
self.add_to_incremental_search(self, backspace=True)
elif e in self.edit_keys.cut_buffer_edits:
self.readline_kill(e)
elif e in self.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)
elif e in key_dispatch[self.config.cut_to_buffer_key]:
self.cut_to_buffer()
elif e in key_dispatch[self.config.reimport_key]:
self.clear_modules_and_reevaluate()
elif e in key_dispatch[self.config.toggle_file_watch_key]:
return self.toggle_file_watch()
elif e in key_dispatch[self.config.clear_screen_key]:
self.request_paint_to_clear_screen = True
elif e in key_dispatch[self.config.show_source_key]:
self.show_source()
elif e in key_dispatch[self.config.help_key]:
self.pager(self.help_text())
elif e in key_dispatch[self.config.exit_key]:
raise SystemExit()
elif e in ("\n", "\r", "<PADENTER>", "<Ctrl-j>", "<Ctrl-m>"):
self.on_enter()
elif e == '<TAB>': # tab
self.on_tab()
elif e in ("<Shift-TAB>",):
self.on_tab(back=True)
elif e in key_dispatch[self.config.undo_key]: # ctrl-r for undo
self.prompt_undo()
elif e in key_dispatch[self.config.save_key]: # ctrl-s for save
greenlet.greenlet(self.write2file).switch()
elif e in key_dispatch[self.config.pastebin_key]: # F8 for pastebin
greenlet.greenlet(self.pastebin).switch()
elif e in key_dispatch[self.config.copy_clipboard_key]:
greenlet.greenlet(self.copy2clipboard).switch()
elif e in key_dispatch[self.config.external_editor_key]:
self.send_session_to_external_editor()
elif e in key_dispatch[self.config.edit_config_key]:
greenlet.greenlet(self.edit_config).switch()
# TODO add PAD keys hack as in bpython.cli
elif e in key_dispatch[self.config.edit_current_block_key]:
self.send_current_block_to_external_editor()
elif e in ["<ESC>"]:
self.incr_search_mode = None
elif e in ["<SPACE>"]:
self.add_normal_character(' ')
else:
self.add_normal_character(e)
def get_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)
def incremental_search(self, reverse=False, include_current=False):
if self.incr_search_mode is None:
self.rl_history.enter(self.current_line)
self.incr_search_target = ''
else:
if self.incr_search_target:
line = (self.rl_history.back(
False, search=True,
target=self.incr_search_target,
include_current=include_current)
if reverse else
self.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)
if reverse:
self.incr_search_mode = 'reverse_incremental_search'
else:
self.incr_search_mode = 'incremental_search'
def readline_kill(self, e):
func = self.edit_keys[e]
self.cursor_offset, self.current_line, cut = func(self.cursor_offset,
self.current_line)
if self.last_events[-2] == e: # consecutive kill commands accumulative
if func.kills == 'ahead':
self.cut_buffer += cut
elif func.kills == 'behind':
self.cut_buffer = cut + self.cut_buffer
else:
raise ValueError("cut value other than 'ahead' or 'behind'")
else:
self.cut_buffer = cut
def on_enter(self, insert_into_history=True):
# so the cursor isn't touching a paren TODO: necessary?
self._set_cursor_offset(-1, update_completion=False)
self.history.append(self.current_line)
self.push(self.current_line, insert_into_history=insert_into_history)
def on_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
"""
def only_whitespace_left_of_cursor():
"""returns true if all characters before cursor are whitespace"""
return not self.current_line[:self.cursor_offset].strip()
logger.debug('self.matches_iter.matches:%r', self.matches_iter.matches)
if only_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)
for unused in range(to_add):
self.add_normal_character(' ')
return
# run complete() if we don't already have matches
if len(self.matches_iter.matches) == 0:
self.list_win_visible = self.complete(tab=True)
# 3. check to see if we can expand the current word
if self.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
if not self.matches_iter.matches:
self.list_win_visible = self.complete()
elif self.matches_iter.matches:
self.current_match = (back and self.matches_iter.previous() or
next(self.matches_iter))
cursor_and_line = self.matches_iter.cur_line()
self._cursor_offset, self._current_line = cursor_and_line
# using _current_line so we don't trigger a completion reset
self.list_win_visible = True
def on_control_d(self):
if self.current_line == '':
raise SystemExit()
else:
self.current_line = (self.current_line[:self.cursor_offset] +
self.current_line[(self.cursor_offset + 1):])
def cut_to_buffer(self):
self.cut_buffer = self.current_line[self.cursor_offset:]
self.current_line = self.current_line[:self.cursor_offset]
def yank_from_buffer(self):
pass
def up_one_line(self):
self.rl_history.enter(self.current_line)
self._set_current_line(tabs_to_spaces(self.rl_history.back(
False,
search=self.config.curtsies_right_arrow_completion)),
update_completion=False,
reset_rl_history=False)
self._set_cursor_offset(len(self.current_line), reset_rl_history=False)
def down_one_line(self):
self.rl_history.enter(self.current_line)
self._set_current_line(tabs_to_spaces(self.rl_history.forward(
False,
search=self.config.curtsies_right_arrow_completion)),
update_completion=False,
reset_rl_history=False)
self._set_cursor_offset(len(self.current_line), reset_rl_history=False)
def process_simple_keypress(self, e):
# '\n' needed for pastes
if e in ("<Ctrl-j>", "<Ctrl-m>", "<PADENTER>", "\n", "\r"):
self.on_enter()
while self.fake_refresh_requested:
self.fake_refresh_requested = False
self.process_event(bpythonevents.RefreshRequestEvent())
elif isinstance(e, events.Event):
pass # ignore events
elif e == '<SPACE>':
self.add_normal_character(' ')
else:
self.add_normal_character(e)
def send_current_block_to_external_editor(self, filename=None):
text = self.send_to_external_editor(self.get_current_block())
lines = [line for line in text.split('\n')]
while lines and not lines[-1].split():
lines.pop()
events = '\n'.join(lines + ([''] if len(lines) == 1 else ['', '']))
self.clear_current_block()
with self.in_paste_mode():
for e in events:
self.process_simple_keypress(e)
self.cursor_offset = len(self.current_line)
def send_session_to_external_editor(self, filename=None):
for_editor = EDIT_SESSION_HEADER
for_editor += '\n'.join(line[len(self.ps1):]
if line.startswith(self.ps1) else
line[len(self.ps2):]
if line.startswith(self.ps2) else
'### ' + line
for line in self.getstdout().split('\n'))
text = self.send_to_external_editor(for_editor)
if text == for_editor:
self.status_bar.message(
_('Session not reevaluated because it was not edited'))
return
lines = text.split('\n')
if not lines[-1].strip():
lines.pop() # strip last line if empty
if lines[-1].startswith('### '):
current_line = lines[-1][4:]
else:
current_line = ''
from_editor = [line for line in lines if line[:3] != '###']
if all(not line.strip() for line in from_editor):
self.status_bar.message(
_('Session not reevaluated because saved file was blank'))
return
source = preprocess('\n'.join(from_editor), self.interp.compile)
lines = source.split('\n')
self.history = lines
self.reevaluate(insert_into_history=True)
self.current_line = current_line
self.cursor_offset = len(self.current_line)
self.status_bar.message(_('Session edited and reevaluated'))
def clear_modules_and_reevaluate(self):
if self.watcher:
self.watcher.reset()
cursor, line = self.cursor_offset, self.current_line
for modname in (set(sys.modules.keys()) - self.original_modules):
del sys.modules[modname]
self.reevaluate(insert_into_history=True)
self.cursor_offset, self.current_line = cursor, line
self.status_bar.message(_('Reloaded at %s by user.') %
(time.strftime('%X'), ))
def toggle_file_watch(self):
if self.watcher:
if self.watching_files:
msg = _("Auto-reloading deactivated.")
self.status_bar.message(msg)
self.watcher.deactivate()
self.watching_files = False
else:
msg = _("Auto-reloading active, watching for file changes...")
self.status_bar.message(msg)
self.watching_files = True
self.watcher.activate()
else:
self.status_bar.message(_('Auto-reloading not available because '
'watchdog not installed.'))
# Handler Helpers
def add_normal_character(self, char):
if len(char) > 1 or is_nop(char):
return
if self.incr_search_mode:
self.add_to_incremental_search(char)
else:
self._set_current_line((self.current_line[:self.cursor_offset] +
char +
self.current_line[self.cursor_offset:]),
update_completion=False,
reset_rl_history=False,
clear_special_mode=False)
self.cursor_offset += 1
if (self.config.cli_trim_prompts and
self.current_line.startswith(self.ps1)):
self.current_line = self.current_line[4:]
self.cursor_offset = max(0, self.cursor_offset - 4)
def add_to_incremental_search(self, char=None, backspace=False):
"""Modify the current search term while in incremental search.
The only operations allowed in incremental search mode are
adding characters and backspacing."""
if char is None and not backspace:
raise ValueError("must provide a char or set backspace to True")
if backspace:
self.incr_search_target = self.incr_search_target[:-1]
else:
self.incr_search_target += char
if self.incr_search_mode == 'reverse_incremental_search':
self.incremental_search(reverse=True, include_current=True)
elif self.incr_search_mode == 'incremental_search':
self.incremental_search(include_current=True)
else:
raise ValueError('add_to_incremental_search not in a special mode')
def update_completion(self, tab=False):
"""Update visible docstring and matches and box visibility"""
# Update autocomplete info; self.matches_iter and self.funcprops
# Should be called whenever the completion box might need to appear
# or disappear; whenever current line or cursor offset changes,