-
Notifications
You must be signed in to change notification settings - Fork 1
/
teco.py
executable file
·3448 lines (3150 loc) · 116 KB
/
teco.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 python3
"""TECO for Python
Copyright (C) 2006-2023 by Paul Koning
This is an implementation of DEC Standard TECO in Python.
It corresponds to PDP-11/VAX TECO V40, give or take a few details
that don't really carry over.
Environment variables:
TECO_PATH -- where EI looks for files
GT40_POINTSIZE -- display point size, defaults to 12
GT40_WIDTH -- display width, defaults to 80
GT40_HEIGHT -- display height, defaults to 24
GT40_COLOR -- either foreground or foreground,background
Both are either a color name or #rrggbb hex values.
The color names are the wx standard ones, which roughly
match the X standard names. _ may be used instead of
space in color names, e.g., "slate_blue".
Default foreground is green, background is black.
"""
import os
import sys
import re
import time
import traceback
import glob
import warnings
import copy
import atexit
import threading
import tempfile
import errno
try:
import curses
curses.initscr ()
curses.endwin ()
curses.def_shell_mode ()
cursespresent = True
except ImportError:
cursespresent = False
try:
import wx
# Make sure it's real
wx.Frame
wxpresent = True
except (ImportError, AttributeError):
wxpresent = False
# char codes
null = '\000'
ctrlc = '\003'
ctrle = '\005'
bs = '\010'
bell = '\007'
tab = '\011'
lf = '\012'
vt = '\013'
ff = '\014'
cr = '\015'
crlf = cr + lf
ctrls = '\023'
ctrlu = '\025'
ctrlx = '\030'
esc = '\033'
rub = '\177'
eol = lf + vt + ff # all these are TECO end of line (TODO)
# global variables
screen = None
display = None
dsem = None
exiting = False
# Other useful constants
VERSION = 40
# There is no good match for the CPU and OS types. Based on the
# features, PDP-11 makes sense, since this TECO looks like TECO-11.
# The implementation of ^B says we'd like to call it RSX/VMS, but
# that won't work because various code (like TECO.TEC) will use that
# as a hint to construct filenames with RMS format switches in them,
# and those look like Unix directory names, so all hell will break
# loose. The best answer, therefore, is to call it RT-11, which
# has neither directories nor file version numbers nor filename
# switches. RSX/VMS has all of those, and RSTS/E has all except
# versions -- but any of those would give Unix filename handlers
# conniption fits...
CPU = 0 # Pretend to be a PDP-11, that's closest
OS = 7 # OS is Unix, but pretend it's RT-11
# unbuffered input: Python Cookbook V2 section 2.23
try:
from msvcrt import getch
rubchr = '\010'
except ImportError:
rubchr = '\177'
def getch ():
"""Get a character in raw (unechoed, single character) mode.
"""
import tty, termios
fd = sys.stdin.fileno ()
old_settings = termios.tcgetattr (fd)
try:
tty.setraw (fd)
ch = sys.stdin.read (1)
finally:
termios.tcsetattr (fd, termios.TCSADRAIN, old_settings)
return ch
# Enhanced traceback, from Python Cookbook section 8.6, slightly tweaked
maxstrlen = 200
def print_exc_plus ():
'''Print all the usual traceback information, followed by a listing of
all the local variables in each frame.
Variable values are truncated to 200 characters max for readability,
and converted to printable characters in standard TECO fashion.
'''
tb = sys.exc_info ()[2]
while tb.tb_next:
tb = tb.tb_next
stack = [ ]
f = tb.tb_frame
while f:
stack.append (f)
f = f.f_back
stack.reverse ()
endwin ()
traceback.print_exc ()
print("Locals by frame, innermost last")
if stack[0].f_code.co_name == "?":
del stack[0]
for frame in stack:
print()
print("Frame %s in %s at line %s" % (frame.f_code.co_name,
frame.f_code.co_filename,
frame.f_lineno))
for key, value in list(frame.f_locals.items ()):
print("\t%20s = " % key, end=' ')
try:
value = printable (str (value))
if len (value) > maxstrlen:
value = value[:maxstrlen] + "..."
print(value)
except:
print("<ERROR while printing value>")
# Transform a generic binary string to a printable one. Try to
# optimize this because sometimes it is fed big strings.
# tab through cr are printed as is; other control chars are uparrowed
# except for esc of course.
# Taken from Python Cookbook, section 1.18
_printre = re.compile ("[\000-\007\016-\037\177]")
_printdict = { }
for c in range (0o40):
_printdict[chr (c)] = '^' + chr (c + 64)
_printdict[esc] = '$'
_printdict[rub] = "^?"
def _makeprintable (m):
return _printdict[m.group (0)]
def printable(s):
"""Convert the supplied string to a printable string,
by converting all unusual control characters to uparrow
form, and escape to $ sign.
"""
return _printre.sub (_makeprintable, s)
# Error handling
class err (Exception):
'''Base class for TECO errors.
Specific errors are derived from this class; the class name is
the three-letter code for the error, and the class doc string
is the event message string.
'''
def __init__ (self, teco, *a):
self.teco = teco
self.args = tuple (printable (arg) for arg in a)
teco.clearargs ()
def show (self):
endwin ()
detail = self.teco.eh & 3
if detail == 1:
print("?%s" % self.__class__.__name__)
else:
if self.args:
msg = self.__class__.__doc__ % self.args
else:
msg = self.__class__.__doc__
print("?%s %s" % (self.__class__.__name__, msg))
if self.teco.eh & 4:
print(printable (self.teco.failedcommand ()), "?")
class ARG (err): 'Improper Arguments'
class BNI (err): '> not in iteration'
class FER (err): 'File Error'
class FNF (err): 'File not found "%s"'
class ICE (err): 'Illegal ^E Command in Search Argument'
class IEC (err): 'Illegal character "%s" after E'
class IFC (err): 'Illegal character "%s" after F'
class IFN (err): 'Illegal character "%s" in filename'
class IIA (err): 'Illegal insert arg'
class ILL (err): 'Illegal command "%s"'
class ILN (err): 'Illegal number'
class INP (err): 'Input error'
class IPA (err): 'Negative or 0 argument to P'
class IQC (err): 'Illegal " character'
class IQN (err): 'Illegal Q-register name "%s"'
class IRA (err): 'Illegal radix argument to ^R'
class ISA (err): 'Illegal search arg'
class ISS (err): 'Illegal search string'
class IUC (err): 'Illegal character "%s" following ^'
class MAP (err): "Missing '"
class MLA (err): 'Missing Left Angle Bracket'
class MLP (err): 'Missing ('
class MRA (err): 'Missing Right Angle Bracket'
class MRP (err): 'Missing )'
class NAB (err): 'No arg before ^_'
class NAC (err): 'No arg before ,'
class NAE (err): 'No arg before ='
class NAP (err): 'No arg before )'
class NAQ (err): 'No arg before "'
class NAS (err): 'No arg before ;'
class NAU (err): 'No arg before U'
class NCA (err): 'Negative argument to ,'
class NFI (err): 'No file for input'
class NFO (err): 'No file for output'
class NPA (err): 'Negative or 0 argument to P'
class NYA (err): 'Numeric argument with Y'
class NYI (err): 'Not Yet Implemented'
class OFO (err): 'Output file already open'
class OUT (err): 'Output error'
class PES (err): 'Attempt to Pop Empty Stack'
class POP (err): 'Attempt to move Pointer Off Page with "%s"'
class SNI (err): '; not in iteration'
class SRH (err): 'Search failure "%s"'
class TAG (err): 'Missing Tag !%s!'
class UTC (err): 'Unterminated command "%s"'
class UTM (err): 'Unterminated macro'
class XAB (err): 'Execution aborted'
class YCA (err): 'Y command aborted'
# Other exceptions used for misc purposes
class ExitLevel (Exception): pass
class ExitExecution (Exception): pass
# text reformatting for screen display
tabre = re.compile (tab)
_tabadjust = 0
def _untabify (m):
global _curcol, _tabadjust
pos = m.start () + _tabadjust
count = 8 - (pos & 7)
if _curcol > pos:
_curcol += count - 1
_tabadjust += count - 1
return " " * count
def untabify (line, curpos, width):
"""Convert tabs to spaces, and wrap the line as needed into chunks
of the specified width. Returns the list of chunks, and the row
and column corresponding to the supplied curpos. There is always
at least one chunk, which may have an empty string if the supplied
line was empty.
Each chunk is a pair of text and wrap flag. Wrap flag is True
if this chunk of text is wrapped, i.e., it does not end with a
carriage return, and False if it is the end of the line.
Note that a trailing cr and/or lf is stripped from the input line.
"""
global _curcol, _tabadjust
_curcol = curpos
_tabadjust = 0
line = tabre.sub (_untabify, printable (line.rstrip (crlf)))
currow = 0
if True: # todo: truncate vs. wrap mode
lines = [ ]
while len (line) > width:
lines.append ((line[:width], True))
line = line[width:]
if _curcol > width:
currow += 1
_curcol -= width
lines.append ((line, False))
return lines, currow, _curcol
# Property makers
def commonprop (name, doc=None):
"""Define a property that references an attribute of 'teco'
(the common state object for TECO).
"""
def _fget (obj):
return getattr (obj.teco, name)
def _fset (obj, val):
return setattr (obj.teco, name, val)
_fget.__name__ = "get_%s" % name
_fset.__name__ = "set_%s" % name
return property (_fget, _fset, doc=doc)
def bufprop (name, doc=None):
"""Define a property that references an attribute of 'buffer'
(the text buffer object for TECO).
"""
def _fget (obj):
return getattr (obj.buffer, name)
def _fset (obj, val):
return setattr (obj.buffer, name, val)
_fget.__name__ = "get_%s" % name
_fset.__name__ = "set_%s" % name
return property (_fget, _fset, doc=doc)
# Global state handling
class teco (object):
'''This class defines the global state for TECO, i.e., the state
that is independent of the macro level. It also points to state
that is kept in separate classes, such as the buffer, the command
input, and the command level for the interactive level.
'''
def __init__(self):
self.radix = 10
self.ed = 0
self.eh = 0
self.es = 0
if wxpresent:
self.etfixed = 1024 # Display available
elif cursespresent:
self.etfixed = 512 # text terminal "watch" available
else:
self.etfixed = 0 # neither available
self.et = 128 + self.etfixed
self.eu = -1
self.ev = 0
setattr (self, ctrlx, 0) # ^X flag
self.trace = False
self.laststringlen = 0
self.qregs = { }
self.lastsearch = ""
self.lastfilename = ""
self.qstack = [ ]
self.clearargs ()
self.interactive = command_level (self)
self.buffer = buffer (self)
self.cmdhandler = command_handler (self)
self.screenok = False
self.incurses = False
self.watchparams = [ 8, 80, 24, 0, 0, 0, 0, 0 ]
self.curline = 16
buf = bufprop ("text")
dot = bufprop ("dot")
end = bufprop ("end")
def doop (self, c):
"""Process a pending arithmetic operation, if any.
self.arg is left with the current term value.
"""
if self.op:
if self.op in '+-' and self.arg is None:
self.arg = 0
if self.num is None:
raise ILL (self, c)
if self.op == '+':
self.arg += self.num
elif self.op == '-':
self.arg -= self.num
elif self.op == '*':
self.arg *= self.num
elif self.op == '/':
if not self.num:
raise ILL (self, '/')
self.arg //= self.num
elif self.op == '&':
self.arg &= self.num
elif self.op == '#':
self.arg |= self.num
else:
self.arg = self.num
def getterm (self, c):
"""Get the current term, i.e., the innermost expression
part in parentheses.
"""
self.doop (c)
ret = self.arg
self.num = None
self.op = None
self.arg = None
return ret
def leftparen (self):
"""Proces a left parenthesis command, by pushing the current
partial expression state onto the operation stack.
"""
self.opstack.append ((self.arg, self.op))
self.arg = None
self.op = None
def rightparen (self):
"""Process a right parenthesis command, by setting the current
right-hand side to the expression term value, and popping the
operation stack state for the left hand and operation (if any).
"""
if self.opstack:
try:
self.num = self.getterm (')')
except err:
raise NAP (self)
self.arg, self.op = self.opstack.pop ()
else:
raise MLP (self)
def operator (self, c):
"""Process an arithmetic operation character.
"""
if self.num is None:
if c in "+-" and self.arg is None:
self.op = c
return
else:
raise ILL (self, c)
self.doop (c)
self.num = None
self.op = c
def digit (self, c):
"""Process a decimal digit. 8 and 9 generate an error if
the current radix is octal.
"""
if self.num is None:
self.num = 0
n = int (c)
if n >= self.radix:
raise ILN (self)
self.num = self.num * self.radix + n
def getarg (self, c):
"""Get a complete argument, or None if there isn't one.
If there are left parentheses that have not yet been matched,
that is an error. + or - alone are taken to be +1 and -1
respectively.
"""
if self.opstack:
raise MRP (self)
if self.op and self.op in '+-' and self.num is None and self.arg is None:
self.num = 1
return self.getterm (c)
def getoptarg (self, c):
"""Get an optional argument. Unlike getarg, this is legal
while we're in an incomplete expression. This method is used
for commands that do something if given an argument, but return
a value if not. This way, the second case can be used as
an element of an expression.
"""
if self.op and self.op in '+-' and self.num is None and self.arg is None:
self.num = 1
if self.num is None:
return None
return self.getarg (c)
def setval (self, val):
"""Set the command result value into the expression state.
"""
self.num = val
self.clearmods ()
def bitflag (self, name):
"""Process a bit-flag type command, i.e., one that is read by
supplying no argument, set by supplying one, and has its bits
fiddled by two arguments.
"""
n = self.getoptarg (name)
if n is None:
self.setval (getattr (self, name))
else:
if self.arg2 is not None:
n = (getattr (self, name) | n) & (~self.arg2)
if n & 32768:
# Sign extend upper 16 bits
n |= -32768
fixed = getattr (self, name + "fixed", 0)
self.clearargs ()
setattr (self, name, n | fixed)
def numflag (self, name):
"""Process a numeric flag type command, i.e., one that is
read by supplying no argument, and set by supplying the new value.
"""
n = self.getoptarg (name)
if n is None:
self.setval (getattr (self, name))
else:
self.clearargs ()
setattr (self, name, n)
def lineargs(self, c):
"""Process the argument(s) for a command that references lines.
If one argument is present, that is taken as a line count
displacement from dot. If two arguments are present, that is
the start and end of the the range.
"""
m, n = self.arg2, self.getarg (c)
if n is None:
n = 1
if m is None:
if n > 0:
m, n = self.dot, self.buffer.line (n)
else:
m, n = self.buffer.line (n), self.dot
else:
if m < 0 or n > self.end or m > n:
raise POP (self, c)
return (m, n)
def clearmods (self):
"""Clear modifier flags (colon and at sign).
"""
self.colons = 0
self.atmod = False
def clearargs (self):
"""Reinitialize all expression state, as well as modifiers.
"""
self.opstack = [ ]
self.arg = None
self.arg2 = None
self.num = None
self.op = None
self.clearmods ()
def failedcommand (self):
"""Return the last failed interactive command, i.e., the last
command up to the point where execution was aborted.
"""
return self.interactive.failedcommand ()
def lastcommand (self):
"""Return the last interactive command, in full.
"""
return self.interactive.lastcommand ()
def mainloop (self):
"""This is the TECO command loop. It fetches the command string,
handles special immediate action forms, and otherwise executes
the command as supplied. Errors are handled by catching the
TECO error exception, and printing the error information as
controlled by the EH flag.
"""
preverror = False
try:
while True:
if not self.cmdhandler.eifile:
if screen:
y, x = screen.getmaxyx ()
screen.untouchwin ()
screen.move (y - 1, 0)
screen.clrtoeol ()
screen.refresh ()
curses.reset_shell_mode ()
self.incurses = False
self.screenok = False
self.updatedisplay ()
# clear "in startup mode" flag
self.et &= ~128
self.autoverify (self.ev)
sys.stdout.write ("*")
sys.stdout.flush ()
cmdline = self.cmdhandler.teco_cmdstring ()
self.clearargs ()
if cmdline and cmdline[-1] != esc:
# it was an immediate action command -- handle that
cmd = cmdline[0]
if cmd == '*':
try:
q = self.interactive.qreg (cmdline[1])
except err as e:
e.show ()
else:
q.setstr (self.lastcommand ())
continue
elif cmd == '?':
if preverror:
print(printable (self.failedcommand ()))
continue
elif cmd == lf:
cmdline = "lt"
else:
cmdline = "-lt"
try:
preverror = False
self.runcommand (cmdline)
except ExitExecution:
pass
except SystemExit:
endwin ()
enddisplay ()
break
except err as e:
preverror = True
e.show ()
###print_exc_plus () # *** for debug
# Turn off any EI
self.cmdhandler.ei ("")
except:
print_exc_plus ()
except:
print_exc_plus ()
def runcommand (self, s):
"""Execute the specified TECO command string as an interactive
level command.
"""
self.interactive.run (s)
def screentext (self, height, width, curlinenum):
"""Given a screen height and width in characters, and the
line on which we want 'dot' to appear, determine the text that
fits on the screen.
Returns a three-element tuple: lines, row, and column corresponding
to dot.
Lines is a list; each list element is a pair of text and
wrap flag. Wrap flag is True if this chunk of text is wrapped,
i.e., it does not end with a carriage return, and False if
it is the end of the line.
"""
curlinestart = self.buffer.line (0)
curcol = self.dot - curlinestart
line = self.buf[curlinestart:self.buffer.line(1)]
lines, currow, curcol = untabify (line, curcol, width)
n = 1
# First add on lines after the current line, up to the
# window height, if we have that many
while len (lines) < height:
start, end = self.buffer.line (n), self.buffer.line (n + 1)
if start >= self.end:
break
line, i, i = untabify (self.buf[start:end], 0, width)
lines += line
n += 1
# Next, add lines before the current line, until we have
# enough to put the cursor onto the line where we want it,
# but also try to fill the screen
n = 0
while currow < curlinenum or len (lines) < height:
start, end = self.buffer.line (-n - 1), self.buffer.line (-n)
if not end:
break
line, i, i = untabify (self.buf[start:end], 0, width)
lines = line + lines
currow += len (line)
n += 1
# Now trim things, since (a) the topmost line may have wrapped
# so the cursor may be lower than we want it to be, and (b)
# we now probably have more lines than we want at the end
# of the screen.
trim = min (currow - curlinenum, len (lines) - height)
if trim > 0:
lines = lines[trim:]
currow -= trim
if len (lines) > height:
lines = lines[:height]
return lines, currow, curcol
def enable_curses (self):
"""Enable curses (VT100 style screen watch) mode, if available
in this Python installation. This is a NOP if curses is not
available.
"""
global screen
if not cursespresent:
return
if not screen:
atexit.register (endwin)
screen = curses.initscr ()
curses.noecho ()
curses.nonl ()
curses.raw ()
curses.def_prog_mode ()
else:
curses.reset_prog_mode ()
self.incurses = True
self.watchparams[2], self.watchparams[1] = screen.getmaxyx ()
def watch (self):
"""Do a screen watch operation, i.e., update the screen to
reflect the buffer contents around the current dot, in curses mode.
"""
if not cursespresent:
return
self.enable_curses ()
curlinenum = self.curline
width, height = self.watchparams[1], self.watchparams[2]
lines, currow, curcol = self.screentext (height, width, curlinenum)
if currow >= height:
currow = height - 1
if curcol >= width:
curcol = width - 1
for row, line in enumerate (lines):
line, wrap = line
screen.addstr (row, 0, line)
screen.clrtoeol ()
screen.clrtobot ()
if not self.screenok:
screen.clearok (1)
self.screenok = True
screen.move (currow, curcol)
screen.refresh ()
# Interface to the display thread
def startdisplay (self):
"""Start the wxPython display (GT40 emulation, essentially).
This is a NOP if wxPython is not available.
"""
if not display:
atexit.register (enddisplay)
# Release the main thread, allowing it to start the display
dsem.release ()
else:
display.show ()
def updatedisplay (self):
"""Refresh the GT40 style display to reflect the current
buffer state around dot.
"""
if display:
display.show (display.frame.doShow)
def hidedisplay (self):
"""Turn off (hide) the GT40 display.
"""
if display:
display.show (False)
def autoverify (self, flag):
"""Handle automatic verify for the ES and EV flags. The input
is the flag in question.
"""
if flag:
if flag == -1:
flag = 0
ch = flag & 255
if ch:
if ch < 32:
ch = lf
else:
ch = chr (ch)
flag >>= 8
start = self.buffer.line (-flag)
end = self.buffer.line (flag + 1)
sys.stdout.write (printable (self.buf[start:self.dot]))
if ch:
sys.stdout.write (ch)
sys.stdout.write (printable (self.buf[self.dot:end]))
sys.stdout.flush ()
self.screenok = False
# A metaclass to allow non-alphanumeric methods to be defined, which
# is handy when you use method names directly for command character
# processing. Inspired by the Python Cookbook, chapter 20 intro.
def _repchar (m):
return chr (int (m.group (1), 8))
class Anychar (type):
def __new__ (cls, cname, cbases, cdict):
newnames = {}
charre = re.compile ("char([0-7]{3})")
for name in cdict:
newname, cnt = charre.subn (_repchar, name)
if cnt:
fun = cdict[name]
newnames[newname] = fun
cdict.update (newnames)
return super (Anychar, cls).__new__ (cls, cname, cbases, cdict)
class qreg (object):
'''Queue register object. Stores text and numeric parts, with
methods to access each part.
'''
def __init__ (self):
self.num = 0
self.text = ""
def getnum (self):
return self.num
def setnum (self, val):
self.num = val
def getstr (self):
return self.text
def setstr (self, val):
self.text = val
def appendstr (self, val):
self.text += val
# Atexit handlers. These are guarded so they can be called even
# if the corresponding module isn't present.
def endwin ():
"""Close down curses mode.
"""
global screen
if screen:
try:
curses.endwin ()
except:
pass
screen = None
def enddisplay ():
"""Stop wxPython display.
"""
global display
if display:
display.stop ()
if wxpresent:
# Display parameters can be customized but have defaults
pointsize = int (os.environ.get ("GT40_POINTSIZE", 12))
width = int (os.environ.get ("GT40_WIDTH", 80))
height = int (os.environ.get ("GT40_HEIGHT", 24))
fgcolor = os.environ.get ("GT40_COLOR", None)
bgcolor = None
if fgcolor:
fgcolor, *bgcolor = fgcolor.split (",")
class displayApp ():
"""This class wraps the App main loop for wxPython.
Due to limitations in some OS (Mac OS at least), this
class must be created in the main thread -- the first
thread of the process. Furthermore, the "start" method
will create the application and run the main loop, and will
not return until application exit. So for any other things
that need to run in the meantime, like user interaction,
the caller will need to create an additional thread.
This class creates a 24 by 80 character window, and initializes
some common state such as the font used to display text
in the window.
"""
def __init__ (self, teco):
self.running = False
self.teco = teco
self.displayline = 16
def start (self):
"""Start the wx App main loop.
This finds a font, then opens up a Frame initially
sized for 80 by 24 characters.
"""
global display
self.app = wx.App ()
self.font = wx.Font (pointsize, wx.FONTFAMILY_MODERN,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_NORMAL)
# The error handling here is a bit ugly because we're too
# far from the command loop to make it cleaner. Some
# restructuring might help, to be examined.
if bgcolor:
# Get the specified color
self.bg = wx.Colour (bgcolor[0].replace ("_", " "))
if not self.bg.IsOk ():
print ("\r\nUnknown background color:", bgcolor, "\r\n")
self.bg = wx.BLACK
self.bgpen = wx.Pen (self.bg)
else:
# Traditional GT40 look
self.bgpen = wx.BLACK_PEN
self.bg = wx.BLACK
if fgcolor:
self.fg = wx.Colour (fgcolor.replace ("_", " "))
if not self.fg.IsOk ():
print ("\r\nUnknown foreground color:", fgcolor, "\r\n")
self.fg = wx.GREEN
self.fgpen = wx.Pen (self.fg)
else:
self.fgpen = wx.GREEN_PEN
self.fg = wx.GREEN
dc = wx.MemoryDC ()
dc.SetFont (self.font)
self.fontextent = dc.GetTextExtent ("a")
cw, ch = self.fontextent
self.margin = cw
cw = cw * width + self.margin * 2
ch = ch * height + self.margin * 2
self.frame = displayframe (self, wx.ID_ANY, "TECO display",
wx.Size (cw, ch))
self.frame.Show (True)
self.running = True
self.app.MainLoop ()
# Come here only on application exit.
display = None
def show (self, show = True):
"""If the display is active, this refreshes it to display
the current text around dot. If "show" is False, it tells
the display to go hide itself.
"""
if self.running:
self.frame.doShow = show
self.frame.doRefresh = True
wx.WakeUpIdle ()
def stop (self):
"""Stop the display thread by closing the Frame.
"""
if self.running:
self.running = False
self.frame.AddPendingEvent (wx.CloseEvent (wx.wxEVT_CLOSE_WINDOW))
class displayframe (wx.Frame):
"""Simple text display window class derived from wxFrame.
It handles repaint, close, and timer events. The timer
event is used for the blinking text cursor.
When instantiated, this class creats the window using the
supplied size, and starts the cursor blink timer.
"""
def __init__ (self, display, id, name, size):
framestyle = (wx.MINIMIZE_BOX |
wx.MAXIMIZE_BOX |
wx.RESIZE_BORDER |
wx.SYSTEM_MENU |
wx.CAPTION |
wx.CLOSE_BOX |
wx.FULL_REPAINT_ON_RESIZE)
wx.Frame.__init__ (self, None, id, name, style = framestyle)
self.SetClientSize (size)
timerId = 666
self.Bind (wx.EVT_PAINT, self.OnPaint)
self.Bind (wx.EVT_CLOSE, self.OnClose)
self.Bind (wx.EVT_TIMER, self.OnTimer)
self.Bind (wx.EVT_IDLE, self.OnIdle)
self.display = display
self.cursor = None, None, False
self.timer = wx.Timer (self, timerId)
self.timer.Start (500)
self.cursorState = True
self.doRefresh = True
self.doShow = True
self.SetBackgroundColour (self.display.bg)
def OnIdle (self, event = None):
"""Used to make a refresh happen, if one has been requested.
"""
if self.doRefresh:
self.doRefresh = False
self.Show (self.doShow)
if self.doShow:
self.Refresh ()
def OnTimer (self, event = None):
"""Draw a GT40-TECO style cursor: vertical line with
a narrow horizontal line across the bottom, essentially
an upside-down T.
If dot is between a CR and LF, the cursor is drawn upside
down (right side up T) at the left margin.
"""
x, y, flip = self.cursor
if x is not None:
cw, ch = self.display.fontextent
if self.cursorState:
pen = self.display.fgpen
else:
pen = self.display.bgpen
self.cursorState = not self.cursorState
dc = wx.ClientDC (self)
dc.SetPen (pen)
if flip:
dc.DrawLine (x, y, x, y - ch)
dc.DrawLine (x - cw // 2, y - ch, x + cw // 2 + 1, y - ch)
else:
dc.DrawLine (x, y, x, y - ch)
dc.DrawLine (x - cw // 2, y, x + cw // 2 + 1, y)
def OnPaint (self, event = None):
"""This is the event handler for window repaint events,
which is also done on window resize. It fills the window
with the buffer contents, centered on dot.
Line wrap is indicated in GT40 fashion: the continuation line
segments have a right-pointing arrow in the left margin.
"""
dc = wx.PaintDC (self)
dc.Clear ()
dc.SetFont (self.display.font)