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 pathcli.py
More file actions
2084 lines (1705 loc) · 65.4 KB
/
cli.py
File metadata and controls
2084 lines (1705 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
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__importwith_statement
importcodecs
importos
importsys
importcurses
importcode
importtraceback
importre
importtime
importurllib
importrlcompleter
importinspect
importsignal
importstruct
importtermios
importfcntl
importstring
importsocket
importpydoc
importtypes
importunicodedata
fromitertoolsimportchain
fromcStringIOimportStringIO
fromlocaleimportLC_ALL,getpreferredencoding,setlocale
fromoptparseimportOptionParser
fromurlparseimporturljoin
fromxmlrpclibimportServerProxy,ErrorasXMLRPCError
fromConfigParserimportConfigParser,NoSectionError,NoOptionError
# These are used for syntax hilighting.
frompygmentsimportformat
frompygments.lexersimportPythonLexer
frompygments.tokenimportToken
frombpython.formatterimportBPythonFormatter,Parenthesis
# This for import completion
frombpythonimportimportcompletion
frombpythonimport__version__
deflog(x):
f=open('/tmp/bpython.log','a')
f.write('%s\n'% (x,))
orig_stdout=sys.__stdout__
stdscr=None
classStruct(object):
"""Simple class for instantiating objects we can add arbitrary attributes
to and use for various arbitrary things."""
pass
classFakeStdin(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
defreadline(self):
"""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."""
buffer=''
whileTrue:
key=self.interface.get_key()
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
ifkey=='\n':
break
returnbuffer
defread(self,x):
pass
defreadlines(self,x):
pass
OPTS=Struct()
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.
#
defDEBUG(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), ))
defget_color(name):
returncolors[OPTS.color_scheme[name].lower()]
defget_colpair(name):
returncurses.color_pair(get_color(name)+1)
defmake_colors():
"""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,
}
foriinrange(63):
ifi>7:
j=i/8
else:
j=c[OPTS.color_scheme['background']]
curses.init_pair(i+1,i%8,j)
returnc
defnext_token_inside_string(s,inside_string):
"""Given a code string s and an initial state inside_string, return
whether the next token will be inside a string or not."""
fortoken,valueinPythonLexer().get_tokens(s):
iftokenisToken.String:
value=value.lstrip('bBrRuU')
ifvaluein ['"""',"'''",'"',"'"]:
ifnotinside_string:
inside_string=value
elifvalue==inside_string:
inside_string=False
returninside_string
classInterpreter(code.InteractiveInterpreter):
def__init__(self):
"""The syntaxerror callback can be set at any time and will be called
on a caught syntax error. The purpose for this in bpython is so that
the repl can be instantiated after the interpreter (which it
necessarily must be with the current factoring) and then an exception
callback can be added to the Interpeter instance afterwards - more
specifically, this is so that autoindentation does not occur after a
traceback."""
self.syntaxerror_callback=None
# Unfortunately code.InteractiveInterpreter is a classic class, so no super()
code.InteractiveInterpreter.__init__(self)
defshowsyntaxerror(self,filename=None):
"""Override the regular handler, the code's copied and pasted from
code.py, as per showtraceback, but with the syntaxerror callback called
and the text in a pretty colour."""
ifself.syntaxerror_callbackisnotNone:
self.syntaxerror_callback()
type,value,sys.last_traceback=sys.exc_info()
sys.last_type=type
sys.last_value=value
iffilenameandtypeisSyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename,lineno,offset,line)=value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
value=SyntaxError(msg, (filename,lineno,offset,line))
sys.last_value=value
list=traceback.format_exception_only(type,value)
self.writetb(list)
defshowtraceback(self):
"""This needs to override the default traceback thing
so it can put it into a pretty colour and maybe other
stuff, I don't know"""
try:
t,v,tb=sys.exc_info()
sys.last_type=t
sys.last_value=v
sys.last_traceback=tb
tblist=traceback.extract_tb(tb)
deltblist[:1]
l=traceback.format_list(tblist)
ifl:
l.insert(0,"Traceback (most recent call last):\n")
l[len(l):]=traceback.format_exception_only(t,v)
finally:
tblist=tb=None
self.writetb(l)
defwritetb(self,l):
"""This outputs the traceback and should be overridden for anything
fancy."""
map(self.write, ["\x01%s\x03%s"% (OPTS.color_scheme['error'],i)foriinl])
classRepl(object):
"""Implements the necessary guff for a Python-repl-alike interface
The execution of the code entered and all that stuff was taken from the
Python code module, I had to copy it instead of inheriting it, I can't
remember why. The rest of the stuff is basically what makes it fancy.
It reads what you type, passes it to a lexer and highlighter which
returns a formatted string. This then gets passed to echo() which
parses that string and prints to the curses screen in appropriate
colours and/or bold attribute.
The Repl class also keeps two stacks of lines that the user has typed in:
One to be used for the undo feature. I am not happy with the way this
works. The only way I have been able to think of is to keep the code
that's been typed in in memory and re-evaluate it in its entirety for each
"undo" operation. Obviously this means some operations could be extremely
slow. I'm not even by any means certain that this truly represents a
genuine "undo" implementation, but it does seem to be generally pretty
effective.
If anyone has any suggestions for how this could be improved, I'd be happy
to hear them and implement it/accept a patch. I researched a bit into the
idea of keeping the entire Python state in memory, but this really seems
very difficult (I believe it may actually be impossible to work) and has
its own problems too.
The other stack is for keeping a history for pressing the up/down keys
to go back and forth between lines.
"""#TODO: Split the class up a bit so the curses stuff isn't so integrated.
"""
"""
def__init__(self,scr,interp,statusbar=None,idle=None):
"""Initialise the repl with, unfortunately, a curses screen passed to
it. This needs to be split up so the curses crap isn't in here.
interp is a Python code.InteractiveInterpreter instance
The optional 'idle' parameter is a function that the repl call while
it's blocking (waiting for keypresses). This, again, should be in a
different class"""
self.cut_buffer=''
self.buffer= []
self.scr=scr
self.interp=interp
self.match=False
self.rl_hist= []
self.stdout_hist=''
self.s_hist= []
self.history= []
self.h_i=0
self.in_hist=False
self.evaluating=False
self.do_exit=False
self.cpos=0
# Use the interpreter's namespace only for the readline stuff:
self.completer=rlcompleter.Completer(self.interp.locals)
self.completer.attr_matches=self.attr_matches
# Gna, Py 2.6's rlcompleter searches for __call__ inside the
# instance instead of the type, so we monkeypatch to prevent
# side-effects (__getattr__/__getattribute__)
self.completer._callable_postfix=self._callable_postfix
self.statusbar=statusbar
self.list_win=newwin(1,1,1,1)
self.idle=idle
self.f_string=''
self.matches= []
self.argspec=None
self.s=''
self.inside_string=False
self.highlighted_paren=None
self.list_win_visible=False
self._C= {}
sys.stdin=FakeStdin(self)
sys.path.insert(0,'.')
ifnotOPTS.arg_spec:
return
pythonhist=os.path.expanduser('~/.pythonhist')
ifos.path.exists(pythonhist):
withcodecs.open(pythonhist,'r',getpreferredencoding(),
'ignore')ashfile:
self.rl_hist=hfile.readlines()
defclean_object(self,obj):
"""Try to make an object not exhibit side-effects on attribute
lookup. Return the type's magic attributes so they can be reapplied
with restore_object"""
type_=type(obj)
__getattribute__=None
__getattr__=None
# Dark magic:
# If __getattribute__ doesn't exist on the class and __getattr__ does
# then __getattr__ will be called when doing
# getattr(type_, '__getattribute__', None)
# so we need to first remove the __getattr__, then the
# __getattribute__, then look up the attributes and then restore the
# original methods. :-(
# The upshot being that introspecting on an object to display its
# attributes will avoid unwanted side-effects.
iftype_!=types.InstanceType:
__getattr__=getattr(type_,'__getattr__',None)
if__getattr__isnotNone:
try:
setattr(type_,'__getattr__', (lambda_:None))
exceptTypeError:
__getattr__=None
__getattribute__=getattr(type_,'__getattribute__',None)
if__getattribute__isnotNone:
try:
setattr(type_,'__getattribute__',object.__getattribute__)
exceptTypeError:
# XXX: This happens for e.g. built-in types
__getattribute__=None
# /Dark magic
return__getattribute__,__getattr__
defrestore_object(self,obj,attribs):
"""Restore an object's magic methods as returned from clean_object"""
type_=type(obj)
__getattribute__,__getattr__=attribs
# Dark magic:
if__getattribute__isnotNone:
setattr(type_,'__getattribute__',__getattribute__)
if__getattr__isnotNone:
setattr(type_,'__getattr__',__getattr__)
# /Dark magic
defattr_matches(self,text):
"""Taken from rlcompleter.py and bent to my will."""
m=re.match(r"(\w+(\.\w+)*)\.(\w*)",text)
ifnotm:
return []
expr,attr=m.group(1,3)
obj=eval(expr,self.interp.locals)
attribs=self.clean_object(obj)
try:
matches=self.attr_lookup(obj,expr,attr)
finally:
self.restore_object(obj,attribs)
returnmatches
defattr_lookup(self,obj,expr,attr):
"""Second half of original attr_matches method factored out so it can
be wrapped in a safe try/finally block in case anything bad happens to
restore the original __getattribute__ method."""
words=dir(obj)
ifhasattr(obj,'__class__'):
words.append('__class__')
words=words+rlcompleter.get_class_members(obj.__class__)
matches= []
n=len(attr)
forwordinwords:
ifword[:n]==attrandword!="__builtins__":
matches.append("%s.%s"% (expr,word))
returnmatches
def_callable_postfix(self,value,word):
"""rlcompleter's _callable_postfix done right."""
attribs=self.clean_object(value)
try:
ifhasattr(value,'__call__'):
word+='('
finally:
self.restore_object(value,attribs)
returnword
defcw(self):
"""Return the current word, i.e. the (incomplete) word directly to the
left of the cursor"""
ifself.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 (notself.sor
(notself.s[l-1].isalnum()and
self.s[l-1]notin ('.','_'))):
return
i=1
whilei<l+1:
ifnotself.s[-i].isalnum()andself.s[-i]notin ('.','_'):
break
i+=1
returnself.s[-i+1:]
defget_args(self):
"""Check if an unclosed parenthesis exists, then attempt to get the
argspec() for it. On success, update self.argspec and return True,
otherwise set self.argspec to None and return False"""
defgetpydocspec(f,func):
try:
argspec=pydoc.getdoc(f)
exceptNameError:
returnNone
rx=re.compile(r'([a-zA-Z_][a-zA-Z0-9_]*?)\((.*?)\)')
s=rx.search(argspec)
ifsisNone:
returnNone
ifs.groups()[0]!=func:
returnNone
args= [i.strip()foriins.groups()[1].split(',')]
return [func, (args,None,None,None)]
defgetargspec(func):
try:
iffuncinself.interp.locals:
f=self.interp.locals[func]
exceptTypeError:
returnNone
else:
try:
f=eval(func,self.interp.locals)
exceptException:
# Same deal with the exceptions :(
returnNone
try:
ifinspect.isclass(f):
argspec=inspect.getargspec(f.__init__)
else:
argspec=inspect.getargspec(f)
self.argspec= [func,argspec]
returnTrue
except (NameError,TypeError,KeyError):
t=getpydocspec(f,func)
iftisNone:
returnNone
self.argspec=t
returnTrue
exceptAttributeError:
# This happens if no __init__ is found
returnNone
ifnotOPTS.arg_spec:
returnFalse
stack= ['']
try:
for (token,value)inPythonLexer().get_tokens(self.s):
iftokenisToken.Punctuation:
ifvalue=='(':
stack.append('')
elifvalue==')':
stack.pop()
elif (tokenisToken.NameortokeninToken.Name.subtypesor
tokenisToken.Operatirandvalue=='.'):
stack[-1]+=value
else:
stack[-1]=''
func=stack.pop()orstack.pop()
exceptIndexError:
returnFalse
returngetargspec(func)
defcomplete(self,tab=False):
"""Wrap the _complete method to determine the visibility of list_win
since there can be several reasons why it won't be displayed; this
makes it more manageable."""
ifself.list_win_visibleandnotOPTS.auto_display_list:
self.scr.touchwin()
self.list_win_visible=False
return
ifOPTS.auto_display_listortab:
self.list_win_visible=self._complete(tab)
return
def_complete(self,unused_tab=False):
"""Construct a full list of possible completions and construct and
display them in a window. Also check if there's an available argspec
(via the inspect module) and bang that on top of the completions too.
The return value is whether the list_win is visible or not."""
ifnotself.get_args():
self.argspec=None
cw=self.cw()
ifnot (cworself.argspec):
self.scr.redrawwin()
self.scr.refresh()
returnFalse
ifnotcw:
self.matches= []
# Check for import completion
e=False
matches=importcompletion.complete(self.s,cw)
ifmatchesisNone:
self.scr.redrawwin()
returnFalse
ifnotmatches:
# Nope, no import, continue with normal completion
try:
self.completer.complete(cw,0)
exceptException:
# This sucks, but it's either that or list all the exceptions that could
# possibly be raised here, so if anyone wants to do that, feel free to send me
# a patch. XXX: Make sure you raise here if you're debugging the completion
# stuff !
e=True
else:
matches=self.completer.matches
ifeornotmatches:
self.matches= []
ifnotself.argspec:
self.scr.redrawwin()
returnFalse
ifnoteandmatches:
# remove duplicates and restore order
self.matches=sorted(set(matches))
iflen(self.matches)==1andnotOPTS.auto_display_list:
self.list_win_visible=True
self.tab()
returnFalse
self.show_list(self.matches,self.argspec)
returnTrue
defshow_list(self,items,topline=None):
shared=Struct()
shared.cols=0
shared.rows=0
shared.wl=0
y,x=self.scr.getyx()
h,w=self.scr.getmaxyx()
down= (y<h/2)
ifdown:
max_h=h-y
else:
max_h=y+1
max_w=int(w*0.8)
self.list_win.erase()
ifitemsand'.'initems[0]:
items= [x.rsplit('.')[-1]forxinitems]
iftopline:
height_offset=self.mkargspec(topline,down)+1
else:
height_offset=0
deflsize():
wl=max(len(i)foriinv_items)+1
ifnotwl:
wl=1
cols= ((max_w-2)/wl)or1
rows=len(v_items)/cols
ifcols*rows<len(v_items):
rows+=1
ifrows+2>=max_h:
rows=max_h-2
returnFalse
shared.rows=rows
shared.cols=cols
shared.wl=wl
returnTrue
ifitems:
# visible items (we'll append until we can't fit any more in)
v_items= [items[0][:max_w-3]]
lsize()
else:
v_items= []
foriinitems[1:]:
v_items.append(i[:max_w-3])
ifnotlsize():
delv_items[-1]
v_items[-1]='...'
break
rows=shared.rows
ifrows+height_offset<max_h:
rows+=height_offset
display_rows=rows
else:
display_rows=rows+height_offset
cols=shared.cols
wl=shared.wl
iftoplineandnotv_items:
w=max_w
elifwl+3>max_w:
w=max_w
else:
t= (cols+1)*wl+3
ift>max_w:
t=max_w
w=t
ifheight_offsetanddisplay_rows+5>=max_h:
delv_items[-(cols* (height_offset)):]
self.list_win.resize(rows+2,w)
ifdown:
self.list_win.mvwin(y+1,0)
else:
self.list_win.mvwin(y-rows-2,0)
ifv_items:
self.list_win.addstr('\n ')
forix,iinenumerate(v_items):
padding= (wl-len(i))*' '
self.list_win.addstr(i+padding,get_colpair('main'))
if ((cols==1or (ixandnot (ix+1)%cols))
andix+1<len(v_items)):
self.list_win.addstr('\n ')
# XXX: After all the trouble I had with sizing the list box (I'm not very good
# at that type of thing) I decided to do this bit of tidying up here just to
# make sure there's no unnececessary blank lines, it makes things look nicer.
y=self.list_win.getyx()[0]
self.list_win.resize(y+2,w)
self.statusbar.win.touchwin()
self.statusbar.win.noutrefresh()
self.list_win.attron(get_colpair('main'))
self.list_win.border()
self.scr.touchwin()
self.scr.cursyncup()
self.scr.noutrefresh()
# This looks a little odd, but I can't figure a better way to stick the cursor
# back where it belongs (refreshing the window hides the list_win)
self.scr.move(*self.scr.getyx())
self.list_win.refresh()
defmkargspec(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]
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('name')|curses.A_BOLD)
self.list_win.addstr(': (',get_colpair('name'))
maxh=self.scr.getmaxyx()[0]
fork,iinenumerate(args):
y,x=self.list_win.getyx()
ln=len(str(i))
kw=None
ifkwargsandk+1>len(args)-len(kwargs):
kw=str(kwargs[k- (len(args)-len(kwargs))])
ln+=len(kw)+1
ifln+x>=w:
ty=self.list_win.getbegyx()[0]
ifnotdownandty>0:
h+=1
self.list_win.mvwin(ty-1,1)
self.list_win.resize(h,w)
elifdownandh+r<maxh-ty:
h+=1
self.list_win.resize(h,w)
else:
break
r+=1
self.list_win.addstr('\n\t')
ifstr(i)=='self'andk==0:
color=get_colpair('name')
else:
color=get_colpair('token')
self.list_win.addstr(str(i),color|curses.A_BOLD)
ifkw:
self.list_win.addstr('=',get_colpair('punctuation'))
self.list_win.addstr(kw,get_colpair('token'))
ifk!=len(args)-1:
self.list_win.addstr(', ',get_colpair("punctuation"))
if_args:
ifargs:
self.list_win.addstr(', ',get_colpair('punctuation'))
self.list_win.addstr('*%s'% (_args, ),get_colpair('token'))
if_kwargs:
ifargsor_args:
self.list_win.addstr(', ',get_colpair('punctuation'))
self.list_win.addstr('**%s'% (_kwargs, ),get_colpair('token'))
self.list_win.addstr(')',get_colpair('punctuation'))
returnr
defgetstdout(self):
"""This method returns the 'spoofed' stdout buffer, for writing to a
file or sending to a pastebin or whatever."""
returnself.stdout_hist+'\n'
defformatforfile(self,s):
"""Format the stdout buffer to something suitable for writing to disk,
i.e. without >>> and ... at input lines and with "# OUT: " prepended to
output lines."""
defprocess():
forlineins.split('\n'):
ifline.startswith('>>>')orline.startswith('...'):
yieldline[4:]
elifline.rstrip():
yield"# OUT: %s"% (line,)
return"\n".join(process())
defwrite2file(self):
"""Prompt for a filename and write the current contents of the stdout
buffer to disk."""
fn=self.statusbar.prompt('Save to file: ')
iffn.startswith('~'):
fn=os.path.expanduser(fn)
s=self.formatforfile(self.getstdout())
try:
f=open(fn,'w')
f.write(s)
f.close()
exceptIOError:
self.statusbar.message("Disk write error for file '%s'."% (fn, ))
else:
self.statusbar.message('Saved to %s'% (fn, ))
defpastebin(self):
"""Upload to a pastebin and display the URL in the status bar."""
pasteservice_url='http://paste.pocoo.org/'
pasteservice=ServerProxy(urljoin(pasteservice_url,'/xmlrpc/'))
s=self.getstdout()
self.statusbar.message('Posting data to pastebin...')
try:
paste_id=pasteservice.pastes.newPaste('pycon',s)
exceptXMLRPCError,e:
self.statusbar.message('Upload failed: %s'% (str(e), ) )
return
paste_url=urljoin(pasteservice_url,'/show/%s/'% (paste_id, ))
self.statusbar.message('Pastebin URL: %s'% (paste_url, ),10)
defmake_list(self,items):
"""Compile a list of items. At the moment this simply returns
the list; it's here in case I decide to add any more functionality.
I originally had this method return a list of items where each item
was prepended with a number/letter so the user could choose an option
but it doesn't seem appropriate for readline-like behaviour."""
returnitems
defpush(self,s):
"""Push a line of code onto the buffer so it can process it all
at once when a code block ends"""
s=s.rstrip('\n')
self.buffer.append(s)
try:
encoding=getpreferredencoding()
source='# coding: %s\n'% (encoding, )
source+='\n'.join(self.buffer).encode(encoding)
more=self.interp.runsource(source)
exceptSystemExit:
# Avoid a traceback on e.g. quit()
self.do_exit=True
returnFalse
ifnotmore:
self.buffer= []
returnmore
defundo(self,n=1):
"""Go back in the undo history n steps and call reeavluate()
Note that in the program this is called "Rewind" because I
want it to be clear that this is by no means a true undo
implementation, it is merely a convenience bonus."""
ifnotself.history:
returnNone
iflen(self.history)<n:
n=len(self.history)
self.history=self.history[:-n]
self.reevaluate()
defenter_hist(self):
"""Set flags for entering into the history by pressing up/down"""
ifnotself.in_hist:
self.in_hist=True
self.ts=self.s
defback(self):
"""Replace the active line with previous line in history and
increment the index to keep track"""
ifnotself.rl_hist:
returnNone
self.cpos=0
self.enter_hist()
ifself.h_i<len(self.rl_hist):
self.h_i+=1
self.s=self.rl_hist[-self.h_i].rstrip('\n')
self.print_line(self.s,clr=True)
deffwd(self):
"""Same as back() but, well, forward"""
self.enter_hist()
self.cpos=0
ifself.h_i>1:
self.h_i-=1
self.s=self.rl_hist[-self.h_i].rstrip('\n')
else:
self.h_i=0
self.s=self.ts
self.ts=''
self.in_hist=False
self.print_line(self.s,clr=True)
defredraw(self):
"""Redraw the screen."""
self.scr.erase()
fork,sinenumerate(self.s_hist):
ifnots:
continue
self.iy,self.ix=self.scr.getyx()
foriins.split('\x04'):
self.echo(i,redraw=False)
ifk<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()
defreevaluate(self):
"""Clear the buffer, redraw the screen and re-evaluate the history"""
self.evaluating=True
self.stdout_hist=''
self.f_string=''
self.buffer= []
self.scr.erase()
self.s_hist= []
self.prompt(False)
self.iy,self.ix=self.scr.getyx()
forlineinself.history:
self.stdout_hist+=line.encode(getpreferredencoding())+'\n'
self.print_line(line)
self.s_hist[-1]+=self.f_string
# I decided it was easier to just do this manually
# than to make the print_line and history stuff more flexible.
self.scr.addstr('\n')
more=self.push(line)
self.prompt(more)
self.iy,self.ix=self.scr.getyx()
self.s=''
self.scr.refresh()
self.evaluating=False
#map(self.push, self.history)
#^-- That's how simple this method was at first :(
defprompt(self,more):
"""Show the appropriate Python prompt"""
ifnotmore:
self.echo("\x01%s\x03>>> "% (OPTS.color_scheme['prompt'],))
self.stdout_hist+='>>> '
self.s_hist.append('\x01%s\x03>>>\x04'% (OPTS.color_scheme['prompt'],))
else:
self.echo("\x01%s\x03... "% (OPTS.color_scheme['prompt_more'],))
self.stdout_hist+='... '
self.s_hist.append('\x01%s\x03...\x04'%
(OPTS.color_scheme['prompt_more'],))
defrepl(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."""
# This was a feature request to have the PYTHONSTARTUP
# file executed on startup - I personally don't use this
# feature so please notify me of any breakage.
filename=os.environ.get('PYTHONSTARTUP')
iffilenameandos.path.isfile(filename):
f=open(filename,'r')
code_obj=compile(f.read(),filename,'exec')
f.close()
self.interp.runcode(code_obj)
# Use our own helper function because Python's will use real stdin and
# stdout instead of our wrapped