FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
bpython/bpython/cli.py at wizard · ata2001/bpython · GitHub
ata2001
/
bpython
Public
forked from
bpython/bpython
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
bpython
/
bpython
/
cli.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1621 lines (1323 loc) · 49.8 KB
Breadcrumbs
bpython
/
bpython
/
cli.py
Copy path
File metadata and controls
1621 lines (1323 loc) · 49.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#!/usr/bin/env python
#
# The MIT License
#
# Copyright (c) 2008 Bob Farrell
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from
__future__
import
division
,
with_statement
import
os
import
sys
import
curses
import
math
import
re
import
time
import
inspect
import
signal
import
struct
import
termios
import
fcntl
import
unicodedata
import
errno
from
locale
import
LC_ALL
,
getpreferredencoding
,
setlocale
from
types
import
ModuleType
# These are used for syntax hilighting.
from
pygments
import
format
from
pygments
.
formatters
import
TerminalFormatter
from
pygments
.
lexers
import
PythonLexer
from
pygments
.
token
import
Token
from
bpython
.
formatter
import
BPythonFormatter
# This for completion
from
bpython
import
inspection
from
bpython
import
importcompletion
# This for config
from
bpython
.
config
import
Struct
# This for keys
from
bpython
.
keys
import
key_dispatch
# This for the wizard
from
bpython
import
wizard
from
bpython
.
pager
import
page
from
bpython
.
repl
import
Interpreter
,
Repl
import
bpython
.
args
def
log
(
x
):
f
=
open
(
'/tmp/bpython.log'
,
'a'
)
f
.
write
(
'%s
\n
'
%
(
x
,))
py3
=
sys
.
version_info
[
0
]
==
3
stdscr
=
None
def
calculate_screen_lines
(
tokens
,
width
,
cursor
=
0
):
"""Given a stream of tokens and a screen width plus an optional
initial cursor position, return the amount of needed lines on the
screen."""
lines
=
1
pos
=
cursor
for
(
token
,
value
)
in
tokens
:
if
token
is
Token
.
Text
and
value
==
'
\n
'
:
lines
+=
1
else
:
pos
+=
len
(
value
)
lines
+=
pos
//
width
pos
%=
width
return
lines
class
FakeStdin
(
object
):
"""Provide a fake stdin type for things like raw_input() etc."""
def
__init__
(
self
,
interface
):
"""Take the curses Repl on init and assume it provides a get_key method
which, fortunately, it does."""
self
.
encoding
=
getpreferredencoding
()
self
.
interface
=
interface
self
.
buffer
=
list
()
def
__iter__
(
self
):
return
iter
(
self
.
readlines
())
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
isatty
(
self
):
return
True
def
readline
(
self
,
size
=
-
1
):
"""I can't think of any reason why anything other than readline would
be useful in the context of an interactive interpreter so this is the
only one I've done anything with. The others are just there in case
someone does something weird to stop it from blowing up."""
if
not
size
:
return
''
elif
self
.
buffer
:
buffer
=
self
.
buffer
.
pop
(
0
)
else
:
buffer
=
''
curses
.
raw
(
True
)
try
:
while
not
buffer
.
endswith
(
'
\n
'
):
key
=
self
.
interface
.
get_key
()
if
key
in
[
curses
.
erasechar
(),
'KEY_BACKSPACE'
]:
y
,
x
=
self
.
interface
.
scr
.
getyx
()
if
buffer
:
self
.
interface
.
scr
.
delch
(
y
,
x
-
1
)
buffer
=
buffer
[:
-
1
]
continue
elif
key
==
chr
(
4
)
and
not
buffer
:
# C-d
return
''
elif
(
key
!=
'
\n
'
and
(
len
(
key
)
>
1
or
unicodedata
.
category
(
key
)
==
'Cc'
)):
continue
sys
.
stdout
.
write
(
key
)
# Include the \n in the buffer - raw_input() seems to deal with trailing
# linebreaks and will break if it gets an empty string.
buffer
+=
key
finally
:
curses
.
raw
(
False
)
if
size
>
0
:
rest
=
buffer
[
size
:]
if
rest
:
self
.
buffer
.
append
(
rest
)
buffer
=
buffer
[:
size
]
if
py3
:
return
buffer
else
:
return
buffer
.
encode
(
getpreferredencoding
())
def
read
(
self
,
size
=
None
):
if
size
==
0
:
return
''
data
=
list
()
while
size
is
None
or
size
>
0
:
line
=
self
.
readline
(
size
or
-
1
)
if
not
line
:
break
if
size
is
not
None
:
size
-=
len
(
line
)
data
.
append
(
line
)
return
''
.
join
(
data
)
def
readlines
(
self
,
size
=
-
1
):
return
list
(
iter
(
self
.
readline
,
''
))
DO_RESIZE
=
False
# TODO:
#
# Tab completion does not work if not at the end of the line.
#
# Numerous optimisations can be made but it seems to do all the lookup stuff
# fast enough on even my crappy server so I'm not too bothered about that
# at the moment.
#
# The popup window that displays the argspecs and completion suggestions
# needs to be an instance of a ListWin class or something so I can wrap
# the addstr stuff to a higher level.
#
def
DEBUG
(
s
):
"""This shouldn't ever be called in any release of bpython, so
beat me up if you find anything calling it."""
open
(
'/tmp/bpython-debug'
,
'a'
).
write
(
"%s
\n
"
%
(
str
(
s
), ))
def
get_color
(
config
,
name
):
return
colors
[
config
.
color_scheme
[
name
].
lower
()]
def
get_colpair
(
config
,
name
):
return
curses
.
color_pair
(
get_color
(
config
,
name
)
+
1
)
def
make_colors
(
config
):
"""Init all the colours in curses and bang them into a dictionary"""
# blacK, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default:
c
=
{
'k'
:
0
,
'r'
:
1
,
'g'
:
2
,
'y'
:
3
,
'b'
:
4
,
'm'
:
5
,
'c'
:
6
,
'w'
:
7
,
'd'
:
-
1
,
}
for
i
in
range
(
63
):
if
i
>
7
:
j
=
i
//
8
else
:
j
=
c
[
config
.
color_scheme
[
'background'
]]
curses
.
init_pair
(
i
+
1
,
i
%
8
,
j
)
return
c
class
CLIRepl
(
Repl
):
def
__init__
(
self
,
scr
,
interp
,
statusbar
,
config
,
idle
=
None
):
Repl
.
__init__
(
self
,
interp
,
config
)
interp
.
writetb
=
self
.
writetb
self
.
scr
=
scr
self
.
list_win
=
newwin
(
get_colpair
(
config
,
'background'
),
1
,
1
,
1
,
1
)
self
.
cpos
=
0
self
.
do_exit
=
False
self
.
f_string
=
''
self
.
idle
=
idle
self
.
in_hist
=
False
self
.
paste_mode
=
False
self
.
last_key_press
=
time
.
time
()
self
.
s
=
''
self
.
statusbar
=
statusbar
self
.
formatter
=
BPythonFormatter
(
config
.
color_scheme
)
def
addstr
(
self
,
s
):
"""Add a string to the current input line and figure out
where it should go, depending on the cursor position."""
if
not
self
.
cpos
:
self
.
s
+=
s
else
:
l
=
len
(
self
.
s
)
self
.
s
=
self
.
s
[:
l
-
self
.
cpos
]
+
s
+
self
.
s
[
l
-
self
.
cpos
:]
self
.
complete
()
def
atbol
(
self
):
"""Return True or False accordingly if the cursor is at the beginning
of the line (whitespace is ignored). This exists so that p_key() knows
how to handle the tab key being pressed - if there is nothing but white
space before the cursor then process it as a normal tab otherwise
attempt tab completion."""
return
not
self
.
s
.
lstrip
()
def
back
(
self
):
"""Replace the active line with previous line in history and
increment the index to keep track"""
self
.
cpos
=
0
self
.
rl_history
.
enter
(
self
.
s
)
self
.
clear_wrapped_lines
()
self
.
s
=
self
.
rl_history
.
back
()
self
.
print_line
(
self
.
s
,
clr
=
True
)
def
bs
(
self
,
delete_tabs
=
True
):
"""Process a backspace"""
y
,
x
=
self
.
scr
.
getyx
()
if
not
self
.
s
:
return
if
x
==
self
.
ix
and
y
==
self
.
iy
:
return
n
=
1
self
.
clear_wrapped_lines
()
if
not
self
.
cpos
:
# I know the nested if blocks look nasty. :(
if
self
.
atbol
()
and
delete_tabs
:
n
=
len
(
self
.
s
)
%
self
.
config
.
tab_length
if
not
n
:
n
=
self
.
config
.
tab_length
self
.
s
=
self
.
s
[:
-
n
]
else
:
self
.
s
=
self
.
s
[:
-
self
.
cpos
-
1
]
+
self
.
s
[
-
self
.
cpos
:]
self
.
print_line
(
self
.
s
,
clr
=
True
)
return
n
def
bs_word
(
self
):
pos
=
len
(
self
.
s
)
-
self
.
cpos
-
1
# First we delete any space to the left of the cursor.
while
pos
>=
0
and
self
.
s
[
pos
]
==
' '
:
pos
-=
self
.
bs
()
# Then we delete a full word.
while
pos
>=
0
and
self
.
s
[
pos
]
!=
' '
:
pos
-=
self
.
bs
()
def
check
(
self
):
"""Check if paste mode should still be active and, if not, deactivate
it and force syntax highlighting."""
if
(
self
.
paste_mode
and
time
.
time
()
-
self
.
last_key_press
>
self
.
config
.
paste_time
):
self
.
paste_mode
=
False
self
.
print_line
(
self
.
s
)
def
clear_current_line
(
self
):
"""Called when a SyntaxError occured in the interpreter. It is
used to prevent autoindentation from occuring after a
traceback."""
Repl
.
clear_current_line
(
self
)
self
.
s
=
''
def
clear_wrapped_lines
(
self
):
"""Clear the wrapped lines of the current input."""
# curses does not handle this on its own. Sad.
height
,
width
=
self
.
scr
.
getmaxyx
()
max_y
=
min
(
self
.
iy
+
(
self
.
ix
+
len
(
self
.
s
))
//
width
+
1
,
height
)
for
y
in
xrange
(
self
.
iy
+
1
,
max_y
):
self
.
scr
.
move
(
y
,
0
)
self
.
scr
.
clrtoeol
()
def
complete
(
self
,
tab
=
False
):
if
self
.
paste_mode
and
self
.
list_win_visible
:
self
.
scr
.
touchwin
()
if
self
.
paste_mode
:
return
if
self
.
list_win_visible
and
not
self
.
config
.
auto_display_list
:
self
.
scr
.
touchwin
()
self
.
list_win_visible
=
False
return
if
self
.
config
.
auto_display_list
or
tab
:
self
.
list_win_visible
=
Repl
.
complete
(
self
,
tab
)
if
self
.
list_win_visible
:
try
:
self
.
show_list
(
self
.
matches
,
self
.
argspec
)
except
curses
.
error
:
# XXX: This is a massive hack, it will go away when I get
# cusswords into a good enough state that we can start
# using it.
self
.
list_win
.
border
()
self
.
list_win
.
refresh
()
self
.
list_win_visible
=
False
if
not
self
.
list_win_visible
:
self
.
scr
.
redrawwin
()
self
.
scr
.
refresh
()
def
clrtobol
(
self
):
"""Clear from cursor to beginning of line; usual C-u behaviour"""
self
.
clear_wrapped_lines
()
if
not
self
.
cpos
:
self
.
s
=
''
else
:
self
.
s
=
self
.
s
[
-
self
.
cpos
:]
self
.
print_line
(
self
.
s
,
clr
=
True
)
self
.
scr
.
redrawwin
()
self
.
scr
.
refresh
()
def
current_line
(
self
):
"""Return the current line."""
return
self
.
s
def
cut_to_buffer
(
self
):
"""Clear from cursor to end of line, placing into cut buffer"""
self
.
cut_buffer
=
self
.
s
[
-
self
.
cpos
:]
self
.
s
=
self
.
s
[:
-
self
.
cpos
]
self
.
cpos
=
0
self
.
print_line
(
self
.
s
,
clr
=
True
)
self
.
scr
.
redrawwin
()
self
.
scr
.
refresh
()
def
cw
(
self
):
"""Return the current word, i.e. the (incomplete) word directly to the
left of the cursor"""
if
self
.
cpos
:
# I don't know if autocomplete should be disabled if the cursor
# isn't at the end of the line, but that's what this does for now.
return
l
=
len
(
self
.
s
)
if
(
not
self
.
s
or
(
not
self
.
s
[
l
-
1
].
isalnum
()
and
self
.
s
[
l
-
1
]
not
in
(
'.'
,
'_'
))):
return
i
=
1
while
i
<
l
+
1
:
if
not
self
.
s
[
-
i
].
isalnum
()
and
self
.
s
[
-
i
]
not
in
(
'.'
,
'_'
):
break
i
+=
1
return
self
.
s
[
-
i
+
1
:]
def
delete
(
self
):
"""Process a del"""
if
not
self
.
s
:
return
if
self
.
mvc
(
-
1
):
self
.
bs
(
False
)
def
echo
(
self
,
s
,
redraw
=
True
):
"""Parse and echo a formatted string with appropriate attributes. It
uses the formatting method as defined in formatter.py to parse the
srings. It won't update the screen if it's reevaluating the code (as it
does with undo)."""
if
not
py3
and
isinstance
(
s
,
unicode
):
s
=
s
.
encode
(
getpreferredencoding
())
a
=
get_colpair
(
self
.
config
,
'output'
)
if
'
\x01
'
in
s
:
rx
=
re
.
search
(
'
\x01
([A-Za-z])([A-Za-z]?)'
,
s
)
if
rx
:
fg
=
rx
.
groups
()[
0
]
bg
=
rx
.
groups
()[
1
]
col_num
=
self
.
_C
[
fg
.
lower
()]
if
bg
and
bg
!=
'I'
:
col_num
*=
self
.
_C
[
bg
.
lower
()]
a
=
curses
.
color_pair
(
int
(
col_num
)
+
1
)
if
bg
==
'I'
:
a
=
a
|
curses
.
A_REVERSE
s
=
re
.
sub
(
'
\x01
[A-Za-z][A-Za-z]?'
,
''
,
s
)
if
fg
.
isupper
():
a
=
a
|
curses
.
A_BOLD
s
=
s
.
replace
(
'
\x03
'
,
''
)
s
=
s
.
replace
(
'
\x01
'
,
''
)
# Replace NUL bytes, as addstr raises an exception otherwise
s
=
s
.
replace
(
'
\x00
'
,
''
)
self
.
scr
.
addstr
(
s
,
a
)
if
redraw
and
not
self
.
evaluating
:
self
.
scr
.
refresh
()
def
end
(
self
,
refresh
=
True
):
self
.
cpos
=
0
h
,
w
=
gethw
()
y
,
x
=
divmod
(
len
(
self
.
s
)
+
self
.
ix
,
w
)
y
+=
self
.
iy
self
.
scr
.
move
(
y
,
x
)
if
refresh
:
self
.
scr
.
refresh
()
return
True
def
fwd
(
self
):
"""Same as back() but, well, forward"""
self
.
cpos
=
0
self
.
clear_wrapped_lines
()
self
.
rl_history
.
enter
(
self
.
s
)
self
.
s
=
self
.
rl_history
.
forward
()
self
.
print_line
(
self
.
s
,
clr
=
True
)
def
get_key
(
self
):
key
=
''
while
True
:
try
:
key
+=
self
.
scr
.
getkey
()
if
not
py3
:
key
=
key
.
decode
(
getpreferredencoding
())
self
.
scr
.
nodelay
(
False
)
except
UnicodeDecodeError
:
# Yes, that actually kind of sucks, but I don't see another way to get
# input right
self
.
scr
.
nodelay
(
True
)
except
curses
.
error
:
# I'm quite annoyed with the ambiguity of this exception handler. I previously
# caught "curses.error, x" and accessed x.message and checked that it was "no
# input", which seemed a crappy way of doing it. But then I ran it on a
# different computer and the exception seems to have entirely different
# attributes. So let's hope getkey() doesn't raise any other crazy curses
# exceptions. :)
self
.
scr
.
nodelay
(
False
)
# XXX What to do here? Raise an exception?
if
key
:
return
key
else
:
t
=
time
.
time
()
self
.
paste_mode
=
(
t
-
self
.
last_key_press
<=
self
.
config
.
paste_time
)
self
.
last_key_press
=
t
return
key
finally
:
if
self
.
idle
:
self
.
idle
(
self
)
def
get_line
(
self
):
"""Get a line of text and return it
This function initialises an empty string and gets the
curses cursor position on the screen and stores it
for the echo() function to use later (I think).
Then it waits for key presses and passes them to p_key(),
which returns None if Enter is pressed (that means "Return",
idiot)."""
self
.
s
=
''
self
.
rl_history
.
reset
()
self
.
iy
,
self
.
ix
=
self
.
scr
.
getyx
()
if
not
self
.
paste_mode
:
for
_
in
xrange
(
self
.
next_indentation
()):
self
.
p_key
(
'
\t
'
)
self
.
cpos
=
0
while
True
:
key
=
self
.
get_key
()
if
self
.
p_key
(
key
)
is
None
:
return
self
.
s
def
home
(
self
,
refresh
=
True
):
self
.
scr
.
move
(
self
.
iy
,
self
.
ix
)
self
.
cpos
=
len
(
self
.
s
)
if
refresh
:
self
.
scr
.
refresh
()
return
True
def
lf
(
self
):
"""Process a linefeed character; it only needs to check the
cursor position and move appropriately so it doesn't clear
the current line after the cursor."""
if
self
.
cpos
:
for
_
in
range
(
self
.
cpos
):
self
.
mvc
(
-
1
)
# Reprint the line (as there was maybe a highlighted paren in it)
self
.
print_line
(
self
.
s
,
newline
=
True
)
self
.
echo
(
"
\n
"
)
def
mkargspec
(
self
,
topline
,
down
):
"""This figures out what to do with the argspec and puts it nicely into
the list window. It returns the number of lines used to display the
argspec. It's also kind of messy due to it having to call so many
addstr() to get the colouring right, but it seems to be pretty
sturdy."""
r
=
3
fn
=
topline
[
0
]
args
=
topline
[
1
][
0
]
kwargs
=
topline
[
1
][
3
]
_args
=
topline
[
1
][
1
]
_kwargs
=
topline
[
1
][
2
]
is_bound_method
=
topline
[
2
]
in_arg
=
topline
[
3
]
if
py3
:
kwonly
=
topline
[
1
][
4
]
kwonly_defaults
=
topline
[
1
][
5
]
or
dict
()
max_w
=
int
(
self
.
scr
.
getmaxyx
()[
1
]
*
0.6
)
self
.
list_win
.
erase
()
self
.
list_win
.
resize
(
3
,
max_w
)
h
,
w
=
self
.
list_win
.
getmaxyx
()
self
.
list_win
.
addstr
(
'
\n
'
)
self
.
list_win
.
addstr
(
fn
,
get_colpair
(
self
.
config
,
'name'
)
|
curses
.
A_BOLD
)
self
.
list_win
.
addstr
(
': ('
,
get_colpair
(
self
.
config
,
'name'
))
maxh
=
self
.
scr
.
getmaxyx
()[
0
]
if
is_bound_method
and
isinstance
(
in_arg
,
int
):
in_arg
+=
1
punctuation_colpair
=
get_colpair
(
self
.
config
,
'punctuation'
)
for
k
,
i
in
enumerate
(
args
):
y
,
x
=
self
.
list_win
.
getyx
()
ln
=
len
(
str
(
i
))
kw
=
None
if
kwargs
and
k
+
1
>
len
(
args
)
-
len
(
kwargs
):
kw
=
str
(
kwargs
[
k
-
(
len
(
args
)
-
len
(
kwargs
))])
ln
+=
len
(
kw
)
+
1
if
ln
+
x
>=
w
:
ty
=
self
.
list_win
.
getbegyx
()[
0
]
if
not
down
and
ty
>
0
:
h
+=
1
self
.
list_win
.
mvwin
(
ty
-
1
,
1
)
self
.
list_win
.
resize
(
h
,
w
)
elif
down
and
h
+
r
<
maxh
-
ty
:
h
+=
1
self
.
list_win
.
resize
(
h
,
w
)
else
:
break
r
+=
1
self
.
list_win
.
addstr
(
'
\n
\t
'
)
if
str
(
i
)
==
'self'
and
k
==
0
:
color
=
get_colpair
(
self
.
config
,
'name'
)
else
:
color
=
get_colpair
(
self
.
config
,
'token'
)
if
k
==
in_arg
or
i
==
in_arg
:
color
|=
curses
.
A_BOLD
self
.
list_win
.
addstr
(
str
(
i
),
color
)
if
kw
:
self
.
list_win
.
addstr
(
'='
,
punctuation_colpair
)
self
.
list_win
.
addstr
(
kw
,
get_colpair
(
self
.
config
,
'token'
))
if
k
!=
len
(
args
)
-
1
:
self
.
list_win
.
addstr
(
', '
,
punctuation_colpair
)
if
_args
:
if
args
:
self
.
list_win
.
addstr
(
', '
,
punctuation_colpair
)
self
.
list_win
.
addstr
(
'*%s'
%
(
_args
, ),
get_colpair
(
self
.
config
,
'token'
))
if
py3
and
kwonly
:
if
not
_args
:
if
args
:
self
.
list_win
.
addstr
(
', '
,
punctuation_colpair
)
self
.
list_win
.
addstr
(
'*'
,
punctuation_colpair
)
marker
=
object
()
for
arg
in
kwonly
:
self
.
list_win
.
addstr
(
', '
,
punctuation_colpair
)
color
=
get_colpair
(
self
.
config
,
'token'
)
if
arg
==
in_arg
:
color
|=
curses
.
A_BOLD
self
.
list_win
.
addstr
(
arg
,
color
)
default
=
kwonly_defaults
.
get
(
arg
,
marker
)
if
default
is
not
marker
:
self
.
list_win
.
addstr
(
'='
,
punctuation_colpair
)
self
.
list_win
.
addstr
(
default
,
get_colpair
(
self
.
config
,
'token'
))
if
_kwargs
:
if
args
or
_args
or
(
py3
and
kwonly
):
self
.
list_win
.
addstr
(
', '
,
punctuation_colpair
)
self
.
list_win
.
addstr
(
'**%s'
%
(
_kwargs
, ),
get_colpair
(
self
.
config
,
'token'
))
self
.
list_win
.
addstr
(
')'
,
punctuation_colpair
)
return
r
def
mvc
(
self
,
i
,
refresh
=
True
):
"""This method moves the cursor relatively from the current
position, where:
0 == (right) end of current line
length of current line len(self.s) == beginning of current line
and:
current cursor position + i
for positive values of i the cursor will move towards the beginning
of the line, negative values the opposite."""
y
,
x
=
self
.
scr
.
getyx
()
if
self
.
cpos
==
0
and
i
<
0
:
return
False
if
x
==
self
.
ix
and
y
==
self
.
iy
and
i
>=
1
:
return
False
h
,
w
=
gethw
()
if
x
-
i
<
0
:
y
-=
1
x
=
w
if
x
-
i
>=
w
:
y
+=
1
x
=
0
+
i
self
.
cpos
+=
i
self
.
scr
.
move
(
y
,
x
-
i
)
if
refresh
:
self
.
scr
.
refresh
()
return
True
def
p_key
(
self
,
key
):
"""Process a keypress"""
if
key
is
None
:
return
''
config
=
self
.
config
if
key
==
chr
(
8
):
# C-Backspace (on my computer anyway!)
self
.
clrtobol
()
key
=
'
\n
'
# Don't return; let it get handled
if
key
==
chr
(
27
):
return
''
if
key
in
(
chr
(
127
),
'KEY_BACKSPACE'
):
self
.
bs
()
self
.
complete
()
return
''
elif
key
in
key_dispatch
[
config
.
delete_key
]
and
not
self
.
s
:
# Delete on empty line exits
self
.
do_exit
=
True
return
None
elif
key
in
(
'KEY_DC'
, )
+
key_dispatch
[
config
.
delete_key
]:
self
.
delete
()
self
.
complete
()
# Redraw (as there might have been highlighted parens)
self
.
print_line
(
self
.
s
)
return
''
elif
key
in
key_dispatch
[
config
.
undo_key
]:
# C-r
self
.
undo
()
return
''
elif
key
in
(
'KEY_UP'
, )
+
key_dispatch
[
config
.
up_one_line_key
]:
# Cursor Up/C-p
self
.
back
()
return
''
elif
key
in
(
'KEY_DOWN'
, )
+
key_dispatch
[
config
.
down_one_line_key
]:
# Cursor Down/C-n
self
.
fwd
()
return
''
elif
key
in
(
"KEY_LEFT"
,
' ^B'
,
chr
(
2
)):
# Cursor Left or ^B
self
.
mvc
(
1
)
# Redraw (as there might have been highlighted parens)
self
.
print_line
(
self
.
s
)
elif
key
in
(
"KEY_RIGHT"
,
'^F'
,
chr
(
6
)):
# Cursor Right or ^F
self
.
mvc
(
-
1
)
# Redraw (as there might have been highlighted parens)
self
.
print_line
(
self
.
s
)
elif
key
in
(
"KEY_HOME"
,
'^A'
,
chr
(
1
)):
# home or ^A
self
.
home
()
# Redraw (as there might have been highlighted parens)
self
.
print_line
(
self
.
s
)
elif
key
in
(
"KEY_END"
,
'^E'
,
chr
(
5
)):
# end or ^E
self
.
end
()
# Redraw (as there might have been highlighted parens)
self
.
print_line
(
self
.
s
)
elif
key
in
key_dispatch
[
config
.
cut_to_buffer_key
]:
# cut to buffer
self
.
cut_to_buffer
()
return
''
elif
key
in
key_dispatch
[
config
.
yank_from_buffer_key
]:
# yank from buffer
self
.
yank_from_buffer
()
return
''
elif
key
in
key_dispatch
[
config
.
clear_word_key
]:
self
.
bs_word
()
self
.
complete
()
return
''
elif
key
in
key_dispatch
[
config
.
clear_line_key
]:
self
.
clrtobol
()
return
''
elif
key
in
key_dispatch
[
config
.
clear_screen_key
]:
self
.
s_hist
=
[
self
.
s_hist
[
-
1
]]
self
.
highlighted_paren
=
None
self
.
redraw
()
return
''
elif
key
in
key_dispatch
[
config
.
exit_key
]:
if
not
self
.
s
:
self
.
do_exit
=
True
return
None
else
:
return
''
elif
key
in
key_dispatch
[
config
.
save_key
]:
self
.
write2file
()
return
''
elif
key
in
key_dispatch
[
config
.
pastebin_key
]:
self
.
pastebin
()
return
''
elif
key
in
key_dispatch
[
config
.
last_output_key
]:
page
(
self
.
stdout_hist
[
self
.
prev_block_finished
:
-
4
])
return
''
elif
key
in
key_dispatch
[
config
.
show_source_key
]:
try
:
obj
=
self
.
current_func
if
obj
is
None
and
inspection
.
is_eval_safe_name
(
self
.
s
):
obj
=
self
.
get_object
(
self
.
s
)
source
=
inspect
.
getsource
(
obj
)
except
(
AttributeError
,
IOError
,
NameError
,
TypeError
):
self
.
statusbar
.
message
(
"Cannot show source."
)
return
''
else
:
if
config
.
highlight_show_source
:
source
=
format
(
PythonLexer
().
get_tokens
(
source
),
TerminalFormatter
())
page
(
source
)
return
''
elif
key
==
'
\n
'
:
self
.
lf
()
return
None
elif
key
==
'
\t
'
:
return
self
.
tab
()
elif
key
==
'KEY_BTAB'
:
return
self
.
tab
(
back
=
True
)
elif
len
(
key
)
==
1
and
not
unicodedata
.
category
(
key
)
==
'Cc'
:
self
.
addstr
(
key
)
self
.
print_line
(
self
.
s
)
else
:
return
''
return
True
def
print_line
(
self
,
s
,
clr
=
False
,
newline
=
False
):
"""Chuck a line of text through the highlighter, move the cursor
to the beginning of the line and output it to the screen."""
if
not
s
:
clr
=
True
if
self
.
highlighted_paren
is
not
None
:
# Clear previous highlighted paren
self
.
reprint_line
(
*
self
.
highlighted_paren
)
self
.
highlighted_paren
=
None
if
self
.
config
.
syntax
and
(
not
self
.
paste_mode
or
newline
):
o
=
format
(
self
.
tokenize
(
s
,
newline
),
self
.
formatter
)
else
:
o
=
s
self
.
f_string
=
o
self
.
scr
.
move
(
self
.
iy
,
self
.
ix
)
if
clr
:
self
.
scr
.
clrtoeol
()
if
clr
and
not
s
:
self
.
scr
.
refresh
()
if
o
:
for
t
in
o
.
split
(
'
\x04
'
):
self
.
echo
(
t
.
rstrip
(
'
\n
'
))
if
self
.
cpos
:
t
=
self
.
cpos
for
_
in
range
(
self
.
cpos
):
self
.
mvc
(
1
)
self
.
cpos
=
t
def
prompt
(
self
,
more
):
"""Show the appropriate Python prompt"""
if
not
more
:
self
.
echo
(
"
\x01
%s
\x03
>>> "
%
(
self
.
config
.
color_scheme
[
'prompt'
],))
self
.
stdout_hist
+=
'>>> '
self
.
s_hist
.
append
(
'
\x01
%s
\x03
>>>
\x04
'
%
(
self
.
config
.
color_scheme
[
'prompt'
],))
else
:
prompt_more_color
=
self
.
config
.
color_scheme
[
'prompt_more'
]
self
.
echo
(
"
\x01
%s
\x03
... "
%
(
prompt_more_color
, ))
self
.
stdout_hist
+=
'... '
self
.
s_hist
.
append
(
'
\x01
%s
\x03
...
\x04
'
%
(
prompt_more_color
, ))
def
push
(
self
,
s
,
insert_into_history
=
True
):
# curses.raw(True) prevents C-c from causing a SIGINT
curses
.
raw
(
False
)
try
:
return
Repl
.
push
(
self
,
s
,
insert_into_history
)
except
SystemExit
:
# Avoid a traceback on e.g. quit()
self
.
do_exit
=
True
return
False
finally
:
curses
.
raw
(
True
)
def
redraw
(
self
):
"""Redraw the screen."""
self
.
scr
.
erase
()
for
k
,
s
in
enumerate
(
self
.
s_hist
):
if
not
s
:
continue
self
.
iy
,
self
.
ix
=
self
.
scr
.
getyx
()
for
i
in
s
.
split
(
'
\x04
'
):
self
.
echo
(
i
,
redraw
=
False
)
if
k
<
len
(
self
.
s_hist
)
-
1
:
self
.
scr
.
addstr
(
'
\n
'
)
self
.
iy
,
self
.
ix
=
self
.
scr
.
getyx
()
self
.
print_line
(
self
.
s
)
self
.
scr
.
refresh
()
self
.
statusbar
.
refresh
()
def
repl
(
self
):
"""Initialise the repl and jump into the loop. This method also has to
keep a stack of lines entered for the horrible "undo" feature. It also
tracks everything that would normally go to stdout in the normal Python
interpreter so it can quickly write it to stdout on exit after
curses.endwin(), as well as a history of lines entered for using
up/down to go back and forth (which has to be separate to the
evaluation history, which will be truncated when undoing."""
# Use our own helper function because Python's will use real stdin and
# stdout instead of our wrapped
self
.
push
(
'from bpython._internal import _help as help
\n
'
,
False
)
self
.
iy
,
self
.
ix
=
self
.
scr
.
getyx
()
more
=
False
while
not
self
.
do_exit
:
self
.
f_string
=
''
self
.
prompt
(
more
)
try
:
inp
=
self
.
get_line
()
except
KeyboardInterrupt
:
self
.
statusbar
.
message
(
'KeyboardInterrupt'
)
self
.
scr
.
addstr
(
'
\n
'
)
self
.
scr
.
touchwin
()
self
.
scr
.
refresh
()
continue
self
.
scr
.
redrawwin
()
if
self
.
do_exit
:
return
self
.
history
.
append
(
inp
)
self
.
s_hist
[
-
1
]
+=
self
.
f_string
if
py3
:
self
.
stdout_hist
+=
inp
+
'
\n
'
else
:
self
.
stdout_hist
+=
inp
.
encode
(
getpreferredencoding
())
+
'
\n
'
stdout_position
=
len
(
self
.
stdout_hist
)
more
=
self
.
push
(
inp
)
if
not
more
:
self
.
prev_block_finished
=
stdout_position
self
.
s
=
''
def
reprint_line
(
self
,
lineno
,
tokens
):
"""Helper function for paren highlighting: Reprint line at offset
`lineno` in current input buffer."""
if
not
self
.
buffer
or
lineno
==
len
(
self
.
buffer
):
return
real_lineno
=
self
.
iy
height
,
width
=
self
.
scr
.
getmaxyx
()
for
i
in
xrange
(
lineno
,
len
(
self
.
buffer
)):
string
=
self
.
buffer
[
i
]
# 4 = length of prompt
length
=
len
(
string
.
encode
(
getpreferredencoding
()))
+
4
real_lineno
-=
int
(
math
.
ceil
(
length
/
width
))
if
real_lineno
<
0
:
return
self
.
scr
.
move
(
real_lineno
,
4
)
line
=
format
(
tokens
,
BPythonFormatter
(
self
.
config
.
color_scheme
))
for
string
in
line
.
split
(
'
\x04
'
):
self
.
echo
(
string
)
def
resize
(
self
):
"""This method exists simply to keep it straight forward when
initialising a window and resizing it."""
self
.
size
()
self
.
scr
.
erase
()
self
.
scr
.
resize
(
self
.
h
,
self
.
w
)
self
.
scr
.
mvwin
(
self
.
y
,
self
.
x
)
self
.
statusbar
.
resize
(
refresh
=
False
)
self
.
redraw
()
def
show_list
(
self
,
items
,
topline
=
None
,
current_item
=
None
):
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL