@@ -1,75 +0,0 @@
1−# Author: John MacFarlane <jgm@berkeley.edu>
2−# Copyright: (C) 2013 John MacFarlane
3−# License: GPL version 2 or higher
4−
5−"""
6−Functions to aid writing python scripts that process the pandoc
7−AST serialized as JSON.
8−"""
9−
10−import sys
11−import json
12−
13−def walk(x, action, format = ""):
14− """Walk a tree, applying an action to every object.
15− Returns a modified tree.
16− """
17− if isinstance(x, list):
18− array = []
19− for item in x:
20− if isinstance(item, dict):
21− if item == {}:
22− array.append(walk(item, action, format))
23− else:
24− for k in item:
25− res = action(k, item[k], format)
26− if res is None:
27− array.append(walk(item, action, format))
28− elif isinstance(res, list):
29− for z in res:
30− array.append(walk(z, action, format))
31− else:
32− array.append(walk(res, action, format))
33− else:
34− array.append(walk(item, action, format))
35− return array
36− elif isinstance(x, dict):
37− obj = {}
38− for k in x:
39− obj[k] = walk(x[k], action, format)
40− return obj
41− else:
42− return x
43−
44−def toJSONFilter(action):
45− """Converts an action into a filter that reads a JSON-formatted
46− pandoc document from stdin, transforms it by walking the tree
47− with the action, and returns a new JSON-formatted pandoc document
48− to stdout. The argument is a function action(key, value, format),
49− where key is the type of the pandoc object (e.g. 'Str', 'Para'),
50− value is the contents of the object (e.g. a string for 'Str',
51− a list of inline elements for 'Para'), and format is the target
52− output format (which will be taken for the first command line
53− argument if present). If the function returns None, the object
54− to which it applies will remain unchanged. If it returns an
55− object, the object will be replaced. If it returns a list, the
56− list will be spliced in to the list to which the target object
57− belongs. (So, returning an empty list deletes the object.)
58− """
59− doc = json.loads(sys.stdin.read())
60− if len(sys.argv) > 1:
61− format = sys.argv[1]
62− else:
63− format = ""
64− altered = walk(doc, action, format)
65− json.dump(altered, sys.stdout)
66−
67−def attributes(attrs):
68− """Returns an attribute list, constructed from the
69− dictionary attrs.
70− """
71− attrs = attrs or []
72− ident = attrs["id"] or ""
73− classes = attrs["classes"] or []
74− keyvals = [x for x in attrs and x != "classes" and x != "id"]
75− return [ident, classes, keyvals]