4 TODO: latex/paper parameters
12 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
15 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
17 minimal classic lilypond-book (WIP):
18 filter-lilypond-book --process="lilypond-bin" BOOK.tely
20 (([0-9][0-9])*pt) -> staffsize=\2
27 ################################################################
28 # Users of python modules should include this snippet
29 # and customize variables below.
31 # We'll suffer this path init stuff as long as we don't install our
32 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
33 # it as we do with teTeX on Red Hat Linux: set some environment var
34 # (PYTHONPATH) in profile)
36 # If set, LILYPONDPREFIX must take prevalence
37 # if datadir is not set, we're doing a build and LILYPONDPREFIX
38 import getopt, os, sys
39 datadir = '@local_lilypond_datadir@'
40 if not os.path.isdir (datadir):
41 datadir = '@lilypond_datadir@'
42 if os.environ.has_key ('LILYPONDPREFIX') :
43 datadir = os.environ['LILYPONDPREFIX']
44 while datadir[-1] == os.sep:
47 sys.path.insert (0, os.path.join (datadir, 'python'))
50 #if __name__ == '__main__':
57 program_version = '@TOPLEVEL_VERSION@'
58 #program_name = 'new-book'
59 program_name = 'filter-lilypond-book'
62 original_dir = os.getcwd ()
65 # help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
66 help_summary = _ ("""Process ly snippets from lilypond-book source. Example usage:
68 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
69 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
72 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
73 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
75 option_definitions = [
76 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
77 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
78 ('', 'h', 'help', _ ("print this help")),
79 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
80 ('', 'V', 'verbose', _ ("be verbose")),
81 ('', 'v', 'version', _ ("print version information")),
82 ('', 'w', 'warranty', _ ("show warranty and copyright")),
85 include_path = [os.getcwd ()]
87 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
89 # only use installed binary when we're installed too.
90 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
91 lilypond_binary = 'lilypond-bin'
96 filter_cmd = 'convert-ly --no-version --from=2.0.0 -'
98 #process_cmd = 'convert-ly --no-version --from=2.0.0'
107 ## lilypond-book heritage. to be cleaned
109 ################################################################
110 # Recognize special sequences in the input
113 # Warning: This uses extended regular expressions. Tread with care.
117 # (?P<name>regex) -- assign result of REGEX to NAME
118 # *? -- match non-greedily.
119 # (?m) -- multiline regex: make ^ and $ match at each line
120 # (?s) -- make the dot match all characters including newline
127 'preamble-end': no_match,
128 'landscape': no_match,
129 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
130 'verb': r'''(?P<code><pre>.*?</pre>)''',
131 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
132 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
133 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
134 'option-sep' : '\s*',
135 'intertext': r',?\s*intertext=\".*?\"',
136 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
137 'singleline-comment': no_match,
139 'multicols': no_match,
140 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
144 'input': r'(?m)^[^%\n]*?(?P<match>\\mbinput{?([^}\t \n}]*))',
145 'include': r'(?m)^[^%\n]*?(?P<match>\\mbinclude{(?P<filename>[^}]+)})',
146 'option-sep' : ',\s*',
147 'header': r"\n*\\documentclass\s*(\[.*?\])?",
148 'preamble-end': r'(?P<code>\\begin\s*{document})',
149 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
150 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
151 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
152 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
153 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
154 'def-post-re': r"\\def\\postLilyPondExample",
155 'def-pre-re': r"\\def\\preLilyPondExample",
156 'usepackage-graphics': r"\usepackage\s*{graphics}",
157 'intertext': r',?\s*intertext=\".*?\"',
158 'multiline-comment': no_match,
159 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
160 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
161 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
166 # why do we have distinction between @mbinclude and @include?
169 'include': '(?m)^[^%\n]*?(?P<match>@mbinclude\s+(?P<filename>\S*))',
172 'preamble-end': no_match,
173 'landscape': no_match,
174 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
175 'verb': r'''(?P<code>@code{.*?})''',
176 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
177 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
178 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
179 'option-sep' : ',\s*',
180 'intertext': r',?\s*intertext=\".*?\"',
181 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
182 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
184 'multicols': no_match,
190 PREAMBLE = 'preamble'
195 'relative': r'''\relative #(ly:make-pitch %(relative)s 0 0)'''
199 indent = %(indent)s''',
201 linewidth = %(linewidth)s''',
207 \remove Time_signature_engraver
210 raggedright = ##t''',
214 #(set-global-staff-size %(staffsize)s)''',
219 PREAMBLE_LY = r'''%% Generated by %(program_name)s
220 %% Options: [%(option_string)s]
222 \paper {%(paper_string)s
226 FRAGMENT_LY = r'''\score{
227 \notes%(notes_string)s{
233 def compose_ly (code, option_string):
234 m = re.search (r'''\\score''', code)
235 options = string.split (option_string, ',')
236 if not m and (not options \
237 or not 'nofragment' in options \
238 or 'fragment' in options):
249 preamble_options = []
251 if string.find (i, '=') > 0:
252 key, value = string.split (i, '=')
258 if key in ly_options[NOTES].keys ():
259 notes_options.append (ly_options[NOTES][key] % vars ())
260 elif key in ly_options[PREAMBLE].keys ():
261 preamble_options.append (ly_options[PREAMBLE][key] \
263 elif key in ly_options[PAPER].keys ():
264 paper_options.append (ly_options[PAPER][key] % vars ())
266 program_name = __main__.program_name
267 notes_string = string.join (notes_options, '\n ')
268 paper_string = string.join (paper_options, '\n ')
269 preamble_string = string.join (preamble_options, '\n ')
270 return (PREAMBLE_LY + body) % vars ()
292 # use lilypond-bin for latex (.lytex) books,
293 # and lilypond --preview for html, texinfo books?
295 cmd = r'latex "\nonstopmode \input %s"' % file
296 # Ugh. (La)TeX writes progress and error messages on stdout
298 cmd = '(( %s >&2 ) >&- )' % cmd
300 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
303 ## make source, index statics of Snippet?
307 def __init__ (self, type, index, match):
314 return self.index + self.match.start (s)
317 return self.index + self.match.end (s)
319 def substring (self, source, s):
320 return source[self.start (s):self.end (s)]
322 def ly (self, source):
323 if self.type == 'lilypond-block' or self.type == 'lilypond':
324 return compose_ly (self.substring (source, 'code'),
325 self.match.group ('options'))
328 def get_hash (self, source):
330 self.hash = abs (hash (self.substring (source,
334 def basename (self, source):
336 return 'lily-%d' % self.get_hash (source)
339 def write_ly (self, source):
340 h = open (self.basename (source) + '.ly', 'w')
341 h.write (self.ly (source))
344 def output_html (self, source):
345 base = self.basename (source)
346 h.write (output[HTML][BEFORE])
347 h.write ('<src image="%(base)s.png">' % vars ())
348 h.write (output[HTML][AFTER])
350 def output_latex (self, source):
351 h.write (output[HTML][BEFORE])
352 name = self.basename (source) + '.tex'
353 h.write (open (name).read ())
354 h.write (output[HTML][AFTER])
356 def output_texinfo (self, source):
358 self.output_latex (source)
359 h.write ('\n@end tex\n')
361 h.write ('\n@html\n')
362 self.output_html (source)
363 h.write ('\n@end html\n')
365 def outdated_p (self, source):
366 base = self.basename (source)
367 if os.path.exists (base + '.ly') \
368 and os.path.exists (base + '.tex') \
369 and (not use_hash_p \
370 or self.ly (source) == open (base + '.ly').read ()):
371 # TODO: something smart with target formats
372 # (ps, png) and m/ctimes
376 def find_snippets (s, type):
377 re = ly.re.compile (re_dict[format][type])
380 m = re.search (s[i:])
382 snippets.append (Snippet (type, i, m))
384 m = re.search (s[i:])
387 def filter_pipe (input, cmd):
389 ly.progress (_ ("Opening filter `%s\'") % cmd)
391 stdin, stdout, stderr = os.popen3 (cmd)
393 status = stdin.close ()
397 output = stdout.read ()
398 status = stdout.close ()
399 error = stderr.read ()
403 signal = 0x0f & status
404 if status or (not output and error):
405 exit_status = status >> 8
406 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
407 ly.error (_ ("The error log is as follows:"))
408 sys.stderr.write (error)
409 sys.stderr.write (stderr.read ())
418 return filter_pipe (s, filter_cmd)
420 def compare_index (a, b):
421 return a.start (0) - b.start (0)
423 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
424 # snippets are skipped. return list with all non-empty return values
427 # Hmm, do we need enclosed snippets at all? Maybe use MAP_SNIPPETS
428 # once and use simple filter/map on that resulting toplevel list iso
429 # silly map_snippets/do_snippets.
430 def map_snippets (source, snippets, func):
435 if i.start (0) < index:
437 # lst.append (func (i, source))
444 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
445 # snippets are skipped. return last snippet's index
446 def do_snippets (source, snippets, func):
450 if i.start (0) < index:
454 #index = i.end ('code')
457 def process_snippets (source, snippets, cmd):
458 names = map_snippets (source, snippets, Snippet.basename)
460 ly.system (string.join ([cmd] + names))
462 if format == HTML or format == TEXINFO:
465 ly.make_ps_images (i + '.eps', resolution=110)
467 LATEX_DOCUMENT = r'''
470 \typeout{columnsep=\the\columnsep}
471 \typeout{textwidth=\the\textwidth}
474 #need anything else besides textwidth?
475 def get_latex_parameters (source):
476 snippet, = find_snippets (source, 'preamble-end')
477 latex_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
478 preamble = source[:snippet.start (0)]
479 latex_document = LATEX_DOCUMENT % vars ()
480 parameter_string = filter_pipe (latex_document, latex_cmd)
483 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
485 columnsep = string.atof (m.group (1))
488 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
490 textwidth = string.atof (m.group (1))
492 textwidth -= columnsep
497 def do_file (input_filename):
511 e = os.path.splitext (input_filename)[1]
512 if e in ext2format.keys ():
513 format = ext2format[e]
515 ly.error (_ ("cannot determine format for: %s" \
521 if input_filename != '-':
522 h = open (input_filename)
525 #snippet_types = ('lilypond', 'lilypond-block')
526 snippet_types = ('verbatim', 'verb', 'multiline-comment',
527 'lilypond', 'lilypond-block')
529 for i in snippet_types:
530 snippets += find_snippets (source, i)
532 snippets.sort (compare_index)
536 def filter_source (snippet, source):
538 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
539 #if snippet.match.group ('code'):
541 if snippet.type == 'lilypond' or snippet.type == 'lilypond-block':
542 h.write (source[index:snippet.start ('code')])
543 h.write (run_filter (snippet.substring (source, 'code')))
544 h.write (source[snippet.end ('code'):snippet.end (0)])
546 h.write (source[index:snippet.end (0)])
547 index = snippet.end (0)
551 snippet_output = eval ("Snippet.output_" + format)
552 def compile_output (snippet, source):
554 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
555 # if snippet.match.group ('code'):
557 if snippet.type == 'lilypond' \
558 or snippet.type == 'lilypond-block':
559 h.write (source[index:snippet.start (0)])
560 snippet_output (snippet, source)
561 index = snippet.end (0)
564 textwdith = get_latex_parameters (source)
565 #TODO: set global option
569 index = do_snippets (source, snippets, filter_source)
570 h.write (source[index:])
572 outdated = map_snippets (source, snippets, Snippet.outdated_p)
573 do_snippets (source, snippets, Snippet.write_ly)
574 process_snippets (source, outdated, process_cmd)
575 do_snippets (source, snippets, compile_output)
576 h.write (source[index:])
580 global filter_cmd, process_cmd, verbose_p
582 (sh, long) = ly.getopt_args (option_definitions)
584 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
585 except getopt.error, s:
586 sys.stderr.write ('\n')
587 ly.error (_ ("getopt says: `%s\'" % s))
588 sys.stderr.write ('\n')
598 elif o == '--version' or o == '-v':
599 ly.identify (sys.stdout)
601 elif o == '--verbose' or o == '-V':
603 elif o == '--filter' or o == '-F':
606 elif o == '--format' or o == '-f':
610 elif o == '--help' or o == '-h':
613 elif o == '--process' or o == '-P':
616 elif o == '--warranty' or o == '-w':
623 files = do_options ()
624 ly.identify (sys.stderr)
625 ly.setup_environment ()
629 if __name__ == '__main__':