summaryrefslogtreecommitdiff
path: root/tools/man-gen.py
blob: 30ade8a08e63c5b09a9be71863993eee6373bdee (plain) (blame)
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
from sys import argv

infn, outfn = argv[1:]

inf = open(infn, 'r')

title = infn[infn.rfind('/')+1:infn.rfind('.')]
lines = []
links = []

coutl = bytes(0)
cllen = 0
cword = ''
ccol  = 0x0f

def word_end():
  global cword, cllen, coutl

  if cword == '':
    return

  if cllen + len(cword) > 80:
    line_end()

  cllen += len(cword)
  coutl += bytes(cword, 'ascii')
  cword = ''

  if cllen == 80:
    line_end()

def line_end():
  global lines, cllen, coutl, ccol

  if len(lines) == 0 and cllen == 0:
    return
  coutl += bytes([0x20] * (80 - cllen))

  lines.append(coutl)
  coutl = bytes(0)
  cllen = 0
  if ccol != 0x0f:
    coutl += bytes([ccol | 0x80])

while True:
  ch = inf.read(1)
  if ch == '':
    word_end()
    line_end()
    break

  elif ch == '\\':
    word_end()

    cmd = ''
    while ch != '{':
      cmd += ch
      ch = inf.read(1)
    cmd = cmd[1:]

    content = ''
    while ch != '}':
      content += ch
      ch = inf.read(1)
    content = content[1:]

    if cmd == 'title':
      title = content
    elif cmd == 'link':
      lto = content
      cpos = content.rfind(':')
      if cpos != -1:
        lto = content[cpos+1:]
        content = content[:cpos]
      links.append((len(lines), cllen, len(content), lto))
      coutl += bytes([0x89])
      cword = content
      word_end()
      coutl += bytes([0x8f])
    elif cmd == 'color':
      ncol = int(content, base=16)
      if ccol != ncol:
        ccol = ncol
        coutl += bytes([ccol | 0x80])

  elif ch == ' ':
    word_end()
    if cllen != 0:
      coutl += bytes([0x20])
      cllen += 1

  elif ch == '\n':
    word_end()
    line_end()

  else:
    cword += ch

inf.close()

def dword(n):
  return bytes([n % 256, (n // 256) % 256, (n // 65536) % 256, n // 16777216])

outf = open(outfn, 'wb')

outf.write(dword(len(title)))
outf.write(bytes(title, 'ascii'))
outf.write(bytes([0]))

outf.write(dword(len(links)))

ltable = bytes(0)
for link in links:
  line, scol, tlen, fpto = link

  ltable += dword(line)
  ltable += bytes([scol, tlen])
  ltable += dword(len(fpto))
  ltable += bytes(fpto, 'ascii')
  ltable += bytes([0])

outf.write(dword(len(ltable)))
outf.write(ltable)

outf.write(dword(len(lines)))

off = 4 + len(title) + 1 + 4 + 4 + len(ltable) + 4 + len(lines) * 4
for line in lines:
  outf.write(dword(off))
  off += len(line)

for line in lines:
  outf.write(line)

outf.close()