forked from MartinPacker/mdpre
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdpre
executable file
·1581 lines (1250 loc) · 48.7 KB
/
mdpre
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
"""
mdpre - Preprocesses a file into Markdown
First argument is file to write to
Reads from stdin
"""
# TODO: (later) new log instead of sys.stderr.write + verbose
# With log( ) we could replace szs.stderr.write
# With log_verbose( ) we could more the if VERBOSE inside the function
# TODO: Warning - mdpre>(node:29276) [DEP0005]
# DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the
# Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
import os
import sys
import csv
import shutil
import zipfile
import io
# import StringIO
import re
import datetime
from functools import partial
from pathlib import Path
from enum import Enum
import calendar
mdpre_level = "0.6.8"
mdpre_date = "8 March, 2024"
banner = "mdpre Markdown Preprocessor v" + mdpre_level + " (" + mdpre_date + ")"
log = partial(print, file=sys.stderr) # | create log to stderr
monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
]
def log_status(p_line):
log("-" * len(banner))
log(p_line)
log("-" * len(banner) + "\n")
g_output = None
g_wrapInCSV = False
csv_colaligns = []
csv_colwidths = []
in_csv = False
cal_date = (0, 0, 2)
in_cal = False
# Find index of variable in variable list. -1 means "not found"
def find_variable(targetVar):
global vars
foundVar = -1
cursor = 0
for var in vars:
if var[0] == targetVar:
varRecord = var
foundVar = cursor
break
cursor += 1
return foundVar
# Set a variable for the first time - or update it if it already exists
def setOrUpdateVariable(varName, varValue):
global vars
var = parse_def(varName + " " + varValue)
var_index = find_variable(var[0])
if var_index > -1:
# Replace the variable with its new definition
vars[var_index] = var
else:
# Add the variable as it's new
vars.append(var)
class OutputType(Enum):
"""preparation for later usage. support e.g. other outputs like MMD or ADOC"""
MD = 1
class Output(object):
NL = "\n"
output = OutputType.MD
def __init__(self, p_toFile):
self.toFile = None
if hasattr(p_toFile, "write"):
self.toFile = p_toFile
log(f"- opened {p_toFile.name} for writing")
else:
log(f"ERROR: g_output could not find an open file {p_toFile}")
exit_script(g_output, -101)
def close(self):
self.toFile.close()
def write(self, p_text):
if self.output == OutputType.MD:
self.toFile.write(f"{p_text}{self.NL}")
def write_line(self, p_text):
self.write(f"{p_text}{self.NL}")
def formatCSV(self, CSV_lines, colalign, colwidth):
CSV_reader = csv.reader(CSV_lines)
# Find out how many columns and prime CSV_lines
columns = 0
CSV_lines = []
for row in CSV_reader:
columns = max(columns, len(row))
CSV_lines.append(row)
# Extend colalign to cover all columns - now we know how many there are
colalign_len = len(colalign)
for i in range(colalign_len, columns + 1):
colalign.append("l")
# Extend colwidth to cover all columns - now we know how many there are
colwidth_len = len(colwidth)
for i in range(colwidth_len, columns + 1):
colwidth.append(1)
# Now print the table
first_row = True
for row in CSV_lines:
row_text = "|"
cell_prefix = ""
cell_suffix = ""
for col_index, col_text in enumerate(row):
if (col_index == 0) & (col_text.startswith("=rowspan ")):
rowspan2 = col_text.split("!!XYZZY!!")
spanClass = rowspan2[0][9:]
col_text = rowspan2[1][1:-1]
cell_prefix = "<span class=\"" + spanClass +"\">"
cell_suffix = "</span>"
row_text = row_text + cell_prefix + col_text + cell_suffix + "|"
self.write(row_text)
titleUnderline = "|"
if first_row is True:
for col_index in range(columns):
dashes = "-" * (colwidth[col_index])
# NOTE: col_width is ratio not characters
if colalign[col_index] == "r":
titleUnderline = titleUnderline + dashes + ":|"
elif colalign[col_index] == "c":
titleUnderline = titleUnderline + ":" + dashes + ":|"
elif colalign[col_index] == "l":
titleUnderline = titleUnderline + ":" + dashes + "|"
else:
titleUnderline = titleUnderline + dashes + "|"
self.write(titleUnderline)
first_row = False
return
def formatCalendar(self, cal_lines, cal_date, cal_spans, cal_keys, cal_notes):
# Get a calendar month in a 2-dimensional array
cal_year, cal_month, cal_cellHeight = cal_date
c = calendar.TextCalendar(calendar.MONDAY)
daysAndNumbers = c.formatmonth(cal_year, cal_month).split("\n")[1: -1]
# Process the rows into day names and actual day numbers
weeks = []
for rowNumber, row in enumerate(daysAndNumbers):
rawCells = []
row = row.ljust(21)
for d in range(7):
rawCells.append(str(row[d * 3 : d * 3 +3]).lstrip().rstrip())
if rowNumber == 0:
dayNames = rawCells
else:
weeks.append(rawCells)
# Write month line
self.write("|" + monthNames[cal_month - 1] + " " + str(cal_year) + "|||||||")
# Write the table heading
self.write(("|:-:") * 7 + "|")
dayLine = "|"
for dayName in dayNames:
dayLine = dayLine + "**" + dayName + "**|"
self.write(dayLine)
# Write the remaining lines
for week in weeks:
weekLine = "|"
for day in week:
# Figure out if day has a note
if day in cal_notes.keys():
dayNote = "<br/>" + cal_notes[day]
cellLines = len(dayNote.split("<br/>"))
else:
dayNote = ""
cellLines = 1
# Compose day Markdown / HTML
if day in cal_spans.keys():
formattedDay = (
"<span class='"
+ cal_spans[day]
+ "'>"
+ day
+ "</span>"
+ dayNote
)
else:
formattedDay = day + dayNote
# Make blank cell appear
if formattedDay == "":
formattedDay = " "
# Vertically pad
formattedDay = formattedDay + "<br/>" * (cal_cellHeight - cellLines)
# Add day cell to week line
weekLine = weekLine + formattedDay + "|"
# Write week line
self.write(weekLine)
# Write any descriptions
self.write("")
for key in cal_keys.keys():
self.write("* <span class='" + key + "'> </span>" + cal_keys[key])
self.write("")
# Print Table Of Contents down to maximum level
def printTableOfContents(self, minLevel, maxLevel, heading, toc):
self.write_line(heading)
for tocEntryLevel, tocEntryText in toc:
if (tocEntryLevel >= minLevel) & (tocEntryLevel <= maxLevel):
self.write(
("\t" * (tocEntryLevel - minLevel))
+ "* ["
+ tocEntryText
+ "](#"
+ makeLink(tocEntryText)
+ ")",
)
def handle_adjustGraphics(self, line):
adjustedLine = ""
splitStart = line.split("![")
fragment = 0
for s in splitStart:
if fragment == 0:
# Before first ![
adjustedLine = s + "!["
else:
# At first or subsequent ![
endLabelPos = s.find("](")
beginGraphicPos = endLabelPos + 2
adjustedLine += s[:beginGraphicPos]
endGraphicPos = s.find(")")
# Extract original graphic name, including subdirs
graphic = s[beginGraphicPos:endGraphicPos]
# Adjust graphic so it's in the assets subfolder
lastSlash = graphic.rfind("/")
if lastSlash == -1:
adjustedGraphic = "assets/" + graphic
else:
adjustedGraphic = "assets/" + graphic[lastSlash + 1 :]
adjustedLine = (
adjustedLine + adjustedGraphic + ")" + s[endGraphicPos + 1 :]
)
# Copy the file into the text bundle
shutil.copy(graphic, realpath + "/" + adjustedGraphic)
fragment += 1
if wantVerbose is True:
sys.stderr.write("Adjusting >>" + adjustedLine + "<<<\n")
self.write(adjustedLine)
return
##########################
# Class to control loops #
##########################
class LoopController:
def __init__(self, loopType, parent, loopVarName, loopVarValues, loopValue = "", children = []):
self.loopType = loopType
self.parent = parent
self.loopVarName = loopVarName
self.loopVarValues = loopVarValues
self.children = children
self.lineValue = loopValue
self.endForEncountered = False
self.currentIndex = -1
self.valueCount = len(loopVarValues)
####################
# Helper Functions #
####################
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
def parse_colalign(colString, p_separator="\s+"):
cs = colString.rstrip().lstrip()
return re.split(p_separator, cs)
def parse_colwidth(colString, p_separator="\s+"):
cs = colString.rstrip().lstrip()
colwidths = re.split(p_separator, cs)
colwidthInt = []
for c in colwidths:
colwidthInt.append(int(c))
return colwidthInt
def parse_calstart(calString, p_separator="\s+"):
d = calString.rstrip().lstrip()
ym = re.split(p_separator, d)
if len(ym) < 3:
cal_cellHeight = 2
else:
cal_cellHeight = int(ym[2])
return (int(ym[0]), int(ym[1]), cal_cellHeight)
def parse_caldays(spanString, cal_spans, p_separator="\s+"):
sp = spanString.rstrip().lstrip()
words = re.split(p_separator, sp)
for w in range(len(words)):
if w == 0:
# Pick up class name
spanClass = words[w]
else:
# Pick up dates
dayRange = words[w].split("-")
if len(dayRange) == 1:
# Single date specified
dayNumber = dayRange[0]
cal_spans[dayNumber] = spanClass
else:
# Range of dates specified
for dayNumber in range(int(dayRange[0]), int(dayRange[1]) + 1):
cal_spans[str(dayNumber)] = spanClass
return cal_spans
def parse_calkeys(keyString, cal_keys):
keyString = keyString.rstrip().lstrip()
spacePos = keyString.find(" ")
keyName = keyString[:spacePos]
keyValue = keyString[spacePos + 1 :]
cal_keys[keyName] = keyValue
return cal_keys
def parse_calnote(noteString, cal_notes):
noteString = noteString.rstrip().lstrip()
# Pick up single date or range
spacePos = noteString.find(" ")
noteDays = noteString[:spacePos]
# Pick up the note string
noteText = noteString[spacePos + 1 :]
# Pick up dates
dayRange = noteDays.split("-")
if len(dayRange) == 1:
# Single date specified
dayNumber = dayRange[0]
cal_notes[dayNumber] = noteText
else:
# Range of dates specified
for dayNumber in range(int(dayRange[0]), int(dayRange[1]) + 1):
cal_notes[str(dayNumber)] = noteText
return cal_notes
def parse_def(defString):
spacePos = defString.find(" ")
varName = defString[:spacePos]
residue = defString[spacePos + 1 :]
if spacePos == -1:
varType = "F"
varValue = ""
varName = defString
else:
varType = "T"
varValue = residue
return [varName, varType, varValue]
def parse_inc(line):
global vars
targetVar = line[5:-1].lstrip()
foundVar = find_variable(targetVar)
if foundVar > -1:
varRecord = vars[foundVar]
if varRecord[1] != "T":
sys.stderr.write(
"Variable " + targetVar + " is a flag. Cannot be incremented.\n"
)
else:
intVal, OK = intTryParse(varRecord[2])
if OK is False:
sys.stderr.write(
"Variable "
+ targetVar
+ " is not an integer. Cannot be incremented.\n"
)
else:
vars[foundVar] = [targetVar, "T", str(intVal + 1)]
else:
sys.stderr.write(
"Variable " + targetVar + " not found. Cannot be incremented.\n"
)
def parse_dec(line):
global vars
targetVar = line[5:-1].lstrip()
foundVar = find_variable(targetVar)
if foundVar > -1:
varRecord = vars[foundVar]
if varRecord[1] != "T":
sys.stderr.write(
"Variable " + targetVar + " is a flag. Cannot be decremented.\n"
)
else:
intVal, OK = intTryParse(varRecord[2])
if OK is False:
sys.stderr.write(
"Variable "
+ targetVar
+ " is not an integer. Cannot be decremented.\n"
)
else:
vars[foundVar] = [targetVar, "T", str(intVal - 1)]
else:
sys.stderr.write(
"Variable " + targetVar + " not found. Cannot be decremented.\n"
)
# =ifdef encountered
def handle_ifdef(ifdefString):
global ifStack, vars
verbosity = ""
for varName, varType, varValue in vars:
if varName == ifdefString:
# Variable is defined
if wantVerbose is True:
verbosity = "<!--mdpre-ifdef:true:" + varName + "-->"
ifStack.append(True)
return verbosity
# Variable is undefined
ifStack.append(False)
if wantVerbose is True:
verbosity = "<!--mdpre-ifdef:false:" + ifdefString + "-->"
return verbosity
# =ifndef encountered
def handle_ifndef(ifndefString):
global ifStack, vars
verbosity = ""
for varName, varType, varValue in vars:
if varName == ifndefString:
# Variable is defined
if wantVerbose is True:
verbosity = "<!--mdpre-ifndef:false:" + ifndefString + "-->"
ifStack.append(False)
return verbosity
# Variable is undefined
ifStack.append(True)
if wantVerbose is True:
verbosity = "<!--mdpre-ifndef:true:" + ifndefString + "-->"
return verbosity
# =endif encountered
def handle_endif():
global ifStack
if wantVerbose is True:
verbosity = "<!--mdpre-endif:-->"
else:
verbosity = ""
ifStack.pop()
return verbosity
def handle_undef(name):
global vars
for var in vars:
if var[0] == name:
vars.remove(var)
return ["<!--mdpre-undef:found:" + name + "-->"]
return ["<!--mdpre-undef:notfound:" + name + "-->"]
def handle_for(forArguments):
global rootLoopController, currentLoopController
global vars
####################
# Handle arguments #
####################
forArgs=forArguments.split(" ")
# Remove empty members because of multiple spaces
forArgs = [i for i in forArgs if i]
# Remove optional "="
forArgs = [i for i in forArgs if i != "="]
loopIsIn = False
# Parse arguments
argCount = len(forArgs)
if argCount < 3:
sys.stderr.write(f"Syntax error: {forArguments}\n")
sys.stderr.write("Stopping.")
sys.exit()
elif forArgs[1].lower() == "in":
# for / in variant
loopVarname = forArgs[0]
# Get remainder of statement after the variable and "in"
afterIn = forArguments.find(" in ") + 4
rest = forArguments[afterIn:]
# ~Use CSV reader to parse the line
loopValues = csv.reader(io.StringIO(rest), escapechar = "\\", skipinitialspace = True).__next__()
loopIsIn = True
elif argCount == 4:
# for / to - without by
loopVarname = forArgs[0]
loopFirst = int(forArgs[1])
if forArgs[2].lower() != "to":
sys.stderr.write(f"Syntax error: {forArguments}\n")
sys.stderr.write("Stopping.")
sys.exit()
loopLast = int(forArgs[3])
loopBy = 1
else:
# for / to / by
loopVarname = forArgs[0]
loopFirst = int(forArgs[1])
if forArgs[2].lower() != "to":
sys.stderr.write(f"Syntax error: {forArguments}\n")
sys.stderr.write("Stopping.")
sys.exit()
loopLast = int(forArgs[3])
if forArgs[4].lower() != "by":
sys.stderr.write(f"Syntax error: {forArguments}\n")
sys.stderr.write("Stopping.")
sys.exit()
loopBy = int(forArgs[5])
# Only use range to make list if not "in" form
if loopIsIn is False:
# Make values into a list
loopLast = loopLast + loopBy
loopValues = [*range(loopFirst, loopLast, loopBy)]
##############################
# Set up the loop controller #
##############################
# Register this for loop
loopController = LoopController("for", None, loopVarname, loopValues,"", [])
if rootLoopController == None:
# Start the tree of loops
rootLoopController = loopController
currentLoopController = loopController
else:
if currentLoopController != None:
# Add loop controller to tree as a child at parent's position
currentLoopController.children.append(loopController)
loopController.parent = currentLoopController
currentLoopController = loopController
# Set the loop variable to its initial value
setOrUpdateVariable(loopVarname, str(loopValues[0]))
return "<!--mdpre-for:" + forArguments + "-->"
def _printLoopControllers(loopController, level):
print(" " * level + "--------------------")
print(" " * level + "Type: " + loopController.loopType)
print(" " * level + "Self: " + str(loopController))
print(" " * level + "Parent: " + str(loopController.parent))
print(" " * level + "End For: " + str(loopController.endForEncountered))
print(" " * level + "Variable: " + loopController.loopVarName)
for value in loopController.loopVarValues:
print(" " * level + str(value))
if loopController.loopType == "line":
print(" " * level + "Line value: " +loopController.lineValue)
elif loopController.loopType == "include":
print(" " * level + "Filename: " +loopController.lineValue[9:])
else:
print(" " * level + "Children:")
for child in loopController.children:
print(" " * level + str(child))
print(" " * level + "--------------------")
print("\n")
for child in loopController.children:
_printLoopControllers(child, level + 1)
print("\n\n")
def printLoopControllers():
if rootLoopController is not None:
_printLoopControllers(rootLoopController, 0)
else:
print("No loop controllers")
def interpretLoops(input_file2, loopController):
global vars
global rootLoopController, currentLoopController
#printLoopControllers()
# Loop over the loop variable's values
for loopVarValue in loopController.loopVarValues:
# Set the loop variable's current value
setOrUpdateVariable(loopController.loopVarName, str(loopVarValue))
# Add the children of this loop controller
for child in loopController.children:
if child.loopType == "line":
line = substitute_variables(child.lineValue)
input_file2.append(line)
elif child.loopType == "include":
line = substitute_variables(child.lineValue)
include_name = substitute_variables(line[9:].rstrip().lstrip())
# Check for recursive inclusion
if include_name in includeStack:
sys.stderr.write(
f"File '{include_name}' recursively included. Stopping."
)
sys.exit()
if wantVerbose is True:
input_file2.append(
"<!--mdpre-embed-start:"
+ str(embedLevel)
+ ":"
+ include_name
+ "-->"
)
# Not recursive so add include file name to stack
includeStack.append(include_name)
try:
with open(include_name, "r") as f:
stopIt, include_lines = parse_include(f.readlines())
except:
sys.stderr.write(f"File {include_name} missing. Terminating.\n")
exit()
for line2 in include_lines:
input_file2.append(line2)
if wantVerbose is True:
input_file2.append(
"<!--mdpre-embed-stop:"
+ str(embedLevel)
+ ":"
+ include_name
+ "-->"
)
if stopIt is True:
return [stopIt, input_file2, vars]
else:
input_file2 = interpretLoops(input_file2, child)
if loopController == rootLoopController:
rootLoopController = None
currentLoopController = None
return input_file2
def handle_endfor(endforArguments, input_file2):
global rootLoopController, currentLoopController
global vars
loopController = currentLoopController
# Flag "end for" encountered
currentLoopController.endForEncountered = True
# Back to processing parent
currentLoopController = currentLoopController.parent
# printLoopControllers()
# If all the way up to root loop controller has met "end for" interpret the loop set
if rootLoopController.endForEncountered:
input_file2 = interpretLoops(input_file2, rootLoopController)
return ["<!--mdpre-endfor:" + endforArguments + "-->", input_file2]
def parse_include(input_file):
global rootLoopController, currentLoopController
global embedLevel
global ifStack
global vars
embedLevel += 1
input_file2 = []
for line in input_file:
if line.startswith("=stop") is True:
return [True, input_file2]
# Substitute any symbols into the included filename
unsubstitutedLine = line
line = substitute_variables(line)
if ifStack[-1] is True:
if (line.startswith("=include ")) & (rootLoopController == None):
include_name = substitute_variables(line[9:].rstrip().lstrip())
# Check for recursive inclusion
if include_name in includeStack:
sys.stderr.write(
f"File '{include_name}' recursively included. Stopping."
)
sys.exit()
# Not recursive so add include file name to stack
includeStack.append(include_name)
if wantVerbose is True:
input_file2.append(
"<!--mdpre-embed-start:"
+ str(embedLevel + 1)
+ ":"
+ include_name
+ "-->"
)
try:
with open(include_name, "r") as f:
stopIt, include_lines = parse_include(f.readlines())
except:
sys.stderr.write(f"File {include_name} missing. Terminating.\n")
exit()
for line2 in include_lines:
input_file2.append(line2)
if wantVerbose is True:
input_file2.append(
"<!--mdpre-embed-stop:"
+ str(embedLevel + 1)
+ ":"
+ include_name
+ "-->"
)
if stopIt is True:
return [stopIt, input_file2, vars]
elif line.startswith("=def ") is True:
var = parse_def(line[5:-1].lstrip())
var_index = find_variable(var[0])
if var_index > -1:
# Replace the variable with its new definition
vars[var_index] = var
else:
# Add the variable as it's new
vars.append(var)
if wantVerbose is True:
varName, varType, varValue = var
if var_index > -1:
redefined =" (redefined)"
else:
redefined =""
input_file2.append(
"<!--mdpre-def:"
+ varName
+ ":"
+ varType
+ ":"
+ varValue
+ redefined
+ "-->"
)
elif line.startswith("=for ") is True:
verbosity = handle_for(line[5:-1].lstrip())
if wantVerbose is True:
input_file2.append(verbosity)
elif line.startswith("=endfor") is True:
verbosity, input_file2 = handle_endfor(line[8:-1].lstrip(), input_file2)
if wantVerbose is True:
input_file2.append(verbosity)
elif currentLoopController != None:
# There is an active loop
if line.startswith("=include "):
# Add current line to loop lines - as an include
lineController = LoopController("include", None, "", [], unsubstitutedLine, [])
currentLoopController.children.append(lineController)
else:
# Add current line to loop lines - as an ordinary line
lineController = LoopController("line", None, "", [], unsubstitutedLine, [])
currentLoopController.children.append(lineController)
elif line.startswith("=inc ") is True:
parse_inc(line)
elif line.startswith("=dec ") is True:
parse_dec(line)
elif line.startswith("=undef") is True:
varName = line[7:-1].lstrip()
verbosity = handle_undef(varName)
if wantVerbose is True:
input_file2.append(verbosity)
elif line.startswith("=ifdef ") is True:
verbosity = handle_ifdef(line[7:].lstrip().rstrip())
if wantVerbose is True:
input_file2.append(verbosity)
elif line.startswith("=ifndef ") is True:
verbosity = handle_ifndef(line[8:].lstrip().rstrip())
if wantVerbose is True:
input_file2.append(verbosity)
elif line.startswith("=endif") is False:
input_file2.append(line)
if line.startswith("=endif") is True:
verbosity = handle_endif()
if wantVerbose is True:
input_file2.append(verbosity)
# Pop this file from the stack
includeStack.pop()
embedLevel -= 1
return [False, input_file2]
def replace_varname(varName):
global vars
for var in vars:
if (var[0] == varName) & (var[1] == "T"):
# A match so return the value
return var[2]
return "&" + varName + ";"
def substitute_variables(input_line):
fragments = input_line.split("&")
ampersands = len(fragments) - 1
# Output line starts with fragment before the first ampersand
output_line = fragments[0]
# Go through the remaining fragments, extracting their data
for f in range(ampersands):
fragment = fragments[f + 1]
semicolonPos = fragment.find(";")
if semicolonPos == -1:
# No terminating semicolon
output_line += "&" + fragment
else:
# Terminating semicolon so extract variable name
varName = fragment[:semicolonPos]
tail = fragment[semicolonPos + 1 :]
output_line += replace_varname(varName) + tail
return output_line
def handle_linejoins(input_file):
input_file2 = []
output_line = ""
pending = False
line_count = len(input_file)
for line_number, line in enumerate(input_file):
output_line += line
if line_number < line_count - 1:
next_line = input_file[line_number + 1]
else:
next_line = ""
if line.endswith("\\\n"):
# Next line should be concatenated to this one
output_line = output_line[:-2]
pending = True
elif next_line.startswith("<br/>"):
output_line = output_line[:-1]
pending = True
else:
# Next line shouldn't be concatenated to this one
input_file2.append(output_line)
output_line = ""
pending = False
if pending is True:
input_file2.append(output_line)
return input_file2