-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathlilypond.py
executable file
·160 lines (142 loc) · 4.39 KB
/
lilypond.py
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
#!/usr/bin/env python3
"""
Pandoc filter to process code blocks with class "ly" containing
Lilypond notation. Assumes that Lilypond and Ghostscript are
installed, plus [lyluatex](https://github.com/jperon/lyluatex) package for
LaTeX, with LuaLaTeX.
"""
import os
from sys import getfilesystemencoding, stderr
from subprocess import Popen, call, PIPE
from hashlib import sha1
from pandocfilters import toJSONFilter, stringify,\
Para, Image, RawInline, RawBlock
IMAGEDIR = "tmp_ly"
LATEX_DOC = """\\documentclass{article}
\\usepackage{libertine}
\\usepackage{lyluatex}
\\pagestyle{empty}
\\begin{document}
%s
\\end{document}
"""
def sha(x):
return sha1(x.encode(getfilesystemencoding())).hexdigest()
def latex(code):
"""LaTeX inline"""
return RawInline('latex', code)
def latexblock(code):
"""LaTeX block"""
return RawBlock('latex', code)
def ly2png(lily, outfile, kvs):
p = Popen([
"lilypond",
"-dno-point-and-click",
"-dbackend=eps",
"-djob-count=2",
"-ddelete-intermediate-files",
"-o", outfile,
"-"
], stdin=PIPE, stdout=stderr)
p.stdin.write(("\\paper{\n"
"indent=0\\mm\n"
"oddFooterMarkup=##f\n"
"oddHeaderMarkup=##f\n"
"bookTitleMarkup = ##f\n"
"scoreTitleMarkup = ##f\n"
"line-width = %s\n"
"}\n"
"#(set-global-staff-size %s)\n" % (
kvs['width'][:-2] + '\\' + kvs['width'][-2:],
kvs['staffsize']) +
lily).encode("utf-8"))
p.communicate()
p.stdin.close()
call([
"gs",
"-sDEVICE=pngalpha",
"-r144",
"-sOutputFile=" + outfile + '.png',
outfile + '.pdf',
], stdout=stderr)
def png(contents, kvs):
"""Creates a png if needed."""
outfile = os.path.join(IMAGEDIR, sha(contents + str(kvs['staffsize'])))
src = outfile + '.png'
if not os.path.isfile(src):
try:
os.mkdir(IMAGEDIR)
stderr.write('Created directory ' + IMAGEDIR + '\n')
except OSError:
pass
ly2png(contents, outfile, kvs)
stderr.write('Created image ' + src + '\n')
return src
def calc_params(kvs, meta):
if 'staffsize' not in kvs:
try:
kvs['staffsize'] = int(
meta['music']['c']['lilypond']['c']['staffsize']['c']
)
except (KeyError, TypeError):
kvs['staffsize'] = 20
if 'width' not in kvs:
try:
kvs['width'] = \
meta['music']['c']['lilypond']['c']['width']['c'][0]['c']
except (KeyError, TypeError):
kvs['width'] = '210mm'
return kvs
def lily(key, value, fmt, meta):
if key == 'Code':
[[ident, classes, kvs], contents] = value # pylint:disable=I0011,W0612
kvs = {key: value for key, value in kvs}
if "ly" in classes:
kvs = calc_params(kvs, meta)
if fmt == "latex":
if ident == "":
label = ""
else:
label = '\\label{' + ident + '}'
return latex(
'\\includely[staffsize=%s]{%s}' % (
kvs['staffsize'], contents
) +
label
)
else:
infile = contents + (
'.ly' if '.ly' not in contents else ''
)
with open(infile, 'r') as doc:
code = doc.read()
return [
Image(['', [], []],
[],
[png(code, kvs), ""]
)
]
if key == 'CodeBlock':
[[ident, classes, kvs], code] = value
kvs = {key: value for key, value in kvs}
if "ly" in classes:
kvs = calc_params(kvs, meta)
if fmt == "latex":
if ident == "":
label = ""
else:
label = '\\label{' + ident + '}'
return latexblock(
'\\lily[staffsize=%s]{%s}' % (kvs['staffsize'], code) +
label
)
else:
return Para([
Image(
['', [], []],
[],
[png(code, kvs), ""]
)
])
if __name__ == "__main__":
toJSONFilter(lily)