pandocfilters.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Author: John MacFarlane <jgm@berkeley.edu>
  2. # Copyright: (C) 2013 John MacFarlane
  3. # License: BSD3
  4. """
  5. Functions to aid writing python scripts that process the pandoc
  6. AST serialized as JSON.
  7. """
  8. import codecs
  9. import hashlib
  10. import io
  11. import json
  12. import os
  13. import sys
  14. # some utility-functions: make it easier to create your own filters
  15. def get_filename4code(module, content, ext=None):
  16. """Generate filename based on content
  17. The function ensures that the (temporary) directory exists, so that the
  18. file can be written.
  19. Example:
  20. filename = get_filename4code("myfilter", code)
  21. """
  22. imagedir = module + "-images"
  23. fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest()
  24. try:
  25. os.mkdir(imagedir)
  26. sys.stderr.write('Created directory ' + imagedir + '\n')
  27. except OSError:
  28. pass
  29. if ext:
  30. fn += "." + ext
  31. return os.path.join(imagedir, fn)
  32. def get_value(kv, key, value = None):
  33. """get value from the keyvalues (options)"""
  34. res = []
  35. for k, v in kv:
  36. if k == key:
  37. value = v
  38. else:
  39. res.append([k, v])
  40. return value, res
  41. def get_caption(kv):
  42. """get caption from the keyvalues (options)
  43. Example:
  44. if key == 'CodeBlock':
  45. [[ident, classes, keyvals], code] = value
  46. caption, typef, keyvals = get_caption(keyvals)
  47. ...
  48. return Para([Image([ident, [], keyvals], caption, [filename, typef])])
  49. """
  50. caption = []
  51. typef = ""
  52. value, res = get_value(kv, u"caption")
  53. if value is not None:
  54. caption = [Str(value)]
  55. typef = "fig:"
  56. return caption, typef, res
  57. def get_extension(format, default, **alternates):
  58. """get the extension for the result, needs a default and some specialisations
  59. Example:
  60. filetype = get_extension(format, "png", html="svg", latex="eps")
  61. """
  62. try:
  63. return alternates[format]
  64. except KeyError:
  65. return default
  66. # end of utilities
  67. def walk(x, action, format, meta):
  68. """Walk a tree, applying an action to every object.
  69. Returns a modified tree. An action is a function of the form
  70. `action(key, value, format, meta)`, where:
  71. * `key` is the type of the pandoc object (e.g. 'Str', 'Para') `value` is
  72. * the contents of the object (e.g. a string for 'Str', a list of
  73. inline elements for 'Para')
  74. * `format` is the target output format (as supplied by the
  75. `format` argument of `walk`)
  76. * `meta` is the document's metadata
  77. The return of an action is either:
  78. * `None`: this means that the object should remain unchanged
  79. * a pandoc object: this will replace the original object
  80. * a list of pandoc objects: these will replace the original object; the
  81. list is merged with the neighbors of the orignal objects (spliced into
  82. the list the original object belongs to); returning an empty list deletes
  83. the object
  84. """
  85. if isinstance(x, list):
  86. array = []
  87. for item in x:
  88. if isinstance(item, dict) and 't' in item:
  89. res = action(item['t'],
  90. item['c'] if 'c' in item else None, format, meta)
  91. if res is None:
  92. array.append(walk(item, action, format, meta))
  93. elif isinstance(res, list):
  94. for z in res:
  95. array.append(walk(z, action, format, meta))
  96. else:
  97. array.append(walk(res, action, format, meta))
  98. else:
  99. array.append(walk(item, action, format, meta))
  100. return array
  101. elif isinstance(x, dict):
  102. for k in x:
  103. x[k] = walk(x[k], action, format, meta)
  104. return x
  105. else:
  106. return x
  107. def toJSONFilter(action):
  108. """Like `toJSONFilters`, but takes a single action as argument.
  109. """
  110. toJSONFilters([action])
  111. def toJSONFilters(actions):
  112. """Generate a JSON-to-JSON filter from stdin to stdout
  113. The filter:
  114. * reads a JSON-formatted pandoc document from stdin
  115. * transforms it by walking the tree and performing the actions
  116. * returns a new JSON-formatted pandoc document to stdout
  117. The argument `actions` is a list of functions of the form
  118. `action(key, value, format, meta)`, as described in more
  119. detail under `walk`.
  120. This function calls `applyJSONFilters`, with the `format`
  121. argument provided by the first command-line argument,
  122. if present. (Pandoc sets this by default when calling
  123. filters.)
  124. """
  125. try:
  126. input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
  127. except AttributeError:
  128. # Python 2 does not have sys.stdin.buffer.
  129. # REF: https://stackoverflow.com/questions/2467928/python-unicodeencode
  130. input_stream = codecs.getreader("utf-8")(sys.stdin)
  131. source = input_stream.read()
  132. if len(sys.argv) > 1:
  133. format = sys.argv[1]
  134. else:
  135. format = ""
  136. sys.stdout.write(applyJSONFilters(actions, source, format))
  137. def applyJSONFilters(actions, source, format=""):
  138. """Walk through JSON structure and apply filters
  139. This:
  140. * reads a JSON-formatted pandoc document from a source string
  141. * transforms it by walking the tree and performing the actions
  142. * returns a new JSON-formatted pandoc document as a string
  143. The `actions` argument is a list of functions (see `walk`
  144. for a full description).
  145. The argument `source` is a string encoded JSON object.
  146. The argument `format` is a string describing the output format.
  147. Returns a the new JSON-formatted pandoc document.
  148. """
  149. doc = json.loads(source)
  150. if 'meta' in doc:
  151. meta = doc['meta']
  152. elif doc[0]: # old API
  153. meta = doc[0]['unMeta']
  154. else:
  155. meta = {}
  156. altered = doc
  157. for action in actions:
  158. altered = walk(altered, action, format, meta)
  159. return json.dumps(altered)
  160. def stringify(x):
  161. """Walks the tree x and returns concatenated string content,
  162. leaving out all formatting.
  163. """
  164. result = []
  165. def go(key, val, format, meta):
  166. if key in ['Str', 'MetaString']:
  167. result.append(val)
  168. elif key == 'Code':
  169. result.append(val[1])
  170. elif key == 'Math':
  171. result.append(val[1])
  172. elif key == 'LineBreak':
  173. result.append(" ")
  174. elif key == 'SoftBreak':
  175. result.append(" ")
  176. elif key == 'Space':
  177. result.append(" ")
  178. walk(x, go, "", {})
  179. return ''.join(result)
  180. def attributes(attrs):
  181. """Returns an attribute list, constructed from the
  182. dictionary attrs.
  183. """
  184. attrs = attrs or {}
  185. ident = attrs.get("id", "")
  186. classes = attrs.get("classes", [])
  187. keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
  188. return [ident, classes, keyvals]
  189. def elt(eltType, numargs):
  190. def fun(*args):
  191. lenargs = len(args)
  192. if lenargs != numargs:
  193. raise ValueError(eltType + ' expects ' + str(numargs) +
  194. ' arguments, but given ' + str(lenargs))
  195. if numargs == 0:
  196. xs = []
  197. elif len(args) == 1:
  198. xs = args[0]
  199. else:
  200. xs = list(args)
  201. return {'t': eltType, 'c': xs}
  202. return fun
  203. # Constructors for block elements
  204. Plain = elt('Plain', 1)
  205. Para = elt('Para', 1)
  206. CodeBlock = elt('CodeBlock', 2)
  207. RawBlock = elt('RawBlock', 2)
  208. BlockQuote = elt('BlockQuote', 1)
  209. OrderedList = elt('OrderedList', 2)
  210. BulletList = elt('BulletList', 1)
  211. DefinitionList = elt('DefinitionList', 1)
  212. Header = elt('Header', 3)
  213. HorizontalRule = elt('HorizontalRule', 0)
  214. Table = elt('Table', 5)
  215. Div = elt('Div', 2)
  216. Null = elt('Null', 0)
  217. # Constructors for inline elements
  218. Str = elt('Str', 1)
  219. Emph = elt('Emph', 1)
  220. Strong = elt('Strong', 1)
  221. Strikeout = elt('Strikeout', 1)
  222. Superscript = elt('Superscript', 1)
  223. Subscript = elt('Subscript', 1)
  224. SmallCaps = elt('SmallCaps', 1)
  225. Quoted = elt('Quoted', 2)
  226. Cite = elt('Cite', 2)
  227. Code = elt('Code', 2)
  228. Space = elt('Space', 0)
  229. LineBreak = elt('LineBreak', 0)
  230. Math = elt('Math', 2)
  231. RawInline = elt('RawInline', 2)
  232. Link = elt('Link', 3)
  233. Image = elt('Image', 3)
  234. Note = elt('Note', 1)
  235. SoftBreak = elt('SoftBreak', 0)
  236. Span = elt('Span', 2)