forked from MarkLodato/vt100-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vt100.py
executable file
·2527 lines (2097 loc) · 73.9 KB
/
vt100.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
"""
NAME
====
vt100.py - Parse a typescript and output text.
SYNOPSIS
========
``vt100.py [OPTIONS] [-f FORMAT] [-g WxH] (filename|-)``
DESCRIPTION
===========
This module implements a VT100-style (ANSI) terminal emulator for the purpose
of parsing the output of script(1) file and printing to a human-readable
format. The intent is to mimic the exact output of xterm(1), as though you
cut and pasted the output from the terminal.
This program can be used to parse any file containing ANSI (ECMA-48) terminal
codes. Usually the input is a typescript file as output from script(1), which
is usually not human-readable. Another potential use of this program to to
parse the output of a program that produces color codes (ESC [ # m) and
produce color HTML.
Output Formats
--------------
A number of output formats are available. Currently, that number is two.
text
The output is a pure ASCII file with unix line endings. All character
attributes are ignored (even 'hidden').
html
The output is a snippet of HTML with one ``pre`` element. Character
attributes, including xterm 256 colors, are supported.
Unimplemented Features
----------------------
This module is designed to mimic the output (and only output) of xterm.
Therefore, there are no plans to implement any sequence that affects input,
causes the terminal to respond, or that xterm does not itself implement.
OPTIONS
=======
-h, --help print help message and exit
--man print manual page and exit
--version print version number and exit
-f FORMAT, --format=FORMAT specify output format (see "Output Formats")
-g WxH, --geometry=WxH specify console geometry (see "Configuration")
--non-script do not ignore "Script (started|done) on" lines
--rc=FILE read configuration from FILE (default ~/.vt100rc)
--no-rc suppress reading of configuration file
-q, --quiet decrease debugging verbosity
-v, --verbose increase debugging verbosity
The following only affect HTML output.
--background=COLOR set the default background color
--foreground=COLOR set the default foreground color
--colorscheme=SCHEME use the given color scheme (see "Configuration")
CONFIGURATION
=============
By default, vt100.py reads ~/.vt100rc for the following 'key = value` pairs.
COLOR is any valid HTML color. The order does not matter, except that all the
settings following ``[SECTION]`` belong to a specific section.
background = COLOR
Default background color.
color0 = COLOR ...through... color255 = COLOR
Color for the 8 ANSI colors (0-7), 8 bright ANSI colors (8-15), and xterm
extended colors (16-255).
colorscheme = SECTION
Import settings from [SECTION] before any in the current section.
format = {text, html}
Default output format. Default is 'text'.
foreground = COLOR
Default foreground color.
geometry = {WxH, detect}
Use W columns and H rows in output. If the value 'detect' is given, the
current terminal's geometry is detected using ``stty size``.
Default is '80x24'.
inverse_bg = COLOR
Background color to use for the "inverse" attribute when neither the
character's foreground color attribute nor the ``foreground`` option is
set. Default is 'black'.
inverse_fg = COLOR
Foreground color to use for the "inverse" attribute when neither the
character's background color attribute nor the ``background`` option is
set. Default is 'white'.
verbosity = INT
Act as those ``-v`` or ``-q`` was given abs(INT) times, if INT positive or
negative, respectively. Default is '0'.
[SECTION]
Start a definition of a color scheme named SECTION.
REQUIREMENTS
============
* Python 2.6+ or 3.0+ (tested on 2.6, 2.7, 3.1, and 3.2)
TODO
====
See TODO for things that are not yet implemented. There are many.
NOTES
=====
For testing how a terminal implements a feature, the included *rawcat* program
may be helpful. It acts like cat(1), except that it outputs the file
literally; it does not perform LF to CRLF translation. Alternatively, one may
replace the LF (0x0a) character with VT (0x0b) or FF (0x0c), which are treated
identically but are not subject to newline translation.
A neat feature of *rawcat* is the ``-w`` option, which causes it to pause
after each output byte so you can observe xterm draw the screen.
SEE ALSO
========
script(1), scriptreplay(1)
AUTHOR
======
Mark Lodato <[email protected]>
THANKS
======
Thanks to http://vt100.net for lots of helpful information, especially the
DEC-compatible parser page.
"""
# Requires Python 2.6
from __future__ import print_function
__version__ = "0.4-git"
__author__ = "Mark Lodato"
__license__ = """
Copyright (c) 2010 Mark Lodato
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.
"""
import collections
import itertools
import os.path
import re
import subprocess
import sys
from optparse import OptionParser, OptionGroup
try:
from ConfigParser import SafeConfigParser as ConfigParser
except ImportError:
from configparser import ConfigParser
try:
from io import StringIO
except ImportError:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
if sys.version_info[0] == 2:
__metaclass__ = type
map = itertools.imap
range = xrange
class TextFormatter:
"""Terminal formatter for plain text output."""
def __init__(self, config=None, eol='\n'):
self.eol = eol
self.init()
if config is not None:
self.parse_config(config)
def init(self):
"""Initialize any default instance variables."""
pass
def parse_config(self, config):
"""Parse a SafeConfigParser object."""
pass
def format(self, lines):
"""Return a stringification of the given lines."""
out = []
out.extend(self.begin())
out.extend(self.format_line(line) for line in lines)
out.extend(self.end())
out.append('')
return self.eol.join(out)
def begin(self):
"""Return a list of lines to be output before the formatted lines."""
return []
def format_line(self, line):
"""Return the given line (sequence of Characters) formatted as
a string (without an EOL character)."""
return ''.join(x.char for x in line)
def end(self):
"""Return a list of lines to be output after the formatted lines."""
return []
class HtmlFormatter (TextFormatter):
"""Terminal formatter for HTML output."""
attr_map = {
# 'fg_color' and 'bg_color' set by init()
('weight', 'bold') : 'font-weight: bold',
('weight', 'feint') : 'font-weight: lighter',
('underline', 'single') : 'text-decoration: underline',
('underline', 'double') : ('text-decoration: underline; '
'border-bottom: 1px solid'),
('style', 'italic') : 'font-style: italic',
('blink', 'rapid') : 'text-decoration: blink',
('blink', 'slow') : 'text-decoration: blink', # no fast or slow
('hidden', True) : 'visibility: hidden',
('strikeout', True) : 'text-decoration: line-through',
('overline', True) : 'text-decoration: overline',
# TODO frame
}
escapes = {
'&' : '&',
'<' : '<',
'>' : '>',
}
default_options = {
'foreground' : '',
'background' : '',
'inverse_fg' : 'white',
'inverse_bg' : 'black',
}
# [black, red, green, brown/yellow, blue, magenta, cyan, white]
# Colors used by xterm (before patch #192, blues were #0000cd and #0000ff)
color_16 = ['#000000', '#cd0000', '#00cd00', '#cdcd00',
'#0000e8', '#cd00cd', '#00cdcd', '#e5e5e5',
'#7f7f7f', '#ff0000', '#00ff00', '#ffff00',
'#5c5cff', '#ff00ff', '#00ffff', '#ffffff']
def init(self):
self.init_colors()
self.attr_map = self.__class__.attr_map.copy()
self.options = self.__class__.default_options.copy()
for index, value in enumerate(self.color_256):
self.set_color(index, value)
def init_colors(self):
def create_color_table(color_scale, gray_scale):
table = self.color_16[:16]
for r, g, b in itertools.product(color_scale, repeat=3):
table.append('#%02x%02x%02x' % (r,g,b))
for g in gray_scale:
table.append('#%02x%02x%02x' % (g,g,g))
return table
self.color_256 = create_color_table([0, 95, 135, 175, 215, 255],
[i*10 + 8 for i in range(24)])
self.color_88 = create_color_table([0, 139, 205, 255],
[46, 92, 113, 139, 162, 185, 208, 231])
def set_color(self, index, value):
self.attr_map['fg_color', index] = 'color: %s' % value
self.attr_map['bg_color', index] = 'background-color: %s' % value
def parse_config(self, config):
self._parse_config(config, config.initial_section, set())
if self.options['foreground']:
self.options['inverse_bg'] = self.options['foreground']
if self.options['background']:
self.options['inverse_fg'] = self.options['background']
def _parse_config(self, config, section, seen):
if config.has_option(section, 'colorscheme'):
scheme = config.get(section, 'colorscheme')
if scheme not in seen:
if config.has_section(scheme):
seen.add(scheme)
self._parse_config(config, scheme, seen)
else:
print('warning: colorscheme "%s" not found' % scheme,
file=sys.stderr)
else:
print('warning: recursion in color scheme: [%s] -> %s'
% (section, scheme), file=sys.stderr)
for i in range(256):
key = 'color%d'%i
if config.has_option(section, key):
self.set_color(i, config.get(section, key))
for key in self.options:
if config.has_option(section, key):
value = config.get(section, key)
self.options[key] = value
def _compute_style(self, attr):
# TODO implement inverse
out = []
if attr.pop('inverse', None):
fg = attr.pop('fg_color', None)
bg = attr.pop('bg_color', None)
if fg is not None:
attr['bg_color'] = fg
else:
out.append('background-color: %s' % self.options['inverse_bg'])
if bg is not None:
attr['fg_color'] = bg
else:
out.append('color: %s' % self.options['inverse_fg'])
for key in sorted(attr):
value = attr[key]
try:
out.append( self.attr_map[key, value] )
except KeyError:
# TODO verbose option?
print('unknown attribute: %s:%s' % (key, value),
file=sys.stderr)
return '; '.join(out)
def begin(self):
style = []
if self.options['foreground']:
style.append('color: %s' % self.options['foreground'])
if self.options['background']:
style.append('background-color: %s' % self.options['background'])
if style:
attribute = ' style="%s"' % '; '.join(style)
else:
attribute = ''
return ['<pre%s>' % attribute]
def format_line(self, line):
out = []
last_style = ''
for c in line:
style = self._compute_style(c.attr)
if style != last_style:
if last_style:
out.append('</span>')
if style:
out.append('<span style="%s">' % style)
last_style = style
char = self.escapes.get(c.char, c.char)
out.append(char)
if last_style:
out.append('</span>')
return ''.join(out)
def end(self):
return ['</pre>']
formatters = {
'text' : TextFormatter,
'html' : HtmlFormatter,
}
class Character:
"""A single character along with an associated attribute."""
def __init__(self, char, attr = {}):
self.char = char
self.attr = attr
def __repr__(self):
return "<'%s'>" % (str(self.char))
def __str__(self):
return str(self.char)
class InvalidParameterListError (RuntimeError):
pass
def param_list(s, default, zero_is_default=True, min_length=1):
"""Return the list of integer parameters assuming `s` is a standard
control sequence parameter list. Empty elements are set to `default`."""
def f(token):
if not token:
return default
value = int(token)
if zero_is_default and value == 0:
return default
if value < 0:
raise ValueError
return value
if s is None:
l = []
else:
try:
l = [f(token) for token in s.split(';')]
except ValueError:
raise InvalidParameterListError
l += [default] * (min_length - len(l))
return l
def clip(n, start, stop=None):
"""Return n clipped to range(start,stop)."""
if stop is None:
stop = start
start = 0
if n < start:
return start
if n >= stop:
return stop-1
return n
def new_sequence_decorator(dictionary):
def decorator_generator(key):
assert isinstance(key, (str, int))
def decorator(f, key=key):
dictionary[key] = f.__name__
return f
return decorator
return decorator_generator
class NoNeedToImplement (Exception):
"""A function for which there is no need to implement."""
pass
class Screen:
"""A two-dimensional collection of characters."""
def __init__(self, width, height):
self.width = width
self.height= height
self.clear()
def __iter__(self):
return iter(self.rows)
def __setitem__(self, idx, value):
row, col = idx
self.rows[row][col] = value
def clear(self):
"""Set all elements to None."""
self.rows = [[None] * self.width for i in range(self.height)]
def clear_row(self, row, start=0, stop=None):
"""Set to None all elements on row `row` and columns `start` to
`stop`-1, inclusive."""
if start < 0:
start = 0
if stop is None or stop > self.width:
stop = self.width
row = self.rows[row]
for c in range(start, stop):
row[c] = None
def clear_rows(self, start=0, stop=None):
"""Set to None all elements on rows `start` to `stop`-1, inclusive."""
if start < 0:
start = 0
if stop is None or stop > self.height:
stop = self.height
for r in range(start, stop):
self.rows[r] = [None] * self.width
def shift_row(self, row, col, amount=1, fill=None):
"""Move the elements on row `row` at and to the right of column
`col`, to the right by `amount` places (negative means left).
Elements shifted past either end are discarded. New elements are set
to `fill`."""
row = self.rows[row]
if amount > 0:
amount = min(amount, self.width-col)
row[col+amount:] = row[col:-amount]
row[col:col+amount] = [fill] * amount
else:
amount = min(-amount, self.width-col)
row[col:-amount] = row[col+amount:]
row[-amount:] = [fill] * amount
class Terminal:
# ---------- Decorators for Defining Sequences ----------
commands = {}
escape_sequences = {}
control_sequences = {}
ansi_modes = {}
dec_modes = {}
command = new_sequence_decorator(commands)
escape = new_sequence_decorator(escape_sequences)
control = new_sequence_decorator(control_sequences)
ansi_mode = new_sequence_decorator(ansi_modes)
dec_mode = new_sequence_decorator(dec_modes)
# ---------- Constructor ----------
def __init__(self, height=24, width=80, verbosity=False,
formatter=TextFormatter()):
self.verbosity = verbosity
self.width = width
self.height = height
self.formatter = formatter
self.main_screen = Screen(width, height)
self.alt_screen = Screen(width, height)
self.reset()
# ---------- Utilities ----------
def reset(self):
"""Reset to initial state."""
self.state = 'ground'
self.prev_state = None
self.next_state = None
self.history = []
self.main_screen.clear()
self.alt_screen.clear()
self.screen = self.main_screen
self.row = 0
self.col = 0
self.saved_cursor = [self.default_cursor, self.default_cursor]
self.margin_top = 0
self.margin_bottom = self.height - 1
self.previous = '\0'
self.current = '\0'
self.tabstops = [(i%8)==0 for i in range(self.width)]
self.attr = {}
self.insert_mode = False
self.new_line_mode = False
self.autowrap_mode = True
self.reverse_wrap = False
self.clear()
default_cursor = {
'pos' : (0, 0),
'attr' : {},
'autowrap' : True,
'reverse_wrap' : False,
'origin_mode' : False,
# TODO: pending SS2 or SS3
# TODO: selective erase
}
def _pos_get(self):
"""The cursor position as (row, column)."""
return self.row, self.col
def _pos_set(self, value):
self.row, self.col = value
pos = property(_pos_get, _pos_set)
def is_alt_screen(self):
"""Return True if in alternate screen mode; False otherwise."""
return self.screen is self.alt_screen
def clear(self):
"""Reset internal buffers for switching between states."""
self.collected = ''
def clip_column(self):
"""If the cursor is past the end of the line, move it to the last
position in the line."""
if self.col >= self.width:
self.col = self.width - 1
def output(self, c):
"""Print the character at the current position and increment the
cursor to the next position. If the current position is past the end
of the line, starts a new line."""
if self.col >= self.width:
if self.autowrap_mode:
self.NEL()
else:
self.col = self.width - 1
c = Character(c, self.attr.copy())
if self.insert_mode:
self.screen.shift_row(self.row, self.col)
self.screen[self.pos] = c
self.col += 1
def scroll(self, n, top = None, bottom = None, save = None):
"""Scroll the scrolling region n lines upward (data moves up) between
rows top (inclusive, default 0) and bottom (exclusive, default
height). Any data moved off the top of the screen (if top is 0/None
and save is None, or if save is True) is saved to the history.
If in alternate screen buffer, no history is saved."""
# TODO add option to print instead of adding to history
if top is None:
top = self.margin_top
if bottom is None:
bottom = self.margin_bottom + 1
s = self.screen
if self.is_alt_screen():
save = False
span = bottom-top
if n > 0:
# TODO transform history?
if (save is None and top == 0) or save:
self.history.extend( s.rows[top:top+n] )
if n > span:
extra = n - span
self.history.extend( [[None]*self.width]*extra )
if n > span:
n = span
s.rows[top:bottom-n] = s.rows[top+n:bottom]
s.clear_rows(start=bottom-n, stop=bottom)
elif n < 0:
n = -n
if n > span:
n = span
s.rows[top+n:bottom] = s.rows[top:bottom-n]
s.clear_rows(start=top, stop=top+n)
def ignore(self, c):
"""Ignore the character."""
self.debug(1, 'ignoring character: %s' % repr(c))
def collect(self, c):
"""Record the character as an intermediate."""
self.collected += c
def clear_on_enter(self, old_state):
"""Since most enter_* functions just call self.clear(), this is a
common function so that you can set enter_foo = clear_on_enter."""
self.clear()
def debug(self, level, *args, **kwargs):
if self.verbosity >= level:
kwargs.setdefault('file', sys.stderr)
print(*args, **kwargs)
# ---------- Parsing ----------
def parse(self, s):
"""Parse an entire string."""
for c in s:
self.parse_single(c)
def parse_single(self, c):
"""Parse a single character."""
if isinstance(c, int):
c = chr(c)
try:
f = getattr(self, 'parse_%s' % self.state)
except AttributeError:
raise RuntimeError("internal error: unknown state %s" %
repr(self.state))
self.next_state = self.state
f(c)
self.transition()
def transition(self):
if self.next_state != self.state:
f = getattr(self, 'leave_%s' % self.state, None)
if f is not None:
f(self.next_state)
self.next_state, self.state, self.prev_state = (None,
self.next_state, self.state)
if self.state != self.prev_state:
f = getattr(self, 'enter_%s' % self.state, None)
if f is not None:
f(self.prev_state)
def parse_ground(self, c):
self.previous, self.current = self.current, c
if ord(c) < 0x20:
self.execute(c)
else:
self.output(c)
# ---------- Output ----------
def to_string(self, history=True, screen=True, remove_blank_end=True,
formatter=None):
"""Return a string form of the history and the current screen."""
# Concatenate the history and the screen, and fix each line.
lines = []
if history:
lines.extend(map(self.fixup_line, self.history))
if screen:
lines.extend(map(self.fixup_line, self.main_screen))
if not lines:
return
# Remove blank lines from the end of input.
if remove_blank_end:
lines = self.drop_end(None, list(lines))
if formatter is None:
formatter = self.formatter
return formatter.format(lines)
def print_screen(self, formatter=None):
"""Print the state of the current screen to standard output."""
print(self.to_string(False, True, False, formatter), end='')
def fixup_line(self, line):
"""Remove empty characters from the end of the line and change Nones
to spaces with no attributes."""
def convert_to_blank(x):
if x is not None:
return x
else:
return Character(' ')
def is_None(x):
return x is None
return list(map(convert_to_blank, self.drop_end(is_None, line)))
@staticmethod
def drop_end(predicate, sequence):
"""Simliar as itertools.dropwhile, except operating from the end."""
i = 0
if predicate is None:
for x in reversed(sequence):
if x:
break
i += 1
else:
for x in reversed(sequence):
if not predicate(x):
break
i += 1
if i == 0:
return sequence
else:
return sequence[:-i]
# ---------- Single-character commands (C0) ----------
def execute(self, c):
"""Execute a C0 command."""
name = self.commands.get(c, None)
f = None
if name is not None:
f = getattr(self, name, None)
if f is None:
f = self.ignore
r = f(c)
if r is NotImplemented:
self.debug(0, 'command not implemented: %s' % f.__name__)
elif r is NoNeedToImplement:
self.debug(1, 'ignoring command: %s' % f.__name__)
@command('\x00') # ^@
def NUL(self, c=None):
"""NULl"""
pass
@command('\x07') # ^G
def BEL(self, c=None):
"""Bell"""
pass
@command('\x08') # ^H
def BS(self, c=None):
"""Backspace"""
self.clip_column()
if self.col > 0:
self.col -= 1
elif self.reverse_wrap:
self.col = self.width - 1
if self.row > 0:
self.row -= 1
else:
self.row = self.height - 1
@command('\x09') # ^I
def HT(self, c=None):
"""Horizontal Tab"""
while self.col < self.width-1:
self.col += 1
if self.tabstops[self.col]:
break
@command('\x0a') # ^J
def LF(self, c=None):
"""Line Feed"""
if self.new_line_mode:
self.NEL()
else:
self.IND()
@command('\x0b') # ^K
def VT(self, c=None):
"""Vertical Tab"""
self.LF(c)
@command('\x0c') # ^L
def FF(self, c=None):
"""Form Feed"""
self.LF(c)
@command('\x0d') # ^M
def CR(self, c=None):
"""Carriage Return"""
self.col = 0
@command('\x18') # ^X
def CAN(self, c=None):
"""Cancel"""
self.next_state = 'ground'
@command('\x1a') # ^Z
def SUB(self, c=None):
"""Substitute"""
self.next_state = 'ground'
@command('\x1b') # ^[
def ESC(self, c=None):
"""Escape"""
self.next_state = 'escape'
# ---------- Escape Sequences ----------
enter_escape = clear_on_enter
def parse_escape(self, c):
if ord(c) < 0x20:
self.execute(c)
elif ord(c) < 0x30:
self.collect(c)
elif ord(c) < 0x7f:
self.next_state = 'ground'
self.dispatch_escape(c)
else:
self.ignore(c)
def dispatch_escape(self, c):
command = self.collected + c
name = self.escape_sequences.get(c, None)
f = None
if name is not None:
f = getattr(self, name, None)
if f is None:
f = self.ignore
r = f(command)
if r is NotImplemented:
self.debug(0, 'escape not implemented: %s' % f.__name__)
elif r is NoNeedToImplement:
self.debug(1, 'ignoring escape: %s' % f.__name__)
@escape('7')
def DECSC(self, c=None):
"""Save Cursor"""
self.saved_cursor[int(self.is_alt_screen())] = {
'pos' : self.pos,
'attr' : self.attr.copy(),
'autowrap' : self.DECAWM(None),
'reverse_wrap' : self.reverse_wraparound_mode(None),
'origin_mode' : self.DECOM(None),
}
@escape('8')
def DECRC(self, c=None):
"""Restore Cursor"""
cursor = self.saved_cursor[int(self.is_alt_screen())]
self.pos = cursor['pos']
self.attr = cursor['attr'].copy()
self.DECAWM(cursor['autowrap'])
self.reverse_wraparound_mode(cursor['reverse_wrap'])
self.DECOM(cursor['origin_mode'])
self.clip_column()
@escape('D')
def IND(self, c=None):
"""Index"""
self.clip_column()
if self.row == self.margin_bottom:
self.scroll(1)
elif self.row < self.height - 1:
self.row += 1
@escape('E')
def NEL(self, c=None):
"""Next Line"""
self.IND()
self.col = 0
@escape('H')
def HTS(self, c=None):
"""Horizontal Tab Set"""
if self.col < self.width:
self.tabstops[self.col] = True
@escape('M')
def RI(self, c=None):
"""Reverse Index (reverse line feed)"""
self.clip_column()
if self.row == self.margin_top:
self.scroll(-1)
elif self.row > 0:
self.row -= 1
@escape('P')
def DCS(self, c=None):
"""Device Control String"""
self.next_state = 'dcs'
@escape('X')
def SOS(self, c=None):
"""Start of String"""
self.next_state = 'sos'
@escape('[')
def CSI(self, c=None):
"""Control Sequence Introducer"""
self.next_state = 'control_sequence'
@escape('\\')
def ST(self, c=None):
"""String Terminator"""
pass
@escape(']')
def OSC(self, c=None):
"""Operating System Command"""
self.next_state = 'osc'
@escape('^')
def PM(self, c=None):
"""Privacy Message"""
self.next_state = 'pm'
@escape('_')
def APC(self, c=None):
"""Application Program Command"""
self.next_state = 'apc'
@escape('c')
def RIS(self, command=None, param=None):
"""Reset to Initial State"""
self.reset()
# ---------- Control Sequences ----------
enter_control_sequence = clear_on_enter
def parse_control_sequence(self, c):
if ord(c) < 0x20:
self.execute(c)
elif ord(c) < 0x40:
self.collect(c)
elif ord(c) < 0x7f:
self.next_state = 'ground'
self.dispatch_control_sequence(c)
else:
self.ignore(c)