-
Notifications
You must be signed in to change notification settings - Fork 1
/
trac.py
executable file
·2161 lines (1891 loc) · 83.4 KB
/
trac.py
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
# trac processor (Mooers' T-64)
# Nat Kuhn (NSK), 7/5/13, v1.0 7/25/13
# 1/1-30/15 NSK with help from BSK, v1.1 implementing meta-sensitive RS with cursor keys
"""
This Trac Processor (i.e., interpreter) implements Calvin N. Mooers Trac T-64
standard, as described in his 1972 document (RR-284):
http://web.archive.org/web/20050205173449/http://tracfoundation.org/t64tech.htm
There are a few deviations from the Mooers standard, including some
improvements:
1. In the Mooers standard, the storage primitives (fb,sb,eb) store a "hardware
address" of the storage block in a named form. I could have slavishly followed
this, putting the file name in a form, but instead, you just supply the file
name as the argument, e.g. #(fb,fact.trac)' gets the forms in a file
"fact.trac" rather than from an address (filename) stored in the form named
fact.trac
2. I stuck some extra spaces in the trace (#(TN)) output for readability
3. There are a couple extra primitives:
3a. #(rm,a,b,default) is a "remainder" function, returns a mod b, and the
default arg for dividing by 0, just as in DV
3b. NI (neutral implied) #(ni,a,b) returns a if the last implied call
("default call") was neutral. This allows scripts to function more like true
primitives. For example:
#(ds,repeat,(#(eq,*2,0,,(#(ni,#)#(cl,*1)#(cl,repeat,*1,#(su,*2,1))))))'
#(ss,repeat,*1,*2)'
#(ds,a,(#(ps,hello)))'
#(repeat,a,5)'
hellohellohellohellohello
##(repeat,a,5)'
#(ps,hello)#(ps,hello)#(ps,hello)#(ps,hello)#(ps,hello)
NI was described to me by Claude Kagan, and I always thought it was part of
the T-64 standard, but it's not in the Mooers document cited above. I have
no idea whether the idea came from Claude, Mooers, or somewhere else.
Presumably not from Mooers, because he used the term "default call" while
Claude used the term "implied call."
4. The "up arrow" (shift-6 on the teletype) was replaced by the caret probably
in the early 1970s. I use the caret in PF, though with this new-fangled
unicode stuff you could probably manage a real up-arrow. :-/
5. Terminal i/o: #(mo,rt,term-mode) allows you to set the terminal mode to
a, b, or l. #(mo,rt) returns the current mode, in lower case. Incidentally,
'rt' is for 'reactive typewriter,' Mooers' term for an interactive terminal.
l line-oriented i/o: uses sys.stdin.readline(), so that you need to
hit <enter> before anything is actually read. Any newline
immediately after a meta character is stripped out.
b basic terminal: implements a rudimentary backspace, which works back
to the last newline, and then echoes deleted characters between
backslashes. Default mode for Windows, has known issues. Based
on code from Ben Kuhn.
a ANSI terminal (e.g., VT-100) mode: default mode for Unix/Mac OS X;
also works on Windows as described under AnsiConsole. Works with
backspace, delete, cursor up/down/left/right, and implements unix
shell-style history using alt-left-arrow and alt-right-arrow
(alt-up and alt-down on Windows). Shift-left- and right-arrow
(alt-left and alt-right on Windows) move to beginning and end of
the current line. I hope someone likes this because it was
painful to implement!
#(mo,rt) returns the terminal mode; in the case of ANSI mode it returns
a,switches,columns,rows; to see those, you need ##(mo,rt).
6. In ansi mode of #5 above, I have implemented an extended version of
read string: #(rs,init string,displacement): it is as if the user has already
entered 'init string' with the cursor placed at 'displacement'. If
'displacement' is positive or 0 is is from the start of the string; if it is
negative or -0 it is from the end, i.e. '-0' positions the cursor at the very
end of the string. This makes scripts like this one, to edit a form, possible:
#(ds,edit,(#(ds,**,##(rs,##(cl,**,<1>,<2>,<3>,<4>,<5>,<6>),-0))#(ss,**,<1>,<2>,<3>,<4>,<5>,<6>)))
#(ss,edit,**)
#(edit,form) then allows you to edit 'form'. Note you must move the cursor to
the end before you hit the meta character, otherwise it will get truncated.
Hitting down-arrow repeatedly is a quick way to move it to the end.
7. I have also added an 'unforgiving' mode: #(mo,e,u) turns it on and
#(mo,e,-u) turns it off. It generates error messages and terminates scripts
for things such as 'form not found', 'too many arguments', 'too few arguments,'
etc. Per Mooers extra arguments should be ignored, missing arguments filled
with null strings (with few exceptions such as the block primitives). There
may be a few scripts that depend on this feature. In any case, it is turned
off as a default.
8. See other extensions to MO in the mode class.
Thanks to Ben Kuhn for getting me Hooked on Pythonics (and for getting me going
on improving RS); to John Levine for consultation, stimulation, and general
interest; and to Andrew Walker for his enthusiasm and support.
Please feel free to report bugs or request features!
Nat Kuhn (NSK, [email protected])
TODO: add #(mo,ar) for arithmetic radix and #(mo,br) for boolean radix
MAYBE: change class names to caps
KNOWN ISSUE: ANSICON handles wrap to new line differently from xterm,
with the result that when you type to the last letter the cursor
advances to the start of the next row. The result winds up being
an extra blank line.
"""
# v1.1 implements new RS with cursor keys, input history, etc.
# v1.0 moves the _Getch code into the main module so it all runs out of a single file
# v0.9 fixes a bug in which seg gaps were identical objects, leading to multiple form
# pointers in a single form. Trace implemented per Mooers
# v0.8 cleans up MO, adds STE error, makes RC functional, traps ^C, implements booleans,
# implements IN. Complete T-64
# v0.7 cleans up error handling, changes "padto" and "exact" for primitive arguments
# to "minargs" and "maxargs". Implements MO
# v0.6 major change is adding endchunk(), eliminating corner cases; partial call
# primitives now work
# Sample scripts [supplied on GitHub, e.g. use #(fb,fact.trac)]:
#(ds,fact,(#(eq,*,0,1,(#(ml,*,#(fact,#(su,*,1)))))))'
#(ss,fact,*)'
# example: #(fact,5)'120
#(ds,tower,(#(eq,*n,0,,(#(tower,#(su,*n,1),*a,*c,*b)#(ps,(
# Move ring from *a to *c))#(tower,#(su,*n,1),*b,*a,*c)))))'
#(ss,tower,*n,*a,*b,*c)'
# example: #(tower,6,here,middle,there)'
#(ds,exp,(#(eq,*n,0,1,(#(eq,#(rm,*n,2),0,(#(sq,#(exp,*a,#(dv,*n,2)))),(#(ml,*a,
#(exp,*a,#(su,*n,1)))))))))'
#(ss,exp,*a,*n)'
#(ds,sq,(#(ml,*x,*x)))'
#(ss,sq,*x)'
# example: #(exp,2,6)'64
from __future__ import print_function # for Python 3 compatibility
import re, sys, os, time
try:
import cPickle as pickle # for SB and FB
except:
import pickle
class form:
"""a 'form' is a 'defined string.' It is stored as a list; each element in
the list is a 'formchunk': either a 'textchunk,' a 'gapchunk,' or an
'endchunk'. The 'form pointer' falls between characters or between a
character and a segment gap. 'pointerchunk' is an int that tells which
chunk the form pointer lies in. A chunk c has a field, c.pointer, that
is -1 if the form pointer is outside the chunk, and >= if inside (i.e.
the chunk is 'active'. exitchunk and enterchunk handle this bookkeeping.
In a textchunk, the pointer can only be to the left of a character; if
it's at the right end of the chunk, it must actually be at the start of
the next chunk. Hence, if the pointer is at the 'far right' of the form,
chunkp points to the terminating endchunk."""
def __init__(self, name, string):
self.name = name
forms[name] = self
if string == '':
self.formlist = [endchunk()]
else:
self.formlist = [textchunk(string), endchunk()]
self.chunkp = 0 #which chunk has the form pointer
self.enterchunk()
def val(self,*args): # for CL
return ''.join(map(lambda x: x.valchunk(*args),self.formlist[self.chunkp:]))
def segment(self,*args): # for SS
self.exitchunk()
for segno in range(len(args)):
segstr = args[segno]
if segstr == '': continue # can't segment out null string
segmented = map( lambda x: x.segmentchunk(segno,segstr), self.formlist )
self.formlist = sum(segmented , [])
chunkp = 0 #per Mooers, the form pointer is moved to the left end
self.enterchunk()
# enterchunk() and exitchunk() are for maintaining the form pointer.
# chunkp is the index in formlist where the formpointer lies. If ch = formlist[chunkp],
# ch.pointer must be >=0 (and = to 0 for a gapchunk and endchunk). ch.pointer should be
# -1 for all the other chunks
def enterchunk(self):
self.formlist[self.chunkp].pointer=0
def exitchunk(self):
self.formlist[self.chunkp].pointer = -1
def curchunk(self):
return self.formlist[self.chunkp]
def atend(self): # returns True if the form pointer is at the right end of the form
return self.curchunk().isend()
def resetPointer(self): # for CR
self.exitchunk()
self.chunkp = 0
self.enterchunk()
def toNextChar(self): # go until a character available or at end
while not ( self.atend() or self.curchunk().charavail() ):
self.exitchunk()
self.chunkp += 1
self.enterchunk()
return self.atend() #true if no character available
# toNextChar, getNextChar, toPrevChar, getPrevChar are used in CC and CN
def getNextChar(self): # only called after toNextChar returns False
(ch, toNext) = self.curchunk().getNextCh()
if toNext: # at end of text chunk, must advance
self.exitchunk()
self.chunkp += 1
self.enterchunk()
return ch
def toPrevChar(self):
# check if inside a text chunk
if self.curchunk().pointer > 0:
return False #OK, character ready before form pointer in the current chunk
while True:
if self.chunkp == 0: return True #at the left end, no next character
if self.formlist[self.chunkp-1].charavail():
return False #positioned after a text chunk
self.exitchunk()
self.chunkp -=1
self.enterchunk()
def getPrevChar(self): # only called after toPrevChar returns False
p = self.curchunk().pointer
assert p >= 0
if p > 0: #inside a text chunk
p -= 1
self.curchunk().pointer = p
return self.curchunk().text[p]
else: #just after a text chunk, at gap or right end
self.exitchunk()
self.chunkp -= 1
self.enterchunk()
c = self.curchunk()
c.pointer = len(c.text) - 1
return c.text[c.pointer]
def validate(self):
"""form.validate() makes sure that a form is valid. The main loop
(psrs(), below) checks each form every time through. I caught some
bugs this way I might not have otherwise."""
activecount = 0 # chunks with c.pointer>=0, all but 1 chunk should have -1.
endcount = 0 # endchunks
previstext = False # if the previous chunk was text (can't have two in a row)
invalid = False
for c in self.formlist:
if c.pointer >= 0: activecount += 1
if isinstance(c, textchunk):
if previstext:
ourOS.print_('Invalid form: consecutive text chunks in', self.name, \
':',c.text,'and previous')
invalid = True
previstext = True
if (c.text) == '':
ourOS.print_('Invalid form: null text chunk in',self.name)
invalid = True
if c.pointer >= len(c.text) or c.pointer <-1:
ourOS.print_('Invalid pointer (',c.pointer,') in text chunk',c.text)
invalid = True
continue
previstext = False #segment gap or end
if c.pointer < -1 or c.pointer > 0:
ourOS.print_('Invalid pointer (',c.pointer,') in gapchunk or endchunk')
invalid = True
if isinstance(c, endchunk): endcount+=1
if activecount != 1:
ourOS.print_('Invalid form:',activecount,'active chunks in',self.name)
invalid = True
if endcount != 1:
ourOS.print_('Invalid form: endcount (',endcount,') is illegal in',self.name)
invalid = True
if not isinstance(self.formlist[len(self.formlist)-1], endchunk):
ourOS.print_('Invalid form: endchunk not at end of',self.name)
invalid = True
if invalid: ourOS.print_('Invalid form',self.name, ': [', *self.formlist)
def __str__(self): # used in PF, so the str functions put in the form pointer as <^>
return ''.join(map(str, self.formlist))
@staticmethod
def find(name): # terminates the primitive if the form not found
if name in forms: return forms[name]
else: form.FNFError(name)
@staticmethod
def callCharacter(name,default): # for CC
f = form.find(name)
if f.toNextChar():
return ( default, True) #at end, force active
return (f.getNextChar(), False)
@staticmethod
def callN(name,numstr,default): # for CN
f = form.find(name)
(n, throwaway, sgn) = mathprim.parsenum(numstr)
if sgn != '-': #either '+' or ''
if f.atend():
return (default, True) #return default only if AT end
if n == 0:
f.toNextChar()
return
chrs = ''
while n > 0:
if f.toNextChar(): return (chrs, False) #null if advancing yields nothing
chrs += f.getNextChar()
n -= 1
return (chrs, False) # got 'em all, pointer remains to the right of last char
else: # sign == '-'...including -0
if f.chunkp == 0 and f.formlist[0].pointer == 0:
return (default, True) #return default only if AT start
if n == 0:
f.toPrevChar()
return
chrs = ''
while n < 0:
if f.toPrevChar(): return (chrs, False) #null if no previous char
chrs = f.getPrevChar() + chrs #"prepend" the next character
n += 1
return (chrs, False) # got 'em all, pointer remains to the left of last char
@staticmethod
def callSeg(name,default): # for CS
f = form.find(name)
if f.atend(): #at right end?
return ( default, True) #at end, force active
(text, skipnext) = f.curchunk().getseg()
f.exitchunk()
f.chunkp += 1
if f.atend():
f.enterchunk()
return (text, False)
if skipnext: f.chunkp += 1 #skip seg gap following text
f.enterchunk()
return (text, False)
@staticmethod
def deleteall(): # for DA
global forms #for some reason, needed here, but not in 'define', above
forms = {}
@staticmethod
def deletedef(*args): # for DD
for name in args:
try:
del forms[name]
except:
if Mode.unforgiving(): form.FNFError(name)
@staticmethod
def initial(name,text,default): # for IN
f = form.find(name)
findp = f.chunkp
val = ''
for chunk in f.formlist[f.chunkp:]:
(idx, string) = chunk.find(text)
val += string
if idx == -1:
findp += 1
continue
break
else:
return ( default, True)
assert idx >= 0
f.exitchunk()
newp = idx + len(text)
if len(f.formlist[findp].text) == newp:
f.chunkp = findp + 1 #form pointer at end of text chunk, move to start of next
f.enterchunk()
else:
f.chunkp = findp
f.enterchunk()
f.formlist[findp].pointer = newp
return ( val, False )
@staticmethod
def FNFError(name): # used in form.find() and also DD, SB
raise primError(False, 'form not found (',name,')')
class formchunk:
"""the content of a form is maintained as a list of 'chunks', each chunk is an
instance of a subclass of formchunk."""
def isend(self):
return False
def segmentchunk(self,gapno,string): # only segment textchunks
return [self]
def charavail(self):
return False
def find(self,text):
return ( -1, '' )
class textchunk(formchunk):
"""this chunk is for a continuous stream of text between segment gaps"""
def __init__(self,text):
self.text = text
self.pointer = -1
def valchunk(self,*args):
return self.text if self.pointer == -1 else self.text[self.pointer:]
def getseg(self):
assert self.pointer >= 0
return (self.text[self.pointer:], True) #advance past following segment gap
def segmentchunk(self,gapno,string):
out = []
for piece in self.text.split(string): #will always execute at least once
if piece != '': out.append(textchunk(piece))
out.append(gapchunk(gapno))
out.pop() # remove final gap
return out
def getNextCh(self):
ch = self.text[self.pointer]
self.pointer += 1
if self.pointer == len(self.text):
self.pointer = -1 # perhaps not necessary
return (ch, True) # move form pointer to next chunk
else:
return (ch, False)
def charavail(self):
return True #by definition, pointer is not at end
def find(self,findstr):
start = self.pointer if self.pointer >= 0 else 0
find = -1 if findstr == '' else self.text.find(findstr, start)
return ( find, self.text[start:] if find < 0 else self.text[start:find] )
def __str__(self):
return self.text if self.pointer == -1 \
else self.text[0:self.pointer] + '<^>' + self.text[self.pointer:]
class gapchunk(formchunk):
"""This chunk represents a segment gap"""
def __init__(self,gapno):
self.gapno = gapno
self.pointer = -1
def valchunk(self,*args):
return args[self.gapno] if self.gapno<len(args) else ''
def getseg(self):
return ('', False) #advance to next chunk, not past it
def __str__(self):
#oops, trac segment gaps are 1-based, not 0-based!
return ('<^>' if self.pointer == 0 else '') + '<'+str(self.gapno+1)+'>'
class endchunk(formchunk):
"""this chunk needs to go at the end of every form; when the form pointer
is at the end (right-hand end) of a form, chunkp points to this chunk.
Many corner cases are eliminated by having it."""
def __init__(self):
self.pointer = -1
def isend(self):
return True
def valchunk(self, *args):
return '' # value for CL
def getseg(self): #value for CS--should never happen
assert False
def __str__(self):
return '<^>' if self.pointer == 0 else ''
class TheOS:
"""OS-dependent stuff goes here.
The code for getraw() comes from:
http://code.activestate.com/recipes/134892/
and screen-polling code for the future can be found at:
http://stackoverflow.com/questions/27750135/
"""
@staticmethod
def whichOS():
"""note that this method is fixed at compile time; for a runtime-
based method, or for the origin of this code, see:
http://stackoverflow.com/questions/4553129/when-to-use-os-name-sys-platform-or-platform-system
"""
if os.name == 'nt':
return WindowsOS()
elif os.name == 'posix':
if sys.platform == 'cygwin':
return CygwinOS()
else:
return PosixOS()
else:
print('Unrecognized OS:',os.name)
return UnknownOS()
def print_(self,*args,**kwargs):
print(*args,**kwargs)
return
def getscrsize(self):
return None
class WindowsOS(TheOS):
def __init__(self):
aw = self.getsizeenv()
self.ansiwidth = aw[1] if aw else None
def getraw(self):
import msvcrt
return msvcrt.getch()
def defaultterm(self):
return 'b'
def rsctrl(self, inp, code):
if code == 8:
return AnsiConsole.BS
if code == 127: # TODO check this
return AnsiConsole.DEL
if code == 224: # alpha
ch = tc.inkey()
if ch == 'H': #up arrow
inp.rowup()
elif ch == 'P': #down arrow
inp.rowdown()
elif ch == 'K': #left arrow
inp.charleft()
elif ch == 'M': #right arrow
inp.charright()
elif ch == 'S': #right arrow
return AnsiConsole.DEL # at least for fn-delete on VMWare
else:
tc.bell() #for the alpha, better late than never
tc.inbuf = ch + tc.inbuf # reprocess the character
elif code == 0: # NUL
ch = tc.inkey()
code = ord(ch)
if code == 155: #alt-left arrow
inp.rowleft()
elif code == 157: #alt-right arrow
inp.rowright()
elif code == 152: #alt-up arrow
tc.dohist('b')
elif code == 160: #alt-down arrow
tc.dohist('f')
else:
tc.bell() #for the alpha, better late than never
tc.inbuf = ch + tc.inbuf # reprocess the character
else:
tc.bell()
def getscrsize(self):
# from http://stackoverflow.com/questions/566746/
res=None
try:
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
except:
return None
if res:
import struct
(bufx, bufy, curx, cury, wattr, left, top, right, bottom, \
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
cols = self.ansiwidth if self.ansiwidth else (right - left + 1)
rows = bottom - top + 1
return rows, cols
else:
return None
ANSIre = re.compile('(\d+)x(\d+)\s*\((\d+)x(\d+)\)\Z') #wxh(WxH)
def getsizeenv(self):
e = os.getenv('ANSICON')
if e == None:
return None
else:
m = WindowsOS.ANSIre.match(e)
try:
#for ANSICON, return "buffer width" rather than "screen width"
#because that is where it wraps
return ( int(m.group(4)), int(m.group(1)) ) # H x w
except (AttributeError, ValueError):
raise termError('ANSICON misformatted: ',e)
def newInputString(self,str,point):
return ACInputString(str,point) #for ANSICON
class PosixOS(TheOS):
def getraw(self):
import sys, tty, termios, fcntl, os
fd = sys.stdin.fileno()
old_attr = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_attr)
return ch
def defaultterm(self):
return 'a'
def rsctrl(self, inp, code):
if code == 127:
return AnsiConsole.BS
if code == 27: #ESC
eseq = tc.geteseq()
ch = eseq.pop(0)
if ch == '[':
if eseq[0] == 'A': #up arrow
inp.rowup()
elif eseq[0] == 'B': #down arrow
inp.rowdown()
elif eseq[0] == 'D': #left arrow
inp.charleft()
elif eseq == ['1',';','2','D']: #shift-left arrow
inp.rowleft()
elif eseq == ['1',';','3','D']: #Cygwin alt-left arrow
tc.dohist('b')
elif eseq[0] == 'C': #right arrow
inp.charright()
elif eseq == ['1',';','2','C']: #shift-right arrow
inp.rowright()
elif eseq == ['1',';','3','C']: #Cygwin alt-right arrow
tc.dohist('f')
elif eseq == ['3','~']: #delete
return AnsiConsole.DEL
else:
tc.bell() #unrecognized CSI (=esc-[ sequence)
else: #eseq doesn't start with [
if ch == 'b' or ch == 'f': #alt-left arrow
tc.dohist(ch)
else:
tc.bell() #for the ESC, better late than never
tc.inbuf = ch + tc.inbuf # reprocess the character
def getscrsize(self):
# from http://stackoverflow.com/questions/566746/
def ioctl_GWINSZ(fd):
try:
import fcntl, termios, struct, os
cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
except:
return None
return cr
cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = ioctl_GWINSZ(fd)
os.close(fd)
except:
pass
return cr or None
def getsizeenv(self):
a = (os.getenv('LINES'), os.getenv('COLUMNS'))
if a[0] or a[1]:
return a
else:
return None
def newInputString(self,str,point):
return InputString(str,point)
class CygwinOS(PosixOS):
def __init__(self):
# linesep code here
pass
def print_(self,*args,**kwargs):
"""this is a workaround for a weird cygwin xterm bug that \n becomes
just lf at times when combined with getraw
http://stackoverflow.com/questions/28162914/
"""
args = map(lambda x: '\r\n'.join(x.split('\n')), args)
if 'end' in kwargs:
PosixOS.print_(self, *args, **kwargs)
else:
PosixOS.print_(self, *args, end='\r\n', **kwargs)
class UnknownOS(TheOS):
#TODO add getraw method to reset to line-mode
def defaultterm(self):
return 'l'
class Console(object):
def __init__(self, *args):
self.inbuf = ''
self.settype(*args)
def settype(self,*args):
prim.condTMA(args, 1, offset=1)
self.contype = args[0].lower()
def gettype(self):
return self.contype
def inkey(self):
if self.inbuf:
ch = self.inbuf[0]
self.inbuf = self.inbuf[1:]
else:
ch = ourOS.getraw()
code = ord(ch)
if code == 3:
raise KeyboardInterrupt # ^C
if code == 4:
raise tracHalt # ^D
if code == 13:
ch = '\n'
return ch
def readch(self):
ch = self.inkey()
self.printstr(ch)
return ch
def bell(self):
ourOS.print_( chr(7), end='')
return
def printstr(self,text):
ourOS.print_(text, end='')
return
class BasicConsole(Console):
"""This code was contributed by Ben Kuhn, and subsequently modified. It
is for a basic terminal, e.g. the Windows command line, which doesn't
have the vt100/xterm escape sequences
"""
def readstr(self, *args):
"""New, improved readstr function. Rather than using stdin.readline(),
loops on getch(); this allows it to capture the metacharacter
immediately, rather than waiting for a newline. If it receives a
backspace, it types over the previous character, so everything looks
normal. Works fine with copy-paste too.--BSK
1/19/15 NSK: when you backspace past a new line, it goes into 'echoing'
mode where is types back erased characters between backslashes
Known issues:
1. Screws up backspacing when the line is long enough to get soft-
wrapped by the terminal.
2. Doesn't work well when you backspace over a printed-out \ from
the echoing mode.
"""
global rshistory
string = ''
mc = metachar.get()
echoing = False #set to true when we BS past \n
while True:
ch = self.inkey()
code = ord(ch)
if code == 127 or ch == '\b': # backspace (mac or Windows)
if string == '':
self.bell()
continue
# print a space over the character immediately preceding the cursor
# but we can't backspace over newlines
if string[-1] == '\n' and not echoing:
ourOS.print_('\\',end='')
echoing = True
ourOS.print_(string[-1] if echoing else '\b \b',end='')
string = string[:-1]
if string == '' and echoing:
ourOS.print_('\\',end='')
echoing = False
else: #anything else
if echoing:
ourOS.print_('\\',end='')
echoing = False
ourOS.print_(ch, end='')
if ch == mc:
sys.stdout.flush()
rshistory.append( string )
return string
else:
string += ch
class LineConsole(Console):
def inkey(self):
if self.inbuf == '':
self.inbuf = sys.stdin.readline()
if self.inbuf == '': #we've hit EOF
raise tracHalt
ch = self.inbuf[0]
self.inbuf = self.inbuf[1:]
return ch
def readch(self):
return self.inkey()
def readstr(self, *args):
global rshistory
prim.condTMA(args, 0)
string = ''
mc = metachar.get()
while True:
ch = self.inkey()
if ch == mc:
if mc != '\n' and self.inbuf[0] == '\n':
#strip \n immed following meta
self.inbuf = self.inbuf[1:]
rshistory.append( string )
return string
else:
string += ch
ESC = chr(27)
class AnsiConsole(Console):
"""
RS implementation of unix readline features: cursor keys, and entry
history. Up, down, left,right cursor keys are implemented, along with
entry history.
Runs on *nix including OSX, Windows under Cygwin or using Jason Hood's
ANSICON.
For ANSICON, see http://adoxa.altervista.org/ansicon/index.html
Download the full package, use either the x86 (32-bit) or x64 (64-bit).
Double-click on ANSICON, and then enter "python trac.py -mo,rt,a"
(supplying the appropriate paths for the files, if necessary).
Known issue with the Windows Console: when you make the window narrower,
it doesn't wrap the lines at the new width, it just makes a scroll bar. As
a result I just leave the line width at buffer width. If you want a truly
narrower window, use Cygwin.
Shift-left and shift-right go to beginning and end of line (alt-left
and alt-right in Windows ANSICON).
Alt-left and Alt-right go backwards and forwards through history (alt-up
and alt-down in Windows ANSICON).
#(mo,rt,a,switches,columns,rows)
Switches (default is +o+e+l):
The first set of switches has to do with ascertaining the screen size. It
tries whichever of the the following methods are enabled (o and e by
default), in order, and uses the first successful one. If +d is enabled
it tries the other enabled modes and reports any discrepancies--mainly
useful for debugging:
o get screen size from OS (seems to work pretty universally)
t get screen size from polling the terminal using ESC sequences (works
on OS X Terminal.app and not many others; prints garbage chars
in ANSICON)
s get screen size from using 'tput' in subprocesses (supposedly
necessary for cygwin using native Windows Python, but character-
by-character I/O doesn't work under those circumstances anyway
e get screen size from environment variables (does not vary dynamically
as user resizes screen, so a next-to-last resort)
f use fixed screen size, as set by columns, rows; default 80,25. These
arguments can be present and they set the screen size for +f
should it be activated in the future
d report discrepancies from the above methods
The second set of switches has to do with ascertaining the location of
the cursor on the screen, mainly used to for figuring out when up-arrow
would go off top of screen (default is +l):
l get screen location by polling the terminal
v validate screen position and give error if it isn't correct (errors
can be thrown by excessively fast typing, or by bug in ANSICON
on Windows); again mainly for debugging
#(mo,rt) returns a,switches,cols,rows where cols,rows is the actual
reported size of the screen. Note that for all this to print you need
to use ##(mo,rt)
"""
DEFSIZE = (25, 80)
MINROWS = 4
MINCOLS = 10
BS = 8
DEL = 127
def __init__(self, *args):
self.fixedsize = AnsiConsole.DEFSIZE
self.carriagepos = 0
self.sb = SwitchBank('otsefdlv', 'oel')
Console.__init__(self, *args)
def settype(self, type, *args):
prim.condTMA(args, 3, offset=2, atmost=True)
self.contype = type.lower()
if len(args) >= 1:
self.sb.flip(args[0])
if len(args) >= 2:
try:
cols = int(args[1])
rows = int(args[2])
if rows >= AnsiConsole.MINROWS and cols >= AnsiConsole.MINCOLS:
self.fixedsize = (rows, cols)
else:
raise ValueError
except (ValueError, IndexError):
raise primError(False, "invalid screen size")
def gettype(self):
tc.refreshsize()
return self.contype + ',' + self.sb.vals() + ',' + \
str(self.scrsize[1]) + ',' + str(self.scrsize[0])
def adjustcarriage(self,t):
p = t.split('\n')
if len(p) == 1: self.carriagepos += len(p[0])
else: self.carriagepos = len(p[-1])
return
def printstr(self,text):
Console.printstr(self,text)
self.adjustcarriage(text)
return
def refreshsize(self):
self.results = []
self.trysize('o', 'OS', ourOS.getscrsize)
self.trysize('t', 'terminal poll', self.sizepoll)
self.trysize('s', 'subprocess', self.sizeproc)
self.trysize('e', 'environment', ourOS.getsizeenv)
if not self.results: #none so far, go to fixed option
self.sb.switches['f'] = True
self.trysize('f', 'fixed', lambda: self.fixedsize )
(self.scrsize, scrsource) = self.results[0]
if self.sb.switches['d']:
discrep = False
for ( size, source ) in self.results[1:]:
if size == self.scrsize:
continue
ourOS.print_("Screen size discrepancy:",self.scrsize,'from',\
scrsource,"vs",size,'from',source)
discrep = True
if discrep:
self.sb.switches['d'] = False # once is enough
def trysize(self,flag,name,fn):
if self.sb.switches[flag] == False: # this method is disabled
return
if self.sb.switches['d'] == False and self.results: # or we already
return # have a result and aren't interested in discrepancies
size = fn()
if size == None:
self.sb.switches[flag] = False # don't retry if it fails
else:
self.results.append( (size, name) )
def sizepoll(self):
ourOS.print_(ESC + '[1 8t', end='')
return self.getcoords('t','8',';')
def sizeproc(self):
try:
import subprocess
proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
output=proc.communicate(input=None)
cols=int(output[0])
proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
output=proc.communicate(input=None)
rows=int(output[0])
return (rows,cols)
except:
return None
def getcoords(self, term, *args):
"""this is a utility function to input the results of device-polling
escape sequences.
If it takes > 50 msec to get to ESC, we conclude that device-polling
is not working."""
time0 = time.time()
while True:
ch = ourOS.getraw()
if (time.time() - time0) <= 0.05:
if ch == ESC: break
self.inbuf += ch
else:
self.inbuf += ch
return None