@@ -1,7 +1,19 @@
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+
110import sys
211import json
312
413def walk(x, action, format = ""):
14+ """Walk a tree, applying an action to every object.
15+ Returns a modified tree.
16+ """
517 if isinstance(x, list):
618 array = []
719 for item in x:
@@ -27,6 +39,20 @@ def walk(x, action, format = ""):
2739 return x
2840
2941def toJSONFilter(action):
42+ """Converts an action into a filter that reads a JSON-formatted
43+ pandoc document from stdin, transforms it by walking the tree
44+ with the action, and returns a new JSON-formatted pandoc document
45+ to stdout. The argument is a function action(key, value, format),
46+ where key is the type of the pandoc object (e.g. 'Str', 'Para'),
47+ value is the contents of the object (e.g. a string for 'Str',
48+ a list of inline elements for 'Para'), and format is the target
49+ output format (which will be taken for the first command line
50+ argument if present). If the function returns None, the object
51+ to which it applies will remain unchanged. If it returns an
52+ object, the object will be replaced. If it returns a list, the
53+ list will be spliced in to the list to which the target object
54+ belongs. (So, returning an empty list deletes the object.)
55+ """
3056 doc = json.loads(sys.stdin.read())
3157 if len(sys.argv) > 1:
3258 format = sys.argv[1]
@@ -36,12 +62,19 @@ def toJSONFilter(action):
3662 json.dump(altered, sys.stdout)
3763
3864def rawInline(format, s):
65+ """Returns a 'RawInline' inline object.
66+ """
3967 return {"RawInline": [{"unFormat": format}, s]}
4068
4169def rawBlock(format, s):
70+ """Returns a 'RawBlock' inline object.
71+ """
4272 return {"RawBlock": [{"unFormat": format}, s]}
4373
4474def attributes(attrs):
75+ """Returns an attribute list, constructed from the
76+ dictionary attrs.
77+ """
4578 attrs = attrs or []
4679 ident = attrs["id"] or ""
4780 classes = attrs["classes"] or []