summaryrefslogtreecommitdiff
path: root/ftt-docgen
blob: 10980a54c61de41cf3667f15b7ffe88399faa62a (plain)
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
#!/usr/bin/env python3

import argparse
import copy
import os
import re
import subprocess
import sys
import tempfile

import CommonMark_bkrs as CommonMark
import yaml

def format_keyword(line):
    words = line.split(' ')
    keyword = words[0]
    return '*{}* '.format(keyword) + line[len(keyword):]

def indent(line):
    prefix = ' ' * 4
    return '>{}{}'.format(prefix, line)

def format_match(keyword, line, m):
    n = len(m.groups())
    if n > 0:
        end = 0
        parts = []
        for i in range(1, n+1):
            parts.append(line[end:m.start(i)])
            thispart = line[m.start(i) : m.end(i)]
            parts.append('*{}*'.format(thispart))
            end = m.end(i)
        line = ''.join(parts) + line[m.end(n):]
    line = '{} {}'.format(keyword, line)
    return line

def format_backtick(c):
    if c == "`":
        return "`"
    return c

def format_chars(s):
    return ''.join(format_backtick(c) for c in s)

def format_scenario_step(bind, line, prev_keyword):
    debug('line: %r' % line)

    words = line.split()
    if not words:
        return line.strip(), prev_keyword

    keyword = words[0]
    real_keyword = keyword
    if keyword.lower() == 'and':
        if prev_keyword is None:
            sys.exit('AND may not be used on first step in snippet')
        real_keyword = prev_keyword
    debug('keyword: %r' % keyword)
    line = line[len(keyword):].lstrip()
    debug('line: %r' % line)

    for b in bind:
        debug('consider binding %r' % b)
        if real_keyword not in b:
            debug('keyword %r not in binding' % real_keyword)
            continue
        m = re.match(b[real_keyword.lower()], line, re.I | re.M)
        debug('m: %r' % m)
        if m and m.end() == len(line):
            debug('match: %r' % line)
            debug('     : %r' % m.groupdict())
            line = format_match(keyword, line, m)
            break
    else:
        line = '{} {}'.format(keyword, line)

    if not line.strip():
        return line

    line = format_chars(line)

    debug('pre-indent: %r' % line)
    lines = line.splitlines()
    if len(lines) > 1:
        line = '\n'.join([lines[0] + '  '] + [indent(x) + '  ' for x in lines[1:]])
    debug('post-indent: %r' % line)

    return format_keyword(line), real_keyword

def count_leading_whitespace(s):
    n = 0
    while s and s[0].isspace():
        n += 1
        s = s[1:]
    return n

def skip_indent(s, indent):
    while indent > 0 and s and s[0].isspace():
        s = s[1:]
        indent -= 1
    return s

def get_steps(lines):
    step = []
    indent = None
    for line in lines:
        if not line.strip():
            yield '\n'.join(step)
            step = []
            indent = None
        elif line[0].isspace():
            if indent is None:
                indent = count_leading_whitespace(line)
            line = skip_indent(line, indent)
            step.append(line)
        else:
            yield '\n'.join(step)
            step = [line]
            indent = None
    if step:
        yield '\n'.join(step)

def format_fable_snippet(bind, lines):
#    debug('snippet: %r' % lines)
    prev_keyword = None
    output = []
    for step in get_steps(lines):
        debug('step: %r' % step)
        ln, prev_keyword = format_scenario_step(bind, step, prev_keyword)
        output.append(ln)
    return output

def is_fable_snippet(o):
    prefix = "```fable\n"
    return o.t == 'FencedCode' and o.info == 'fable'

def is_heading(o):
    return o.t =='ATXHeader'

def write_document(bind, f, o):
    pass

def write_atxheader(bind, f, o):
    f.write('{} {}\n\n'.format('#' * o.level, ' '.join(o.strings)))

def write_setextheader(bind, f, o):
    chars = {
        1: '=',
        2: '-',
    }
    c = chars[o.level]
    f.write('{}\n{}\n\n'.format(' '.join(o.strings), c * 72))

def write_paragraph(bind, f, o):
    for s in o.strings:
        f.write('{}\n'.format(s))
    f.write('\n')

def write_fable_snippet(bind, f, o):
    for line in format_fable_snippet(bind, o.strings[1:]):
        f.write('> {}  \n'.format(line))
    f.write('\n')

def write_not_fable_snippet(bind, f, o):
    fence = o.fence_char * o.fence_length
    lang = o.strings[0]
    f.write('{}{}\n'.format(fence, lang))
    for line in o.strings[1:]:
        f.write('{}\n'.format(line))
    f.write('{}\n'.format(fence))
    f.write('\n')

def write_fencedcode(bind, f, o):
    if is_fable_snippet(o):
        write_fable_snippet(bind, f, o)
    else:
        write_not_fable_snippet(bind, f, o)

def write_indentedcode(bind, f, o):
    for s in o.strings:
        f.write('    {}\n'.format(s))
    f.write('\n')

def write_horizontalrule(bind, f, o):
    f.write('---\n')

def write_list(bind, f, o):
    pass

def write_listitem(bind, f, o):
    bullet = o.list_data['bullet_char']
    offset = o.list_data['marker_offset']
    padding = o.list_data['padding']
    prefix = '{}{} '.format(' ' * offset, bullet)
    cont = ' ' * padding
    for c in o.children:
        prepend = prefix
        for s in c.strings:
            f.write('{}{}\n'.format(prepend, s))
            prepend = cont
    if o.last_line_blank:
        f.write('\n')
    return True

def write_referencedef(bind, f, o):
    for s in o.strings:
        f.write('{}\n'.format(s))

writers = {
    'Document': write_document,
    'ATXHeader': write_atxheader,
    'SetextHeader': write_setextheader,
    'Paragraph': write_paragraph,
    'FencedCode': write_fencedcode,
    'IndentedCode': write_indentedcode,
    'HorizontalRule': write_horizontalrule,
    'List': write_list,
    'ListItem': write_listitem,
    'ReferenceDef': write_referencedef,
}

def write(bind, f, o):
    if o.t not in writers:
        debug('{} not known'.format(repr(o.t)))
        return
    writer = writers[o.t]
    return writer(bind, f, o)

def walk(o, func):
    done = func(o)
    if not done:
        for c in o.children:
            walk(c, func)

def infer_basename(markdowns):
    root, ext = os.path.splitext(markdowns[0])
    if ext not in ['.md', '.mdwn']:
        sys.exit('Input filenames must end in .md or .mdwn')
    return root

# This only allows one markdown filename. This is crap. But I can't
# get it work with -- otherwise. What I want is for the following to
# work:
#    ftt-docgetn --pdf foo.md bar.md -- --pandoc-arg --other-pandoc-arg
# but I can't make it work.
def parse_cli():
    p = argparse.ArgumentParser()
    p.add_argument('--pdf', action='store_true')
    p.add_argument('--html', action='store_true')
    p.add_argument('markdown', nargs=1)
    args, pandoc_args = p.parse_known_args()
    return args, pandoc_args

def debug(msg):
    if False:
        sys.stderr.write('DEBUG: {}\n'.format(msg))
        sys.stderr.flush()

def pandoc(args):
    argv = ['ftt-pandoc'] + args
    subprocess.check_call(argv)

args, pandoc_args = parse_cli()

text = ''.join(open(filename).read() for filename in args.markdown)

basename = infer_basename(args.markdown)
dirname = os.path.dirname(basename)

with open(basename + '.yaml') as f:
    bindings = yaml.safe_load(f)


start = '---\n'
end = '\n...\n'
if text.startswith(start):
    meta, text = text.split(end, 1)
    meta += end + '\n'
else:
    meta = ''

parser = CommonMark.DocParser()
ast = parser.parse(text)

if args.pdf or args.html:
    with tempfile.NamedTemporaryFile(mode='w', dir=dirname) as f:
        f.write(meta)
        walk(ast, lambda o: write(bindings, f, o))
        f.flush()
        if args.pdf:
            pandoc(['-o', basename + '.pdf', f.name] + pandoc_args)
        elif args.html:
            pandoc(['-o', basename + '.html', f.name] + pandoc_args)
else:
    sys.stdout.write(meta)
    walk(ast, lambda o: write(bindings, sys.stdout, o))