-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.py
executable file
·1739 lines (1508 loc) · 57.8 KB
/
view.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
import datetime
import json
import os
import re
import shutil
import sys
import textwrap
try:
import colored
except ImportError:
colored = None
__version__ = '0.0.14'
__commit__ = 'HEAD'
# Available rendering modes.
RENDERING_MODE_ASCII_ART = 'RENDERING_MODE_ASCII_ART'
RENDERING_MODE_HTML_ASCII_ART = 'RENDERING_MODE_HTML_ASCII_ART'
RENDERING_MODE_HTML = 'RENDERING_MODE_HTML'
# Selected rendering mode.
RENDERING_MODE = os.environ.get('RENDERING_MODE', RENDERING_MODE_ASCII_ART)
RENDERED_LINES = []
_preserved_old_print = print
def print(*args, **kwargs):
RENDERED_LINES.append(' '.join(args))
COLOR_SECTION_INDEX = 'red'
COLOR_SECTION_NAME = 'light_yellow'
COLOR_SECTION_SLUG = 'green'
COLOR_REF = 'green'
COLOR_SOURCE = 'light_green'
def colorise(text, color):
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
if os.environ.get('COLOR') != 'no':
return '<span style="color: {color};">{text}</span>'.format(color = color, text = str(text).replace('<', '<').replace('>', '>'))
return str(text)
if colored is None or os.environ.get('COLOR') == 'no':
return str(text)
return (colored.fg(color) + str(text) + colored.attr('reset'))
DEBUG_LONGEN = False
def longen_line(line, width):
chunks = line.split()
length_of_chunks = len(''.join(chunks))
spaces_to_fill = (width - length_of_chunks)
no_of_splits = len(chunks) - 1
spaces_per_split = (spaces_to_fill // (no_of_splits or 1))
spaces_left = (spaces_to_fill - (spaces_per_split * no_of_splits))
no_of_double_spaces = spaces_left
if DEBUG_LONGEN:
sys.stderr.write('---- for line: {}\n'.format(repr(line)))
sys.stderr.write('length_of_chunks = {}\n'.format(length_of_chunks))
sys.stderr.write('spaces_to_fill = {}\n'.format(spaces_to_fill))
sys.stderr.write('no_of_splits = {}\n'.format(no_of_splits))
sys.stderr.write('spaces_per_split = {}\n'.format(spaces_per_split))
sys.stderr.write('spaces_left = {}\n'.format(spaces_left))
new_line = [chunks[0]]
normal_spacing = (' ' if spaces_per_split == 2 else ' ')
for each in chunks[1:]:
if no_of_double_spaces:
new_line.append(' ')
no_of_double_spaces -= 1
else:
new_line.append(normal_spacing)
new_line.append(each)
new_line = ''.join(new_line)
# If the desired width was not reached, do not introduce any "double spaces" and
# just return the simples representation possible.
if len(new_line) != width:
new_line = ' '.join(chunks)
if DEBUG_LONGEN:
new_line = '[{}:{}] {}'.format(len(new_line), width, new_line)
return new_line
def longen(lines, width):
return [longen_line(each, width) for each in lines]
RENDER_TIMESTAMP = os.environ.get('RENDER_TIMESTAMP', 'none')
MARGIN_COLUMNS = 2
LINE_WIDTH = int(os.popen('stty size', 'r').read().split()[1])
if 'RENDER_COLUMNS' in os.environ:
x = os.environ.get('RENDER_COLUMNS', LINE_WIDTH)
if x.startswith('<'):
LINE_WIDTH = min(LINE_WIDTH, int(x[1:]))
else:
LINE_WIDTH = int(x)
LINE_WIDTH -= MARGIN_COLUMNS
TOP_MARKER = '^^^^'
# See https://www.unicode.org/charts/beta/nameslist/n_2190.html
# 21B5 ↵ Downwards Arrow With Corner Leftwards
NEWLINE_MARKER = '↵'
INDENT_MARKER = ' '
NESTED_CALL_MARKER = '↳ '
TITLE = None
REFS = None
REF_NOT_FOUND_MARKER = '????'
def stringify_encoding(encoding):
stringified = []
size_so_far = 0
for each in encoding:
if each == '@opcode':
head = '{} ... {}'.format(size_so_far, size_so_far + 7)
size_so_far += 8
stringified.append(
(head, 'OP',),
)
elif each == '@register':
head = '{} ... {}'.format(size_so_far, size_so_far + 7)
size_so_far += 8
stringified.append(
(head, 'AS',),
)
head = '{} ... {}'.format(size_so_far, size_so_far + 7)
size_so_far += 8
stringified.append(
(head, 'RS',),
)
max_lengths = list(map(lambda pair: max(len(pair[0]), len(pair[1])), stringified))
heads = []
bodies = []
for i, each in enumerate(stringified):
head, body = each
heads.append(head.center(max_lengths[i]))
bodies.append(body.center(max_lengths[i]))
return (
size_so_far,
'| {} |'.format(' | '.join(heads)),
'| {} |'.format(' | '.join(bodies))
)
DEFAULT_INDENT_WIDTH = 2
COMMENT_MARKER = '%%'
KEYWORD_REFLOW_OFF_REGEX = re.compile(r'\\reflow{off}')
KEYWORD_REFLOW_ON_REGEX = re.compile(r'\\reflow{on}')
KEYWORD_SOURCE_BEGIN_REGEX = re.compile(r'\\source{begin}')
KEYWORD_SOURCE_END_REGEX = re.compile(r'\\source{end}')
KEYWORD_WRAP_BEGIN_REGEX = re.compile(r'\\wrap{begin}')
KEYWORD_WRAP_END_REGEX = re.compile(r'\\wrap{end}')
KEYWORD_LIST_BEGIN_REGEX = re.compile(r'\\list{begin}')
KEYWORD_LIST_END_REGEX = re.compile(r'\\list{end}')
KEYWORD_LISTED_BEGIN_REGEX = re.compile(r'\\listed{begin}')
KEYWORD_LISTED_END_REGEX = re.compile(r'\\listed{end}')
KEYWORD_ITEM_REGEX = re.compile(r'\\item')
KEYWORD_INDENT_REGEX = re.compile(r'\\indent{(\d*)}')
KEYWORD_DEDENT_REGEX = re.compile(r'\\dedent{(\d*|all)}')
KEYWORD_SECTION_BEGIN_REGEX = re.compile(r'\\section{begin}')
KEYWORD_SECTION_END_REGEX = re.compile(r'\\section{end}')
KEYWORD_HEADING_REGEX = re.compile(r'\\heading{([^}]+)}')
PARAMETER_REGEX = re.compile(r'{([a-z_]+)(?:(=[^}]*))?}')
KEYWORD_INSTRUCTION_REGEX = re.compile(r'\\instruction{([a-z]+)}')
KEYWORD_SYNTAX_REGEX = re.compile(r'\\syntax{([0-9]+)}')
KEYWORD_REF_REGEX = re.compile(r'\\ref{([a-z_][a-z0-9_-]*(?:[:.][a-z0-9_-]+)*)}')
KEYWORD_NAMEREF_REGEX = re.compile(r'\\nameref{([a-z_][a-z0-9_-]*(?:[:.][a-z_][a-z0-9_-]*)*)}')
KEYWORD_COLOR_REGEX = re.compile(r'\\color{([a-z]+)}{([^}]+)}')
KEYWORD_INCLUDE = re.compile(r'\\include{(.*)}')
KEYWORD_TITLE_REGEX = re.compile(r'\\title{(.*)}')
KEYWORD_HORIZONTAL_SEPARATOR = r'\hr'
KEYWORD_EMPTY_LINE = r'\emptyline'
KEYWORD_CALLSEQUENCE_BEGIN = r'\callsequence{begin}'
KEYWORD_CALLSEQUENCE_END = r'\callsequence{end}'
KEYWORD_CALL_BEGIN = r'\call{begin}'
KEYWORD_CALL_END = r'\call{end}'
KEYWORD_CALLOF = re.compile(r'\\callof{(.*)}')
KEYWORD_TOC = re.compile(r'\\toc{(.*)}')
def paragraph_visible(para):
para = (para[0] if para else None)
if para is None:
return True
if para == r'\reflow{off}' or para == r'\reflow{on}':
return False
if para == r'\section{begin}' or para == r'\section{end}':
return False
if KEYWORD_INDENT_REGEX.match(para) or KEYWORD_DEDENT_REGEX.match(para):
return False
return True
def into_paragraphs(text):
raw_lines = text.splitlines()
paragraphs = []
para = []
lines = []
for each in raw_lines:
if lines and lines[-1] and (lines[-1][-1] == '\\' and lines[-1][-2] != '\\'):
lines[-1] = lines[-1][:-1] + each
continue
if lines and lines[-1] and (lines[-1][-1] == '\\' and lines[-1][-2] == '\\'):
lines[-1] = lines[-1][:-1]
lines.append(each)
for each in lines:
if not each:
if para:
paragraphs.append(para)
para = []
# No reason to append breaking paragraph after an invisible one.
if (not paragraphs) or not paragraph_visible(paragraphs[-1]):
continue
# If the last paragraph is also empty, push only one paragraph-break.
if not paragraphs[-1]:
continue
# Append the paragraph, and the paragraph-break after it.
# Empty lines on their own introduce paragraph breaks.
# Use \break on its own to introduce line-break without an empty line.
paragraphs.append([])
continue
if each == r'\toc{overview}':
if para:
paragraphs.append(para)
para = []
paragraphs.append([r'\toc{overview}'])
continue
if each == r'\toc{full}':
if para:
paragraphs.append(para)
para = []
paragraphs.append([r'\toc{full}'])
continue
if KEYWORD_TOC.match(each):
if para:
paragraphs.append(para)
para = []
paragraphs.append([each])
continue
if each == r'\break':
paragraphs.append(para)
para = []
continue
if each == r'\reflow{off}' or each == r'\reflow{on}':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if each == KEYWORD_LIST_BEGIN_REGEX.match(each) or each == r'\list{end}':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_LISTED_BEGIN_REGEX.match(each) or each == r'\listed{end}':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if each == r'\item':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if each == r'\wrap{begin}' or each == r'\wrap{end}':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if each == r'\section{begin}' or each == r'\section{end}':
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_SOURCE_BEGIN_REGEX.match(each) or KEYWORD_SOURCE_END_REGEX.match(each):
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_INDENT_REGEX.match(each) or KEYWORD_DEDENT_REGEX.match(each):
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_HEADING_REGEX.match(each):
if para:
paragraphs.append(para)
paragraphs.append([])
paragraphs.append([each])
paragraphs.append([])
para = []
continue
if KEYWORD_TITLE_REGEX.match(each):
global TITLE
if TITLE is not None:
raise Exception('title already set to {}'.format(repr(TITLE)))
TITLE = KEYWORD_TITLE_REGEX.match(each).group(1)
continue
if KEYWORD_HORIZONTAL_SEPARATOR == each:
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_EMPTY_LINE == each:
if para:
paragraphs.append(para)
para = []
continue
if KEYWORD_CALLSEQUENCE_BEGIN == each or KEYWORD_CALLSEQUENCE_END == each:
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_CALL_BEGIN == each or KEYWORD_CALL_END == each:
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if KEYWORD_CALLOF.match(each):
if para:
paragraphs.append(para)
paragraphs.append([each])
para = []
continue
if each.startswith(COMMENT_MARKER):
continue
para.append(each)
if para:
paragraphs.append(para)
return ['\n'.join(each) for each in paragraphs]
class SectionTracker:
class TooManyEnds(Exception):
pass
def __init__(self, start_counting_at = 0):
self._start_counting_at = start_counting_at
self._depth = 0
self._path = []
self._counters = { '': self._start_counting_at, }
self._recorded_headings = []
def data(self):
recorded = self._recorded_headings
indexes = {}
for each in recorded:
indexes[each[0]] = each
labels = {}
for each in recorded:
if each[4] is None:
continue
labels[each[4]] = {
'index': each[0],
'extra': each[3],
'name': each[1],
}
refs = {
'recorded': recorded,
'indexes': indexes,
'labels': labels,
}
return refs
def depth(self):
return self._depth
def recorded_headings(self):
return self._recorded_headings
def slug(self, index, ref = None):
return (ref or index)
def current_base_index(self):
return '.'.join(map(str, self._path))
def heading(self, text, noise = False, extra = None, ref = None):
base_index = self.current_base_index()
counter_at_base_index = self._counters[base_index]
index = '{base}{sep}{counter}'.format(
base = base_index,
sep = ('.' if base_index else ''),
counter = counter_at_base_index,
)
self._recorded_headings.append( (index, text, noise, extra, ref,) )
self._counters[base_index] += 1
return index
def begin(self):
# This marker is only useful for tracking how many sections were opened to
# prevent calling .end() too many times.
self._depth += 1
current_index = self.current_base_index()
counter = self._counters[current_index] - 1
self._path.append(counter)
base_index = self.current_base_index()
if base_index not in self._counters:
self._counters[base_index] = self._start_counting_at
def end(self):
if self._depth == 0:
raise SectionTracker.TooManyEnds()
self._depth -= 1
self._path.pop()
section_tracker = SectionTracker(1)
class InvalidReference(Exception):
pass
class UnknownInstruction(Exception):
pass
class UnknownArgument(Exception):
pass
class MissingArgument(Exception):
pass
def parse_and_expand(text, syntax, documented_instructions):
expanded_text = text
reg = re.compile(r'\\syntax{(\d+)}')
found_syntax_refs = re.findall(reg, text)
for i in found_syntax_refs:
if int(i) >= len(syntax):
raise InvalidReference('invalid syntax reference: \\syntax{{{}}}\n'.format(i))
expanded_text = expanded_text.replace((r'\syntax{' + i + '}'), syntax[int(i)])
found_instruction_refs = re.compile(r'\\instruction{([a-z]+)}').findall(expanded_text)
for each in found_instruction_refs:
if each not in documented_instructions:
raise UnknownInstruction(each)
pat = (r'\instruction{' + each + '}')
replacement = each
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
for a in REFS['recorded']:
if a[3] is None:
continue
if a[3].get('instruction') and a[1] == each.upper():
replacement = '<a href="#{location}">{name}</a>'.format(
location = a[0].replace('.', '-'),
name = each,
)
break
expanded_text = expanded_text.replace(pat, replacement)
found_colorisations = re.compile(r'\\color{([a-z]+)}{([^}]+)}').findall(expanded_text)
for each in found_colorisations:
color, text = each
pat = (r'\color{' + color + '}{' + text + '}')
expanded_text = expanded_text.replace(pat, colorise(text, color))
found_refs = re.compile(r'\\ref{([a-z_][a-z0-9_]*(?::[a-z_][a-z0-9_]*)*)}').findall(expanded_text)
for each in found_refs:
if REFS is not None and each not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(each))
replacement = (REFS['labels'][each].get('index') if REFS is not None else None)
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
replacement = '<a href="#{location}">{name}</a>'.format(
location = (replacement or REF_NOT_FOUND_MARKER).replace('.', '-'),
name = replacement,
)
expanded_text = expanded_text.replace(
(r'\ref{' + each + '}'),
(replacement or REF_NOT_FOUND_MARKER),
)
found_name_refs = re.compile(r'\\nameref{([a-z_][a-z0-9_]*(?::[a-z_][a-z0-9_]*)*)}').findall(expanded_text)
for each in found_refs:
if REFS is not None and each not in REFS['labels']:
raise InvalidReference('invalid reference: \\nameref{{{}}}\n'.format(each))
replacement = (REFS['labels'][each].get('name') if REFS is not None else None)
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
replacement = '<a href="#{location}">{name}</a>'.format(
location = (replacement or REF_NOT_FOUND_MARKER).replace('.', '-'),
name = replacement,
)
else:
replacement = '{} {{{}}}'.format(
colorise(replacement, COLOR_REF),
colorise(each, COLOR_REF),
)
expanded_text = expanded_text.replace(
(r'\nameref{' + each + '}'),
(replacement or REF_NOT_FOUND_MARKER),
)
return expanded_text
def render_multiline_heading(heading_text, index, indent, noise, extra, ref):
format_line_title = '{prefix}[{index}] {text}'
format_line_ref = '{prefix}{index_prefix}{ref}'
ref_name = ''
if ref is not None:
ref_name = ' {{{}}}'.format(colorise(ref, COLOR_SECTION_SLUG))
top_marker = ''
top_marker_spacing = ''
slug = section_tracker.slug(index, ref)
index_slug = index.replace('.', '-')
index_prefix = len(index) + 2 # +2 for '[' and ']'
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
format_line_title = '{prefix}[{index}] <a id="{slug}"><a id="{index_slug}"></a><a href="#{slug}">{text}</a>{top_marker_spacing}{top_marker}'
if slug == index_slug:
format_line_title = '{prefix}[{index}] <a id="{index_slug}"></a><a href="#{slug}">{text}</a>{top_marker_spacing}{top_marker}'
format_line_ref = '{prefix}{index_prefix}{ref}'
top_marker_spacing = (' ' * (LINE_WIDTH - indent - len(index) - len(heading_text) - 1 -
len(TOP_MARKER) - 2))
top_marker = '<a href="#0">{}</a>'.format(TOP_MARKER)
print(format_line_title.format(
prefix = (' ' * indent),
index = colorise(index, COLOR_SECTION_INDEX),
index_slug = index,
slug = slug,
text = colorise(heading_text, COLOR_SECTION_NAME),
top_marker = top_marker,
top_marker_spacing = top_marker_spacing,
))
print(format_line_ref.format(
prefix = (' ' * indent),
index_prefix = (' ' * index_prefix),
ref = ref_name,
))
def render_heading(heading_text, indent, noise = False, extra = None, ref = None):
format_line = '{prefix}[{index}] {text}{ref}'
index = section_tracker.heading(heading_text, noise = noise, extra = extra, ref = ref)
ref_name = ''
if ref is not None:
ref_name = ' {{{}}}'.format(ref)
top_marker = ''
top_marker_spacing = ''
slug = section_tracker.slug(index, ref)
index_slug = index.replace('.', '-')
index_prefix = len(index) + 2
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
format_line = '{prefix}[{index}] <a id="{slug}"></a><a id="{index_slug}"></a><a href="#{slug}"><strong>{text}</strong></a>{ref}{top_marker_spacing}{top_marker}'
if slug == index_slug:
format_line = '{prefix}[{index}] <a id="{index_slug}"></a><a href="#{slug}"><strong>{text}</strong></a>{ref}{top_marker_spacing}{top_marker}'
top_marker_spacing = (
' ' *
(LINE_WIDTH - indent - len(index) - len(heading_text) - len(ref_name) - 1 - len(TOP_MARKER) - 2)
)
top_marker = '<a href="#0">{}</a>'.format(TOP_MARKER)
rendered_line = format_line.format(
prefix = (' ' * indent),
index = colorise(index, COLOR_SECTION_INDEX),
index_slug = index_slug,
slug = slug,
text = colorise(heading_text, COLOR_SECTION_NAME),
ref = (
' {{{}}}'.format(colorise(ref, COLOR_SECTION_SLUG))
if ref is not None else
''
),
top_marker = top_marker,
top_marker_spacing = top_marker_spacing,
)
visible_width = indent + index_prefix + 1 + len(section_tracker.slug(index, ref)) + len(ref_name)
if visible_width >= (LINE_WIDTH - len(TOP_MARKER)):
return render_multiline_heading(heading_text, index, indent, noise, extra, ref)
print(rendered_line)
class Types:
@staticmethod
def boolean(value):
if value == 'true':
return True
elif value == 'false':
return False
else:
raise ArgumentError(value)
@staticmethod
def integer(value):
try:
return int(value)
except Exception:
raise ArgumentError(value)
@staticmethod
def string(value):
return value
@staticmethod
def any(value):
return value
@staticmethod
def stringify(something):
if something is Types.boolean:
return 'boolean'
elif something is Types.any:
return 'any'
def build_params(raw, description, required = (), default = None):
params = {}
for key, value in raw:
if not value:
value = None
if key not in description:
raise UnknownArgument(key, value)
if value is None:
value = 'true'
else:
# Cut the '='
value = value[1:]
params[key] = description[key](value)
if default is not None:
for key, value in default.items():
if key not in params:
params[key] = value
for each in required:
if each not in params:
raise MissingArgument(each + ' : ' + Types.stringify(description[each]))
return params
def text_reflow(text, indent):
return '\n'.join(longen(textwrap.wrap(text,
width=(LINE_WIDTH - indent)),
width=(LINE_WIDTH - indent))
)
def text_wrap(text, indent):
lines = text.split('\n')
wrapped_lines = []
wrap_to_length = (LINE_WIDTH - indent)
for each in lines:
if len(each) <= wrap_to_length:
wrapped_lines.append(each)
continue
remaining = each
part = remaining[:wrap_to_length - len(NEWLINE_MARKER)] + NEWLINE_MARKER
remaining = remaining[wrap_to_length - 1:]
wrapped_lines.append(part)
while remaining:
if len(remaining) <= (wrap_to_length - len(INDENT_MARKER)):
part = (INDENT_MARKER + remaining[:wrap_to_length - len(INDENT_MARKER)])
remaining = remaining[wrap_to_length - len(INDENT_MARKER):]
else:
part = (INDENT_MARKER + remaining[:wrap_to_length - 1 - len(INDENT_MARKER)] + NEWLINE_MARKER)
remaining = remaining[wrap_to_length - 1 - len(INDENT_MARKER):]
wrapped_lines.append(part)
return '\n'.join(wrapped_lines)
class RENDERING_MODE_ASCII_RENDERER:
@staticmethod
def render(text, syntax, documented_instructions):
m = KEYWORD_SYNTAX_REGEX.match(text)
if m:
i = int(m.group(1))
if i >= len(syntax):
raise InvalidReference(
'invalid syntax reference: \\syntax{{{}}}'.format(i)
)
return "`{}'".format(syntax[i])
m = KEYWORD_INSTRUCTION_REGEX.match(text)
if m:
instruction = m.group(1)
if instruction not in documented_instructions:
raise UnknownInstruction(instruction)
return instruction
m = KEYWORD_REF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
replacement = (REFS['labels'][name].get('index') if REFS is not None else None)
return (
colorise(replacement, COLOR_REF)
if replacement is not None else
REF_NOT_FOUND_MARKER
)
m = KEYWORD_NAMEREF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\nameref{{{}}}\n'.format(name))
replacement = (REFS['labels'][name].get('name') if REFS is not None else None)
return (
'{} {{{}}}'.format(
colorise(replacement, COLOR_REF),
colorise(name, COLOR_REF),
)
if replacement is not None else
REF_NOT_FOUND_MARKER
)
m = KEYWORD_COLOR_REGEX.match(text)
if m:
color = m.group(1)
content = m.group(2)
return colorise(text, color)
return text
@staticmethod
def length(text, syntax, documented_instructions):
m = KEYWORD_SYNTAX_REGEX.match(text)
if m:
i = int(m.group(1))
if i >= len(syntax):
raise InvalidReference(
'invalid syntax reference: \\syntax{{{}}}'.format(i)
)
return len(syntax[i]) + 2
m = KEYWORD_INSTRUCTION_REGEX.match(text)
if m:
instruction = m.group(1)
if instruction not in documented_instructions:
raise UnknownInstruction(instruction)
return len(instruction)
m = KEYWORD_REF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
replacement = (REFS['labels'][name].get('index') if REFS is not None else None)
return len(replacement or REF_NOT_FOUND_MARKER)
m = KEYWORD_NAMEREF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
replacement = (REFS['labels'][name].get('name') if REFS is not None else None)
replacement = '{} {{{}}}'.format(
replacement,
name,
)
return len(replacement or REF_NOT_FOUND_MARKER)
m = KEYWORD_COLOR_REGEX.match(text)
if m:
content = m.group(2)
return len(content)
return len(text)
class RENDERING_MODE_HTML_ASCII_ART_RENDERER:
@staticmethod
def render(text, syntax, documented_instructions):
m = KEYWORD_SYNTAX_REGEX.match(text)
if m:
i = int(m.group(1))
if i >= len(syntax):
raise InvalidReference(
'invalid syntax reference: \\syntax{{{}}}'.format(i)
)
return "`{}'".format(syntax[i])
m = KEYWORD_INSTRUCTION_REGEX.match(text)
if m:
instruction = m.group(1)
if instruction not in documented_instructions:
raise UnknownInstruction(instruction)
replacement = instruction
for a in REFS['recorded']:
if a[3] is None:
continue
if a[3].get('instruction') and a[1] == instruction.upper():
replacement = '<a href="#{location}">{name}</a>'.format(
location = a[0].replace('.', '-'),
name = instruction,
)
break
return replacement
m = KEYWORD_REF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
location = (name if REFS is not None else REF_NOT_FOUND_MARKER)
replacement = (REFS['labels'][name].get('index') if REFS is not None else REF_NOT_FOUND_MARKER)
replacement = '<a href="#{location}">{name}</a>'.format(
location = location,
name = replacement,
)
return replacement
m = KEYWORD_NAMEREF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: {}\n'.format(name))
location = (name if REFS is not None else REF_NOT_FOUND_MARKER)
replacement = (REFS['labels'][name].get('name') if REFS is not None else REF_NOT_FOUND_MARKER)
replacement = '<a href="#{location}">{name} ({index})</a>'.format(
location = location,
name = replacement,
index = (
REFS['labels'][name].get('index')
if REFS is not None
else REF_NOT_FOUND_MARKER
),
)
return replacement
m = KEYWORD_COLOR_REGEX.match(text)
if m:
color = m.group(1)
content = m.group(2)
return colorise(content, color)
text = text.replace('<', '<').replace('>', '>')
return text
@staticmethod
def length(text, syntax, documented_instructions):
m = KEYWORD_SYNTAX_REGEX.match(text)
if m:
i = int(m.group(1))
if i >= len(syntax):
raise InvalidReference(
'invalid syntax reference: \\syntax{{{}}}'.format(i)
)
return len(syntax[i]) + 2
m = KEYWORD_INSTRUCTION_REGEX.match(text)
if m:
instruction = m.group(1)
if instruction not in documented_instructions:
raise UnknownInstruction(instruction)
return len(instruction)
m = KEYWORD_REF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
replacement = (REFS['labels'][name].get('index') if REFS is not None else None)
return len(replacement or REF_NOT_FOUND_MARKER)
m = KEYWORD_NAMEREF_REGEX.match(text)
if m:
name = m.group(1)
if REFS is not None and name not in REFS['labels']:
raise InvalidReference('invalid reference: \\ref{{{}}}\n'.format(name))
replacement = ('{} ({})'.format(
REFS['labels'][name].get('name'),
REFS['labels'][name].get('index'),
) if REFS is not None else None)
return len(replacement or REF_NOT_FOUND_MARKER)
m = KEYWORD_COLOR_REGEX.match(text)
if m:
content = m.group(2)
return len(content)
return len(text)
class Token:
def __init__(self, text):
self._text = text
def __repr__(self):
return repr(self._text)
def render(self, syntax, documented_instructions):
if RENDERING_MODE == RENDERING_MODE_ASCII_ART:
return RENDERING_MODE_ASCII_RENDERER.render(
text = self._text,
syntax = syntax,
documented_instructions = documented_instructions,
)
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
return RENDERING_MODE_HTML_ASCII_ART_RENDERER.render(
text = self._text,
syntax = syntax,
documented_instructions = documented_instructions,
)
def length(self, syntax, documented_instructions):
if RENDERING_MODE == RENDERING_MODE_ASCII_ART:
return RENDERING_MODE_ASCII_RENDERER.length(
text = self._text,
syntax = syntax,
documented_instructions = documented_instructions,
)
if RENDERING_MODE == RENDERING_MODE_HTML_ASCII_ART:
return RENDERING_MODE_HTML_ASCII_ART_RENDERER.length(
text = self._text,
syntax = syntax,
documented_instructions = documented_instructions,
)
TOKENS_THAT_SHOULD_NOT_BE_PRECEDED_BY_WHITESPACE = (
'.',
',',
')',
)
TOKENS_THAT_SHOULD_NOT_BE_SUCCEEDED_BY_WHITESPACE = (
'(',
)
def simple_join_with_spaces(chunks):
if not chunks:
return ''
new_line = [chunks[0]['rendered']]
for each in chunks[1:]:
text = each['rendered']
if (text[0] not in TOKENS_THAT_SHOULD_NOT_BE_PRECEDED_BY_WHITESPACE) and (new_line[-1] not in
TOKENS_THAT_SHOULD_NOT_BE_SUCCEEDED_BY_WHITESPACE):
new_line.append(' ')
new_line.append(text)
return ''.join(new_line)
def longen_tokenised_line(chunks, width):
length_of_chunks = sum(map(lambda x: x['length'], chunks))
spaces_to_fill = (width - length_of_chunks)
no_of_splits = len(chunks) - 1
spaces_per_split = (spaces_to_fill // (no_of_splits or 1))
spaces_left = (spaces_to_fill - (spaces_per_split * no_of_splits))
no_of_double_spaces = spaces_left
if DEBUG_LONGEN:
sys.stderr.write('length_of_chunks = {}\n'.format(length_of_chunks))
sys.stderr.write('spaces_to_fill = {}\n'.format(spaces_to_fill))
sys.stderr.write('no_of_splits = {}\n'.format(no_of_splits))
sys.stderr.write('spaces_per_split = {}\n'.format(spaces_per_split))
sys.stderr.write('spaces_left = {}\n'.format(spaces_left))
if chunks:
new_line = [chunks[0]['rendered']]
line_length = chunks[0]['length']
else:
new_line = ''
line_length = 0
normal_spacing = (' ' if spaces_per_split == 2 else ' ')
for each in chunks[1:]:
text = each['rendered']
if text[0] not in TOKENS_THAT_SHOULD_NOT_BE_PRECEDED_BY_WHITESPACE:
if no_of_double_spaces:
new_line.append(' ')
line_length += 2
no_of_double_spaces -= 1
else:
new_line.append(normal_spacing)
line_length += 1
new_line.append(text)
line_length += each['length']
new_line = ''.join(new_line)