-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathduplicate_mplibcode_as_examples.py
More file actions
86 lines (72 loc) · 2.39 KB
/
duplicate_mplibcode_as_examples.py
File metadata and controls
86 lines (72 loc) · 2.39 KB
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
#! /usr/bin/env python3
import argparse
import fileinput
import sys
parser = argparse.ArgumentParser()
parser.add_argument("tex_source", help="TeX Source filename")
args = parser.parse_args()
chunks = []
buffer = []
chapter_counter = 0
for line in fileinput.input(files=args.tex_source):
line = line.rstrip()
if line == r'\usepackage{luamplib}':
line = '\\usepackage{luamplib}\n\\usepackage{dwmpcode}'
if line.startswith(r'\contrib'):
buffer.append(line)
chunks.append("\n".join(buffer))
buffer.clear()
elif line.startswith(r'\section{'):
if buffer:
chunks.append("\n".join(buffer))
buffer.clear()
buffer.append(line)
elif line.startswith(r'\chapter{'):
if buffer:
chunks.append("\n".join(buffer))
buffer.clear()
chapter_counter += 1
if chapter_counter > 1:
buffer.append(r"\makeatletter\ifodd\c@page\clearpage\hbox{}\fi\makeatother")
buffer.append(line)
else:
buffer.append(line)
if buffer:
chunks.append("\n".join(buffer))
def get_mplibcode(lines):
'''find the contents of the mplibcode environment'''
mp = []
capture = False
squash = False
for line in lines:
if line.startswith(r'\begin{mplibcode}'):
capture = True
elif line.startswith(r'\end{mplibcode}'):
capture = False
elif line.strip().startswith(r'% DUMP '):
k = eval(f"dict({line.strip()[7:]})")
if "capture" in k:
capture = k["capture"]
if "squash" in k:
squash = k["squash"]
if "replace" in k:
mp.append(k["replace"])
if "comment" in k:
if mp:
previous_leading_space = len(mp[-1]) - len(mp[-1].lstrip())
else:
previous_leading_space = 0
mp.append(' ' * previous_leading_space +
'% ' + ' '.join(k['comment'].split()))
elif capture:
if line or not squash:
mp.append(line)
return '\n'.join(mp)
for i, c in enumerate(chunks):
if c.startswith(r'\section'):
mpcode = get_mplibcode(c.splitlines())
print(rf'''\clearpage
\vbox to\textheight{{\vss\begin{{smallcode}}[xleftmargin=-16pt,xrightmargin=-80pt]
{mpcode}
\end{{smallcode}}\vss}}''')
print(c)