git.iko.soy/typeable/pandoc
on 0b5156c help sign in
50 lines 1.4 kB history raw
1#!/usr/bin/env python
3"""
4Pandoc filter to process code blocks with class "abc" containing
5ABC notation into images. Assumes that abcm2ps and ImageMagick's
6convert are in the path. Images are put in the abc-images directory.
7"""
9import hashlib
10import os
11import sys
12from pandoc import toJSONFilter
13from subprocess import Popen, PIPE, call
15imagedir = "abc-images"
17def sha1(x):
18 return hashlib.sha1(x).hexdigest()
20def abc2eps(abc, filetype, outfile):
21 p = Popen(["abcm2ps", "-O", outfile + '.eps', "-"],stdin=PIPE)
22 p.stdin.write(abc)
23 p.communicate()
24 p.stdin.close()
25 call(["convert", outfile + '.eps', outfile + '.' + filetype])
27def abc(key, value, format):
28 if key == 'CodeBlock':
29 [[ident,classes,keyvals], code] = value
30 if "abc" in classes:
31 outfile = imagedir + '/' + sha1(code)
32 if format == "html":
33 filetype = "png"
34 elif format == "latex":
35 filetype = "pdf"
36 else:
37 filetype = "png"
38 src = outfile + '.' + filetype
39 if not os.path.isfile(src):
40 try:
41 os.mkdir(imagedir)
42 sys.stderr.write('Created directory ' + imagedir + '\n')
43 except OSError:
44 pass
45 abc2eps(code, filetype, outfile)
46 sys.stderr.write('Created image ' + src + '\n')
47 return {'Para': [{'Image': [[], [src,""]]}]}
49if __name__ == "__main__":
50 toJSONFilter(abc)